Docs

React Router library mode

Warning

The React Router SDK is currently in beta.

You will learn the following:

  • Install @clerk/react-router
  • Set your Clerk API keys
  • Add <ClerkProvider>
  • Protect your pages

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

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.

Run the following command to install the SDK:

terminal
npm install @clerk/react-router
terminal
yarn add @clerk/react-router
terminal
pnpm add @clerk/react-router

Note

You will not need the Clerk Secret Key in React Router's library mode, as it should never be used on the client-side.

.env
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:

src/main.tsx
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.
src/App.tsx
import { SignInButton, SignedIn, SignedOut, UserButton } from '@clerk/react-router'

export default function App() {
  return (
    <header>
      <SignedOut>
        <SignInButton />
      </SignedOut>
      <SignedIn>
        <UserButton />
      </SignedIn>
    </header>
  )
}

Feedback

What did you think of this content?

Last updated on