### Install and Start Development Server
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/quick-start-guide.md
Install project dependencies using pnpm and start the development server. The server typically runs at http://localhost:5173.
```bash
# Install dependencies
pnpm install
# Start dev server
pnpm run dev
# Server runs at http://localhost:5173
```
--------------------------------
### Run Docker Image
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/project-overview.md
Builds and runs the Docker image for the Clerk React Router quickstart application. Ensure Docker is installed and running.
```bash
docker build -t clerk-rr-quickstart .
docker run -p 3000:3000 clerk-rr-quickstart
```
--------------------------------
### Traditional Node.js Deployment Steps
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/app-structure.md
Provides the sequence of commands for deploying a Clerk React Router application to a traditional Node.js environment. This includes installing production dependencies, building the app, and starting the server.
```text
1. Run: pnpm install --prod
2. Run: pnpm run build
3. Run: pnpm run start
4. Server listens on port 3000 (default)
5. Proxy requests through nginx/Apache if needed
```
--------------------------------
### Clone the Clerk React Router Quickstart Repository
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/README.md
Clone the official Clerk React Router quickstart repository to begin. This sets up the project structure for local development.
```bash
git clone https://github.com/clerk/clerk-react-router-quickstart
```
--------------------------------
### Start Development Server
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/configuration.md
Starts the development server with hot module replacement, type checking, and server-side rendering enabled. Accessible at http://localhost:5173.
```bash
pnpm run dev
```
--------------------------------
### Install pnpm Package Manager
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/quick-start-guide.md
Install the pnpm package manager globally if you haven't already.
```bash
npm install -g pnpm
```
--------------------------------
### Loader-Only Setup (Not Recommended)
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/clerk-server.md
This setup is not recommended because it lacks request validation before route execution and requires the client to fetch auth data after hydration.
```typescript
// Not recommended because:
// 1. No request validation before route execution
// 2. Client must fetch auth data after hydration
export const loader = (args: Route.LoaderArgs) => rootAuthLoader(args)
```
--------------------------------
### Full Example: Protected Admin Dashboard
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/middleware-and-loaders.md
This example demonstrates setting up Clerk middleware and loaders for a protected admin dashboard. It includes route protection, role checking, and data fetching for authenticated administrators.
```typescript
// app/root.tsx
import { clerkMiddleware, rootAuthLoader } from '@clerk/react-router/server'
import { ClerkProvider } from '@clerk/react-router'
import type { Route } from './+types/root'
export const middleware: Route.MiddlewareFunction[] = [clerkMiddleware()]
export const loader = (args: Route.LoaderArgs) => rootAuthLoader(args)
export default function Root({ loaderData }: Route.ComponentProps) {
return (
)
}
// app/routes/admin.tsx
import type { Route } from './+types/admin'
import { isRouteErrorResponse } from 'react-router'
export const loader = async ({ context }: Route.LoaderArgs) => {
const clerkAuth = context.clerkAuth as any
// Check authentication
if (!clerkAuth?.userId) {
throw new Response('Unauthorized', { status: 401 })
}
// Check admin role (would typically come from database/API)
const userRole = await fetch(`/api/users/${clerkAuth.userId}/role`)
.then(r => r.json())
if (userRole.role !== 'admin') {
throw new Response('Forbidden', { status: 403 })
}
// Fetch admin data
const adminData = await fetch(`/api/admin/dashboard`)
.then(r => r.json())
return { adminData, userId: clerkAuth.userId }
}
export default function Admin({ loaderData }: Route.ComponentProps) {
return (
Admin Dashboard
{JSON.stringify(loaderData.adminData, null, 2)}
)
}
export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
if (isRouteErrorResponse(error)) {
if (error.status === 401) {
return
Please log in to access the admin panel.
}
if (error.status === 403) {
return
You don't have permission to access the admin panel.
}
}
return
Error loading admin panel.
}
```
--------------------------------
### Basic Clerk Middleware Setup
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/clerk-server.md
Integrate Clerk authentication middleware into your root route for session validation and context injection. This is the most basic setup.
```typescript
import { clerkMiddleware } from '@clerk/react-router/server'
import type { Route } from './+types/root'
export const middleware: Route.MiddlewareFunction[] = [clerkMiddleware()]
export default function App() {
return (
{/* Application content */}
)
}
```
--------------------------------
### Basic Setup in Root Route
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/clerk-server.md
Demonstrates how to use `rootAuthLoader` in your root route's loader function and pass the resulting data to `ClerkProvider`.
```typescript
import { rootAuthLoader } from '@clerk/react-router/server'
import { ClerkProvider } from '@clerk/react-router'
import type { Route } from './+types/root'
export const loader = (args: Route.LoaderArgs) => rootAuthLoader(args)
export default function App({ loaderData }: Route.ComponentProps) {
return (
{/* Header with auth-dependent UI */}
{/* Application routes */}
)
}
```
--------------------------------
### Clerk Middleware Setup
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/clerk-server.md
Demonstrates how to set up the clerkMiddleware for session validation without client-side auth context.
```APIDOC
## Middleware-Only Setup (Without Loader)
### Description
This setup uses `clerkMiddleware()` to validate sessions on every request without providing authentication data to the client.
### Usage
```typescript
import { clerkMiddleware } from "@clerk/nextjs/server";
export const middleware = [clerkMiddleware()];
// No loader needed; authentication is validated but not passed to client
```
```
--------------------------------
### ClerkProvider Setup for React Router
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/quick-start-guide.md
Wrap your entire application with ClerkProvider to enable authentication context. This setup is typically done in your root component file.
```typescript
import { ClerkProvider, rootAuthLoader } from '@clerk/react-router/server'
export const loader = (args: Route.LoaderArgs) => rootAuthLoader(args)
export default function App({ loaderData }: Route.ComponentProps) {
return (
{/* Your app here */}
)
}
```
--------------------------------
### Project Directory Structure
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/project-overview.md
Illustrates the file and folder organization for the Clerk React Router quickstart project. This structure helps in understanding the placement of different configuration files, route handlers, and components.
```tree
clerk-react-router-quickstart/
├── app/
│ ├── root.tsx # Root component with middleware and provider
│ ├── routes.ts # Route configuration
│ ├── routes/
│ │ └── home.tsx # Home route handler
│ ├── welcome/
│ │ └── welcome.tsx # Welcome component
│ └── app.css # Global styles
├── public/ # Static assets
├── package.json # Dependencies and scripts
├── tsconfig.json # TypeScript configuration
├── react-router.config.ts # React Router configuration
├── vite.config.ts # Vite build configuration
├── .env.example # Environment variable template
└── Dockerfile # Docker deployment configuration
```
--------------------------------
### Standard Route Usage Examples
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/react-router.md
Provides examples of using the route function to define routes for specific paths, including dynamic parameters and a catch-all route for not found pages.
```typescript
[
route('users', 'routes/users.tsx'),
route('users/:id', 'routes/user-detail.tsx'),
route('*', 'routes/not-found.tsx')
]
```
--------------------------------
### Copy .env.example to .env.local
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/configuration.md
This bash command copies the example environment file to `.env.local`, which is used for local development configuration. Ensure `.env.local` is added to your `.gitignore`.
```bash
cp .env.example .env.local
```
--------------------------------
### Install Specific pnpm Version
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/configuration.md
Use this npm command to globally install a specific version of `pnpm`, such as 10.33.4.
```bash
npm install -g pnpm@10.33.4
```
--------------------------------
### Middleware-Only Setup
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/clerk-server.md
Use this setup if you need session validation without client-side auth context. The authentication is validated but not passed to the client.
```typescript
export const middleware: Route.MiddlewareFunction[] = [clerkMiddleware()]
// No loader needed; authentication is validated but not passed to client
```
--------------------------------
### Meta Function Usage Example
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/react-router.md
Example of how to use the Route.MetaArgs interface in a meta function to define document head meta tags.
```typescript
// app/routes/home.tsx
export function meta({}: Route.MetaArgs) {
return [
{ title: "Home" },
{ name: "description", content: "Welcome to our app" }
]
}
```
--------------------------------
### Middleware Function Usage Example
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/react-router.md
Example of defining middleware using the Route.MiddlewareFunction type, typically including clerkMiddleware.
```typescript
export const middleware: Route.MiddlewareFunction[] = [clerkMiddleware()]
```
--------------------------------
### Layout Route Usage Example
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/react-router.md
Demonstrates how to use the layout function to define a layout route for authentication, including sign-in and sign-up child routes.
```typescript
[
layout('routes/auth-layout.tsx', [
index('routes/signin.tsx'),
route('signup', 'routes/signup.tsx')
])
]
```
--------------------------------
### Client-Only Module Example
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/app-structure.md
This code snippet shows how to import and use client-only modules. Files ending with `.client.*` are exclusively loaded on the client.
```typescript
// Only imported client-side
import { useClerk } from '@clerk/react'
```
--------------------------------
### Complete Root Layout with Clerk Authentication
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/react-router.md
This comprehensive example demonstrates setting up a root layout in a React Router application with Clerk authentication. It includes middleware, root auth loader, CSS links, layout component, main app component with ClerkProvider, and an error boundary that uses `isRouteErrorResponse`.
```typescript
// app/root.tsx
import {
ClerkProvider,
Show,
SignInButton,
UserButton
} from '@clerk/react-router'
import {
clerkMiddleware,
rootAuthLoader
} from '@clerk/react-router/server'
import {
isRouteErrorResponse,
Links,
Meta,
Outlet,
Scripts,
ScrollRestoration
} from 'react-router'
import type { Route } from './+types/root'
import stylesheet from './app.css?url'
export const middleware: Route.MiddlewareFunction[] = [clerkMiddleware()]
export const loader = (args: Route.LoaderArgs) => rootAuthLoader(args)
export const links: Route.LinksFunction = () => [
{ rel: 'stylesheet', href: stylesheet }
]
export function Layout({ children }: { children: React.ReactNode }) {
return (
{children}
)
}
export default function App({ loaderData }: Route.ComponentProps) {
return (
MyApp
)
}
export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
let message = 'Oops!'
let details = 'An unexpected error occurred.'
if (isRouteErrorResponse(error)) {
message = error.status === 404 ? '404' : 'Error'
details = error.status === 404
? 'The requested page could not be found.'
: error.statusText || details
}
return (
{message}
{details}
)
}
```
--------------------------------
### Check Installed pnpm Version
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/configuration.md
Run this bash command to check the currently installed version of the `pnpm` package manager.
```bash
pnpm --version
```
--------------------------------
### Server-Only Module Example
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/app-structure.md
This code snippet demonstrates how to import and use server-only modules. Files ending with `.server.*` are exclusively loaded on the server.
```typescript
// Only imported server-side
import { clerkMiddleware } from '@clerk/react-router/server'
export const middleware = [clerkMiddleware()]
```
--------------------------------
### Index Route Usage Examples
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/react-router.md
Demonstrates how to use the index function to define an index route for the root path or nested within a layout route.
```typescript
// Routes home component at '/'
[index("routes/home.tsx")]
// Routes to parent URL without additional path segment
[
{
path: "/dashboard",
component: DashboardLayout,
children: [
index("routes/dashboard-home.tsx") // Matches /dashboard
]
}
]
```
--------------------------------
### Test Clerk Loaders
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/middleware-and-loaders.md
Example of how to test Clerk loaders by calling them with a mock request and context.
```typescript
// Loader test
const testLoader = async () => {
const loaderData = await rootAuthLoader({
request: new Request('http://localhost/'),
context: { clerkAuth: { userId: 'user_123' } }
})
// Assert loaderData.user exists
}
```
--------------------------------
### Test Clerk Middleware
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/middleware-and-loaders.md
Example of how to test Clerk middleware by creating a mock request and context.
```typescript
// Middleware test
const testMiddleware = async () => {
const request = new Request('http://localhost/test')
const context = { clerkAuth: { userId: 'user_123' } }
const middleware = clerkMiddleware()
const response = await middleware({ request, next: () => new Response('OK'), context })
// Assert response
}
```
--------------------------------
### Vercel Deployment Structure
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/app-structure.md
Outlines the essential files and directories for deploying a Clerk React Router application to Vercel. Vercel automates dependency installation, build processes, and serving of static and SSR assets.
```text
Root: /
Files to deploy:
- package.json
- build/ (generated)
- public/ (static assets)
- node_modules/ (not needed, installed by Vercel)
```
--------------------------------
### Complete Root Route Configuration with Clerk
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/clerk-server.md
This snippet shows the full setup for a root route file (`app/root.tsx`) using Clerk with React Router. It includes setting up middleware for request validation, a root loader to fetch authentication data, and the main `ClerkProvider` component. It also demonstrates how to conditionally render `SignInButton` and `UserButton` based on the user's authentication state.
```typescript
// app/root.tsx
import {
ClerkProvider,
SignInButton,
Show,
UserButton
} from '@clerk/react-router'
import {
clerkMiddleware,
rootAuthLoader
} from '@clerk/react-router/server'
import type { Route } from './+types/root'
import { Outlet } from 'react-router'
// Step 1: Set up middleware for request validation
export const middleware: Route.MiddlewareFunction[] = [
clerkMiddleware({
signInUrl: '/signin',
signUpUrl: '/signup'
})
]
// Step 2: Set up loader to fetch auth data
export const loader = (args: Route.LoaderArgs) => rootAuthLoader(args)
// Step 3: Create root component with ClerkProvider
export default function Root({ loaderData }: Route.ComponentProps) {
return (
)
}
// Step 4: Use auth components in child components
function Header() {
return (
)
}
```
--------------------------------
### Route Loader Usage Example
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/react-router.md
Illustrates how to use Route.LoaderArgs within a loader function to access request details, parameters, and context, including Clerk authentication.
```typescript
// app/root.tsx
import { rootAuthLoader } from '@clerk/react-router/server'
import type { Route } from './+types/root'
export const loader = (args: Route.LoaderArgs) => {
// Access request, params, context
return rootAuthLoader(args)
}
```
--------------------------------
### Route Component Usage Example
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/react-router.md
Shows how to use Route.ComponentProps in a React component to access loader data and URL parameters, and render the outlet for nested routes.
```typescript
// app/routes/home.tsx
import type { Route } from "./+types/home"
export default function Home({ loaderData, params }: Route.ComponentProps) {
return (
Home
{loaderData &&
Data: {loaderData}
}
)
}
```
--------------------------------
### Usage of MetaFunction in a Route
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/react-router.md
Example of implementing the MetaFunction in a route to set the page title and description.
```typescript
// app/routes/home.tsx
import type { Route } from "./+types/home"
export function meta({}: Route.MetaArgs) {
return [
{ title: "Home - MyApp" },
{ name: "description", content: "Welcome to MyApp" }
]
}
```
--------------------------------
### ClerkProvider Usage Example
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/clerk-components.md
Wrap your root component with ClerkProvider to provide authentication context. Ensure it receives loaderData from rootAuthLoader().
```typescript
import { ClerkProvider, rootAuthLoader } from '@clerk/react-router/server'
import type { Route } from './+types/root'
export const loader = (args: Route.LoaderArgs) => rootAuthLoader(args)
export default function App({ loaderData }: Route.ComponentProps) {
return (
{/* Other components here */}
{/* Application routes */}
)
}
```
--------------------------------
### Usage of LinksFunction in Root Route
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/react-router.md
Example of implementing the LinksFunction in a root route to include preconnect and stylesheet links.
```typescript
// app/root.tsx
import type { Route } from './+types/root'
import stylesheet from './app.css?url'
export const links: Route.LinksFunction = () => [
{ rel: 'preconnect', href: 'https://fonts.googleapis.com' },
{ rel: 'stylesheet', href: stylesheet }
]
```
--------------------------------
### ErrorBoundary Component Usage Example
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/react-router.md
Example of implementing an ErrorBoundary component using Route.ErrorBoundaryProps to display error messages.
```typescript
export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
return (
)
}
```
--------------------------------
### Build Docker Image
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/quick-start-guide.md
Build a Docker image for your application, tagged as `myapp`.
```bash
docker build -t myapp .
```
--------------------------------
### Create Production Build
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/configuration.md
Creates an optimized production build including type generation, type checking, code minification, and splitting. Output is placed in the ./build/ directory.
```bash
pnpm run build
```
--------------------------------
### Run Production Server
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/configuration.md
Runs the production server, serving the built application from ./build/server/index.js. Requires the @react-router/serve package and loads environment variables from .env.local.
```bash
pnpm run start
```
--------------------------------
### Welcome Component Imports
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/app-structure.md
Imports necessary logo assets for the Welcome component, supporting both light and dark themes.
```typescript
import logoDark from "./logo-dark.svg"
import logoLight from "./logo-light.svg"
```
--------------------------------
### Docker Deployment Structure
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/app-structure.md
Describes the multi-stage Docker build process for a Clerk React Router application. This includes stages for development, production dependencies, building the application, and the final runtime environment.
```text
Dockerfile uses multi-stage build:
1. Development dependencies stage
2. Production dependencies stage
3. Build stage (runs pnpm run build)
4. Runtime stage (Node.js Alpine)
Command: npm run start
Runs: react-router-serve ./build/server/index.js
```
--------------------------------
### Run Docker Container
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/quick-start-guide.md
Run your Docker container, mapping environment variables and port 3000.
```bash
docker run \
-e VITE_CLERK_PUBLISHABLE_KEY=pk_test_... \
-e CLERK_SECRET_KEY=sk_test_... \
-p 3000:3000 \
myapp
```
--------------------------------
### Environment Variables Configuration
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/quick-start-guide.md
Define required Clerk environment variables for frontend and backend.
```bash
# Required
VITE_CLERK_PUBLISHABLE_KEY=pk_test_... # Frontend key
CLERK_SECRET_KEY=sk_test_... # Backend key
```
--------------------------------
### Root Entry Point Configuration (`app/root.tsx`)
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/app-structure.md
This snippet shows the exports from the `app/root.tsx` file, including middleware, root loader, document head links, layout component, main application component, and error boundary. It demonstrates how to integrate Clerk's authentication middleware and loaders within a React Router application.
```typescript
import { ClerkProvider, Show, UserButton, SignInButton } from '@clerk/react-router'
import { isRouteErrorResponse, Links, Meta, Outlet, Scripts, ScrollRestoration } from 'react-router'
import { clerkMiddleware, rootAuthLoader } from '@clerk/react-router/server'
import type { Route } from './+types/root'
import stylesheet from './app.css?url'
```
```typescript
// Middleware array
export const middleware: Route.MiddlewareFunction[] = [clerkMiddleware()]
// Root loader
export const loader = (args: Route.LoaderArgs) => rootAuthLoader(args)
// Document head links
export const links: Route.LinksFunction = () => [
{ rel: 'preconnect', href: 'https://fonts.googleapis.com' },
{ rel: 'preconnect', href: 'https://fonts.gstatic.com', crossOrigin: 'anonymous' },
{ rel: 'stylesheet', href: 'https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap' },
{ rel: 'stylesheet', href: stylesheet }
]
```
```typescript
// HTML layout component
export function Layout({ children }: { children: React.ReactNode }): React.ReactElement
// Root application component
export default function App({ loaderData }: Route.ComponentProps): React.ReactElement
// Error boundary for unhandled errors
export function ErrorBoundary({ error }: Route.ErrorBoundaryProps): React.ReactElement
```
--------------------------------
### Wrap App with ClerkProvider
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/quick-start-guide.md
Ensure your entire application is wrapped with `` in `app/root.tsx` to initialize Clerk.
```typescript
export default function App({ loaderData }: Route.ComponentProps) {
return (
{/* Must wrap everything */}
)
}
```
--------------------------------
### Home Route Component
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/app-structure.md
The main component for the home route. It renders the `Welcome` component, which displays the landing page UI.
```typescript
import type { Route } from "./+types/home"
import { Welcome } from "../welcome/welcome"
export default function Home(): React.ReactElement {
return
}
```
--------------------------------
### Enable Server-Side Rendering and V8 Middleware
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/project-overview.md
Configure server-side rendering and enable the v8 middleware API in your React Router setup. This snippet is used in `react-router.config.ts`.
```typescript
export default {
ssr: true,
future: {
v8_middleware: true,
},
} satisfies Config
```
--------------------------------
### Loader Fetching Without Caching
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/middleware-and-loaders.md
Loaders run once per navigation and their results are not cached between navigations. This example shows a fetch operation that executes every time the route loads.
```typescript
export const loader = async ({ context }: Route.LoaderArgs) => {
// This fetch runs every time the route loads
const data = await fetch(`/api/data`)
return { data: await data.json() }
}
```
--------------------------------
### Meta
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/react-router.md
Renders meta tags from `meta` functions. This component should be placed in your root layout's head.
```APIDOC
## Meta
### Description
Renders meta tags from `meta` functions. This component should be placed in your root layout's head.
### Signature
```typescript
export function Meta(): React.ReactElement
```
```
--------------------------------
### Specify pnpm Package Manager
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/configuration.md
This JSON snippet in `package.json` specifies `pnpm` version 10.33.4 as the required package manager. This ensures consistent dependency installation across different development environments.
```json
{
"packageManager": "pnpm@10.33.4+sha512.1c67b3b359b2d408119ba1ed289f34b8fc3c6873412bec6fd264fbdc82489e510fcbecb9ce9d22dae7f3b76269d8441046014bdca53b9979cd7a561ad631b800"
}
```
--------------------------------
### clerkMiddleware with Options
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/middleware-and-loaders.md
Configures `clerkMiddleware` with specific options such as sign-in and sign-up URLs, and Clerk publishable and secret keys.
```typescript
export const middleware: Route.MiddlewareFunction[] = [
clerkMiddleware({
signInUrl: '/auth/signin',
signUpUrl: '/auth/signup',
publishableKey: process.env.VITE_CLERK_PUBLISHABLE_KEY,
secretKey: process.env.CLERK_SECRET_KEY
})
]
```
--------------------------------
### Initial Page Request Data Flow
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/app-structure.md
Illustrates the sequence of events from a user visiting a page to the application rendering with authentication context. This flow involves React Router, Clerk middleware, loader functions, and component rendering.
```text
User visits /
↓
React Router matches index route → home.tsx
↓
Root middleware executes
↓
clerkMiddleware() validates session token
↓
Root loader executes
↓
rootAuthLoader() fetches user data from Clerk
↓
loaderData returned to component
↓
ClerkProvider receives loaderData
↓
App component renders with auth context
↓
Home component renders (wrapped by ClerkProvider)
↓
Show component checks auth state
↓
SignInButton or UserButton renders
↓
Client hydration completes
```
--------------------------------
### Type-Safe Auth Data with Clerk Hooks
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/quick-start-guide.md
This example illustrates how to use Clerk's `useUser` hook to access user data in a type-safe manner within a React component. It handles loading and sign-in states and ensures user properties are correctly typed.
```typescript
import { useUser } from '@clerk/react'
export default function Profile() {
const { user, isLoaded, isSignedIn } = useUser()
// All are properly typed
if (!isLoaded) return null
if (!isSignedIn) return
Not signed in
// user is typed as User | null
return
{user?.firstName}
}
```
--------------------------------
### Links
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/react-router.md
Renders stylesheet and preload links from the `links` function. This component should be placed in your root layout's head.
```APIDOC
## Links
### Description
Renders stylesheet and preload links from the `links` function. This component should be placed in your root layout's head.
### Signature
```typescript
export function Links(): React.ReactElement
```
```
--------------------------------
### Set Environment Variables for Clerk
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/quick-start-guide.md
Configure your Clerk publishable and secret keys in a `.env.local` file. Ensure this file is not committed to version control.
```bash
VITE_CLERK_PUBLISHABLE_KEY=pk_test_YOUR_PUBLISHABLE_KEY_HERE
CLERK_SECRET_KEY=sk_test_YOUR_SECRET_KEY_HERE
```
--------------------------------
### Landing Page with Conditional Auth UI
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/clerk-components.md
Display different content on a landing page based on the user's authentication status. Shows a welcome message and sign-in button for guests, and a welcome back message with user profile for logged-in users.
```typescript
export default function Home() {
return (
<>
Welcome to Our App
Start Free Trial
Welcome Back!
>
)
}
```
--------------------------------
### Manual Async Loader with rootAuthLoader
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/clerk-server.md
Illustrates how to manually call `rootAuthLoader` within a custom loader function to fetch authentication data and then perform additional server-side data fetching.
```typescript
export async function loader({ request, context }: Route.LoaderArgs) {
// Get auth data from Clerk
const authData = await rootAuthLoader({ request, context })
// Fetch user-specific data if authenticated
if (authData.user) {
const userData = await fetch(`/api/users/${authData.user.id}`)
return { ...authData, userData }
}
return authData
}
```
--------------------------------
### Clerk Middleware Options
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/clerk-server.md
Reference for the configuration options available for `clerkMiddleware`.
```APIDOC
## ClerkMiddlewareOptions
### Description
Configuration options for the `clerkMiddleware` function.
### Interface
```typescript
interface ClerkMiddlewareOptions {
signInUrl?: string // Default: '/sign-in'
signUpUrl?: string // Default: '/sign-up'
publishableKey?: string // Default: VITE_CLERK_PUBLISHABLE_KEY env var
secretKey?: string // Default: CLERK_SECRET_KEY env var
}
```
```
--------------------------------
### ClerkMiddlewareOptions Interface
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/types.md
Options for configuring the `clerkMiddleware()` function, specifying URLs for sign-in/sign-up and Clerk API keys.
```typescript
interface ClerkMiddlewareOptions {
signInUrl?: string
signUpUrl?: string
publishableKey?: string
secretKey?: string
}
```
--------------------------------
### Vite Build Configuration
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/app-structure.md
Vite configuration file setting up essential plugins for Tailwind CSS, React Router, and TypeScript path aliases.
```typescript
defineConfig({
plugins: [
tailwindcss(),
reactRouter(),
tsconfigPaths()
]
})
```
--------------------------------
### Show Component
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/clerk-components.md
The Show component conditionally renders its children based on the provided 'when' prop, which specifies the desired authentication state ('signed-in' or 'signed-out').
```APIDOC
## Show Component
### Description
Conditionally renders content based on the user's authentication state.
### Props
#### `when`
- **Type**: `'signed-in' | 'signed-out'`
- **Required**: Yes
- **Description**: Specifies the authentication state for which the content should be shown. Use `'signed-in'` for authenticated users and `'signed-out'` for unauthenticated users.
#### `children`
- **Type**: `React.ReactNode`
- **Required**: Yes
- **Description**: The content to be rendered conditionally.
### Returns
Returns the `children` if the `when` condition matches the current authentication state, otherwise returns `null`.
### Usage Example
```typescript
import { Show, SignInButton, UserButton } from '@clerk/react-router'
export default function Header() {
return (
)
}
```
```
--------------------------------
### Importing Global Stylesheet
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/app-structure.md
Demonstrates how to import a global stylesheet in a React application using the `links` function for route-specific stylesheets.
```typescript
import stylesheet from './app.css?url'
export const links = () => [
{ rel: 'stylesheet', href: stylesheet }
]
```
--------------------------------
### route Function
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/react-router.md
Creates a standard route with an optional path. It accepts the URL path segment and the path to the component file.
```APIDOC
## Function: route
Creates a standard route with optional path.
### Signature
```typescript
export function route(path: string, componentPath: string): RouteObject
```
### Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `path` | `string` | URL path segment. Example: `'users'`, `'users/:id'`, `'*'` |
| `componentPath` | `string` | Path to component file relative to `app/` |
### Returns
`RouteObject` for the specified path
### Usage
```typescript
[
route('users', 'routes/users.tsx'),
route('users/:id', 'routes/user-detail.tsx'),
route('*', 'routes/not-found.tsx')
]
```
--------------------------------
### Clerk Middleware with Custom Sign-In/Sign-Up URLs
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/clerk-server.md
Configure custom URLs for sign-in and sign-up pages when using Clerk middleware. This allows for a branded authentication flow.
```typescript
export const middleware: Route.MiddlewareFunction[] = [
clerkMiddleware({
signInUrl: '/auth/signin',
signUpUrl: '/auth/signup'
})
]
```
--------------------------------
### Vite Configuration with Plugins
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/configuration.md
Configures Vite for development and production builds, integrating Tailwind CSS, React Router, and tsconfig path aliases.
```typescript
import { reactRouter } from "@react-router/dev/vite";
import tailwindcss from "@tailwindcss/vite";
import { defineConfig } from "vite";
import tsconfigPaths from "vite-tsconfig-paths";
export default defineConfig({
plugins: [tailwindcss(), reactRouter(), tsconfigPaths()],
});
```
--------------------------------
### ClerkMiddlewareOptions
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/types.md
Options for configuring the `clerkMiddleware()` function, which handles authentication routing.
```APIDOC
## clerkMiddleware(options)
### Description
Options for configuring `clerkMiddleware()`.
### Fields
#### Path Parameters
- None
#### Query Parameters
- None
#### Request Body
- **signInUrl** (`string`) - Optional - URL to redirect unsigned requests. Defaults to `/sign-in`.
- **signUpUrl** (`string`) - Optional - URL of sign-up page. Defaults to `/sign-up`.
- **publishableKey** (`string`) - Optional - Clerk publishable key. Defaults to environment variable.
- **secretKey** (`string`) - Optional - Clerk secret key (server-only). Defaults to environment variable.
```
--------------------------------
### Using Path Aliases in TypeScript Imports
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/app-structure.md
Demonstrates the usage of the '~/*' path alias for cleaner import statements in TypeScript files. This replaces relative imports with a more readable alias.
```typescript
// Instead of: import { Welcome } from '../welcome/welcome'
// Use: import { Welcome } from '~/welcome/welcome'
```
--------------------------------
### Protected Header with Clerk Components
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/clerk-components.md
Implement a header that shows a sign-in button for logged-out users and a user profile button for logged-in users.
```typescript
export default function Header() {
return (
)
}
```
--------------------------------
### TypeScript Includes Configuration
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/app-structure.md
Specifies which files and directories TypeScript should include for type checking and compilation, including server-only, client-only, and auto-generated route types.
```typescript
[
"**/*",
"**/.server/**/*",
"**/.client/**/*",
".react-router/types/**/*"
]
```
--------------------------------
### Docker Runtime Environment Variables
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/configuration.md
When running the Docker container, mount or pass environment variables for Clerk's publishable and secret keys, and map the port.
```bash
docker run \
-e VITE_CLERK_PUBLISHABLE_KEY=pk_test_... \
-e CLERK_SECRET_KEY=sk_test_... \
-p 3000:3000 \
clerk-rr-quickstart
```
--------------------------------
### ClerkMiddlewareOptions Interface
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/clerk-server.md
Reference for the options available when configuring Clerk middleware. Defaults are provided for signInUrl, signUpUrl, publishableKey, and secretKey.
```typescript
interface ClerkMiddlewareOptions {
signInUrl?: string // Default: '/sign-in'
signUpUrl?: string // Default: '/sign-up'
publishableKey?: string // Default: VITE_CLERK_PUBLISHABLE_KEY env var
secretKey?: string // Default: CLERK_SECRET_KEY env var
}
```
--------------------------------
### Environment Variables for Clerk
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/configuration.md
Define required environment variables in a `.env.local` file for Clerk integration. Use `VITE_` prefix for client-side keys and no prefix for server-side secret keys.
```dotenv
VITE_CLERK_PUBLISHABLE_KEY=pk_test_Y2xlcmsuY29tLmNsZXJr
CLERK_SECRET_KEY=sk_test_5wJlSCxrYLJYRXz0G4RvZT6Q7kR9sN2xL
```
--------------------------------
### Create Standard Route
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/react-router.md
Helper function to create a standard route with a specified path and component path. Supports dynamic segments and catch-all routes.
```typescript
export function route(path: string, componentPath: string): RouteObject
```
--------------------------------
### index Function
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/react-router.md
Creates an index route that matches the parent path without an additional segment. It takes the path to the component file as an argument.
```APIDOC
## Function: index
Creates an index route (matches parent path with no additional segment).
### Signature
```typescript
export function index(componentPath: string): RouteObject
```
### Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `componentPath` | `string` | Path to the component file relative to `app/` directory. Example: `'routes/home.tsx'` |
### Returns
`RouteObject` configured as an index route
### Usage
```typescript
// Routes home component at '/'
[index("routes/home.tsx")]
// Routes to parent URL without additional path segment
[
{
path: "/dashboard",
component: DashboardLayout,
children: [
index("routes/dashboard-home.tsx") // Matches /dashboard
]
}
]
```
--------------------------------
### Define CLERK_SECRET_KEY in .env.local
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/quick-start-guide.md
Add your Clerk secret key to the `.env.local` file to prevent middleware failures. Restart the dev server after adding.
```bash
CLERK_SECRET_KEY=sk_test_YOUR_KEY_HERE
```
--------------------------------
### Type-Safe Loader and Component Usage
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/types.md
Demonstrates how to import and use auto-generated route types for type-safe arguments in loaders and props in components. This enhances developer experience and reduces runtime errors.
```typescript
import type { Route } from './+types/home'
export const loader = (args: Route.LoaderArgs) => {
// Type-safe args
return { title: 'Home' }
}
export default function Home({ loaderData }: Route.ComponentProps) {
// Type-safe loaderData
return
{loaderData.title}
}
```
--------------------------------
### Basic clerkMiddleware Configuration
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/middleware-and-loaders.md
Applies the `clerkMiddleware` to validate Clerk session tokens on incoming requests. This is typically configured in your root layout file.
```typescript
// app/root.tsx
import { clerkMiddleware } from '@clerk/router/server'
import type { Route } from './+types/root'
export const middleware: Route.MiddlewareFunction[] = [
clerkMiddleware()
]
```
--------------------------------
### Root-Level Authentication Loader
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/middleware-and-loaders.md
Use this pattern when you only need to know if the user is authenticated globally. It sets up Clerk authentication for the entire application.
```typescript
// app/root.tsx
import { rootAuthLoader } from '@clerk/react-router/server'
export const loader = (args: Route.LoaderArgs) => rootAuthLoader(args)
export default function App({ loaderData }: Route.ComponentProps) {
return (
{/* All components have access to auth context */}
)
}
```
--------------------------------
### React Router Configuration
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/quick-start-guide.md
Configure React Router for server-side rendering and middleware.
```typescript
{
ssr: true, // Server-side render (required for Clerk)
future: {
v8_middleware: true // Enable middleware (required)
}
}
```
--------------------------------
### User Interface
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/types.md
Represents a user's profile information. Includes details like ID, email addresses, phone numbers, names, and profile image.
```typescript
interface User {
id: string
emailAddresses: EmailAddress[]
phoneNumbers: PhoneNumber[]
firstName?: string
lastName?: string
fullName?: string
profileImageUrl?: string
primaryEmailAddressId?: string
primaryPhoneNumberId?: string
metadata?: Record
externalId?: string
externalAccounts?: ExternalAccount[]
createdAt: Date
updatedAt: Date
}
```
--------------------------------
### SignInButton Configuration
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/quick-start-guide.md
Configure the SignInButton to open the sign-in interface in a modal or redirect the user. You can specify a redirect URL and customize the button's label.
```typescript
Click to Sign In
```
--------------------------------
### Clerk React Router Components
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/INDEX.md
API documentation for UI components exported from `@clerk/react-router`, including authentication context provider and user interaction components.
```APIDOC
## Clerk React Router Components
### Description
This section details the UI components provided by the `@clerk/react-router` library, designed for seamless integration with React Router for authentication flows.
### Components
- **``**
- **Description**: Provides the authentication context for the application, making Clerk's authentication state and methods available to child components.
- **``**
- **Description**: A pre-built button component that initiates the sign-in flow when clicked.
- **``**
- **Description**: Displays the current user's profile information and provides an option to sign out.
- **``**
- **Description**: A conditional rendering component that allows displaying content based on the user's authentication state.
```
--------------------------------
### Dockerfile Structure
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/configuration.md
The Dockerfile uses Node.js 20 Alpine for multi-stage builds, separating development dependencies, production dependencies, and the final production image.
```dockerfile
FROM node:20-alpine AS development-dependencies-env
# ... development dependencies
FROM node:20-alpine AS production-dependencies-env
# ... production dependencies only
FROM node:20-alpine AS build-env
# ... build stage
FROM node:20-alpine
# ... final production image
```
--------------------------------
### Multiple Conditional Sections
Source: https://github.com/clerk/clerk-react-router-quickstart/blob/main/_autodocs/api-reference/clerk-components.md
Demonstrates rendering distinct sections of UI for both signed-out and signed-in states using multiple Show components. This allows for a tailored user experience on landing pages or application interfaces.
```typescript