React Router library mode
You will learn the following:
- Install
@clerk/react-router
- Set your Clerk API keys
- Add
<ClerkProvider>
- Protect your pages
Before you start
React Router can be used as a framework or as a standalone library. This guide explains how to add React Router authentication to an existing React application using library mode. To use React Router as a framework instead, see the React Router quickstart.
Install @clerk/react-router
The Clerk React Router SDK provides prebuilt components, hooks, and stores to make it easy to integrate authentication and user management in your React Router app.
Run the following command to install the SDK:
npm install @clerk/react-router
yarn add @clerk/react-router
pnpm add @clerk/react-router
bun add @clerk/react-router
Add your Clerk Publishable Key to your .env
file. This key can always be retrieved from the API keys page of the Clerk Dashboard.
- In the Clerk Dashboard, navigate to the API keys page.
- In the Quick Copy section, copy your Clerk Publishable Key.
- Add your key to your
.env
file.
The final result should resemble the following:
VITE_CLERK_PUBLISHABLE_KEY=YOUR_PUBLISHABLE_KEY
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.
You must pass your Publishable Key as a prop, as shown in the following example:
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { BrowserRouter, Routes, Route } from 'react-router'
import { ClerkProvider } from '@clerk/react-router'
import './index.css'
import App from './App.tsx'
const PUBLISHABLE_KEY = import.meta.env.VITE_CLERK_PUBLISHABLE_KEY
createRoot(document.getElementById('root')!).render(
<StrictMode>
<BrowserRouter>
<ClerkProvider publishableKey={PUBLISHABLE_KEY}>
<Routes>
<Route path="/" element={<App />} />
</Routes>
</ClerkProvider>
</BrowserRouter>
</StrictMode>,
)
Create a header with Clerk components
You can control which content signed-in and signed-out users can see with the prebuilt control components. The following example creates a header using the following 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 or displays the sign-in modal.
import { SignInButton, SignedIn, SignedOut, UserButton } from '@clerk/react-router'
export default function App() {
return (
<header>
<SignedOut>
<SignInButton />
</SignedOut>
<SignedIn>
<UserButton />
</SignedIn>
</header>
)
}
Feedback
Last updated on