React Router library mode
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
Run the following command to install the SDK:
npm install @clerk/react-routeryarn add @clerk/react-routerpnpm add @clerk/react-routerbun add @clerk/react-routerAdd 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
.envfile.
The final result should resemble the following:
VITE_CLERK_PUBLISHABLE_KEY=YOUR_PUBLISHABLE_KEYAdd <ClerkProvider> to your app
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