Skip to main content

rootAuthLoader()

The rootAuthLoader() function makes Clerk authentication state available to React Router routes through the root loader.

rootAuthLoader() requires clerkMiddleware()React Router Icon in the root route. Pass authentication optionsReact Router Icon to clerkMiddleware().

Usage

You can use the rootAuthLoader() in two different ways:

Without a callback

In your root.tsx file, add rootAuthLoader() to the loader() function. If your app doesn't have a loader() function yet, you'll need to add it manually.

app/root.tsx
import { clerkMiddleware, rootAuthLoader } from '@clerk/react-router/server'
import type { Route } from './+types/root'

export const middleware: Route.MiddlewareFunction[] = [clerkMiddleware()]

export async function loader(args: Route.LoaderArgs) {
  return rootAuthLoader(args)
}

With a callback

If you need to load in additional data, you can pass a callback to rootAuthLoader() that handles the route data loading with auth state.

app/root.tsx
import { clerkMiddleware, rootAuthLoader } from '@clerk/react-router/server'
import type { Route } from './+types/root'

export const middleware: Route.MiddlewareFunction[] = [clerkMiddleware()]

export async function loader(args: Route.LoaderArgs) {
  return rootAuthLoader(args, ({ request, context, params }) => {
    const { sessionId, userId, getToken } = request.auth
    // Add logic to fetch data
    return { yourData: 'here' }
  })
}

Feedback

What did you think of this content?

Last updated on