React Router Quickstart (Beta)
You will learn the following:
- Install
@clerk/react-router
- Set your Clerk API keys
- Configure
rootAuthLoader()
- Add
<ClerkProvider>
and Clerk components
Before you start
Example repository
Clerk's React Router SDK provides prebuilt components, hooks, and stores to make it easy to integrate authentication and user management in your React Router app. This guide assumes that you're using React Router v7 or later.
Install @clerk/react-router
Run the following command to install the SDK:
Add the following keys to your .env
file. These keys can always be retrieved from the API keys page in the Clerk Dashboard.
- In the Clerk Dashboard, navigate to the API keys page.
- In the Quick Copy section, copy your Clerk Publishable and Secret Key.
- Paste your keys into your
.env
file.
The final result should resemble the following:
Configure rootAuthLoader()
The rootAuthLoader()
function provides access to authentication state in any React Router route.
The following code shows how to add this function to your root.tsx
file. If you're using Clerk's React Router quickstart or the React Router template, most of this code will already be present.
To load additional data or configure options, see the rootAuthLoader()
reference.
The <ClerkProvider>
component provides session and user context to Clerk's hooks and components. It's recommended to wrap your entire app at the entry point with <ClerkProvider>
to make authentication globally accessible. See the reference docs for other configuration options.
It's required to pass loaderData
to the <ClerkProvider>
component. This data is provided by the rootAuthLoader()
function. It's also recommended to pass the signUpFallbackRedirectUrl
and signInFallbackRedirectUrl
props. These specify the fallback URL to redirect to after the user signs up or signs in, respectively, if there's no redirect_url
in the path already.
You can control which content signed-in and signed-out users can see with Clerk's prebuilt control components.
The following example adds <ClerkProvider>
and creates a header using the following Clerk components:
<SignedIn>
: Children of this component can only be seen while signed in.<SignedOut>
: Children of this component can only be seen while signed out.<UserButton />
: Shows the signed-in user's avatar. Selecting it opens a dropdown menu with account management options.<SignInButton />
: An unstyled component that links to the sign-in page. In this example, since no props or environment variables are set for the sign-in URL, this component links to the Account Portal sign-in page.
Create your first user
Run your project with the following command:
Visit your app's homepage at http://localhost:5173
. Sign up to create your first user.
Feedback
Last updated on