React Router can be used in different modes: declarative, data, or framework. This tutorial explains how to use React Router in framework mode. To use React Router in declarative mode instead, see the dedicated guide.
This tutorial assumes that you're using React Router v7.1.2 or later in framework mode.
While an upstream issue is being fixed, you must add @clerk/react-router to the ssr.noExternal array in your vite.config.ts file. Without it, every page fails during server-side rendering in development with Error: useNavigate() may be used only in the context of a <Router> component. — even though npm ls react-router shows a single installed copy.
clerkMiddleware()React Router Icon grants you access to user authentication state throughout your app. It also allows you to protect specific routes from unauthenticated users. To add clerkMiddleware() to your app, follow these steps:
Important
If you're using React Router v7, enable the v8_middleware future flag in your react-router.config.ts file.
By default, clerkMiddleware() will not protect any routes. All routes are public and you must opt-in to protection for routes. See the clerkMiddleware() referenceReact Router Icon to learn how to require authentication for specific routes.
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.
Copy and paste the following code into your root.tsx file. This:
Adds the <ClerkProvider> to your app, providing Clerk's authentication context to your app. Pass loaderData to the provider so it can access the authentication data loaded by rootAuthLoader().
Creates a header with Clerk's prebuilt components to allow users to sign in and out, and display different content for signed-in and signed-out users.
Select "Sign up" on the page and authenticate to create your first user.
Important
To make configuration changes to your Clerk development instance, claim the Clerk keys that were generated for you by selecting Configure your application in the bottom right of your app. This will associate the application with your Clerk account. Once claimed, you can find your Publishable Key and Secret Key any time on the API keys page in the Clerk Dashboard.