Use Clerk with RedwoodJS
Learn how to use Clerk to quickly and easily add secure authentication and user management to your RedwoodJS application.
Create a RedwoodJS application
terminalnpm create redwood-app my-redwood-project --typescript
terminalyarn create redwood-app my-redwood-project --typescript
terminalpnpm create redwood-app my-redwood-project --typescript
Set environment variables
Below is an example of an .env.local
file.
Pro tip! If you are signed into your Clerk Dashboard, your secret key should become visible by clicking on the eye icon. Otherwise, you can find your keys in the Clerk Dashboard on the API Keys(opens in a new tab) page.
.env.localCLERK_PUBLISHABLE_KEY={{pub_key}} CLERK_SECRET_KEY={{secret}}
Update redwood.toml
redwood.toml[web] includeEnvironmentVariables = ['CLERK_PUBLISHABLE_KEY']
Set up Redwood auth
The next step is to run a Redwood CLI command to install the required packages and generate some boilerplate code:
my-redwood-projectyarn rw setup auth clerk --force
The --force
flag is needed to overwrite the existing dbAuth logic, that is set by default.
You can now access Clerk functions through the Redwood useAuth()
hook, which is exported from src/web/auth.tsx
, or you can use the Clerk components directly.
Protecting your pages
Below is an example of using the useAuth()
hook to verify if the user is authenticated. This will open a modal for your user to sign in to their account.
index.tsximport { useAuth } from '../../auth' const HomePage = () => { const { currentUser, isAuthenticated, logIn, logOut } = useAuth() return ( <> {isAuthenticated ? ( <button onClick={logOut}>Log out</button> <h1>Hello {currentUser.firstName}</h1> ) : ( <button onClick={logIn}>Log in</button> )} </> ) } export default HomePage
Using Clerk components directly
index.tsximport { SignInButton, UserButton } from '@clerk/clerk-react' import { useAuth } from '../../auth' const HomePage = () => { const { currentUser, isAuthenticated } = useAuth() return ( <> {isAuthenticated ? ( <UserButton afterSignOutUrl={window.location.href} /> <h1>Hello {currentUser.firstName}</h1> ) : ( <SignInButton mode="modal" /> )} </> ) }
Next steps
Now that you have an application integrated with Clerk, you will want to read the following documentation:
Last updated on March 1, 2024