Clerk Auth Patterns for React Router v7

VerifiedSafe

React Router v7 patterns with Clerk: rootAuthLoader, getAuth, clerkMiddleware, protected routes, SSR user data, and org switching.

Sby Skills Guide Bot
DevelopmentIntermediate
8/6/2026
Claude CodeCursorCopilotCodex
#clerk#react-router#authentication#ssr#protected-routes

Recommended for

Automated summary

This skill provides engineering patterns for integrating Clerk authentication into React Router v7 applications, covering loaders, middleware, protected routes, SSR user data, and organization switching.

Strengths

  • Clear mental model of the middleware-loader pipeline.
  • Concise reference tables for common tasks.
  • Practical pitfalls and fixes with code examples.
  • Example code for loaders, actions, and client components.

Limitations

  • Requires React Router v7.9+ and Clerk React Router v3+.
  • Focuses on Clerk-specific patterns, not general auth.
  • Does not cover advanced flows like webhooks or advanced multi-tenancy.
When to use it

When implementing Clerk authentication in a React Router v7 app and need guidance on loaders, middleware, and protected routes.

When not to use it

When using a different auth provider or an older React Router version that does not support the new loader/middleware pipeline.

Security analysis

Safe
Quality score93/100

The skill provides documentation and code examples for Clerk authentication with React Router. It uses only the WebFetch tool, no destructive or exfiltrating actions, and contains no sensitive data.

No concerns found

How this analysis is made

Examples

Add Clerk auth to a React Router v7 app
I'm building a React Router v7 app and want to add Clerk authentication. Show me how to set up rootAuthLoader, clerkMiddleware, and protect my routes.
Protect a loader with getAuth
How do I use getAuth in a React Router loader to protect a dashboard route and redirect unauthenticated users to /sign-in?
Organization switching
I need to implement organization switching in my React Router app using Clerk. How should I set up the OrganizationSwitcher and my loaders to handle org-scoped data?

name: clerk-react-router-patterns description: 'React Router v7 patterns with Clerk — rootAuthLoader, getAuth in loaders, clerkMiddleware, protected routes, SSR user data, org switching. Triggers on: react-router auth, rootAuthLoader, getAuth loader, react-router protected route, loader authentication, SSR auth react-router.' license: MIT allowed-tools: WebFetch metadata: author: clerk version: 1.0.0

React Router Patterns

SDK: @clerk/react-router v3+. Requires React Router v7.9+.

What Do You Need?

| Task | Reference | |------|-----------| | Auth in loaders and actions | references/loaders-actions.md | | Protected routes and redirects | references/protected-routes.md | | SSR user data and session | references/ssr-auth.md |

Mental Model

React Router v7 uses a middleware + loader pipeline. Clerk plugs into both layers:

  • Middleware (clerkMiddleware()) — runs on every request, attaches auth to context
  • rootAuthLoader — required in root.tsx to pass Clerk state to the client
  • getAuth(args) — called inside any loader/action to get the current user
Request → clerkMiddleware() → rootAuthLoader → page loader → component
                 ↓                   ↓               ↓
           attaches auth      injects state     getAuth(args)
           to context         to response       reads context

Minimal Setup

1. root.tsx

import { rootAuthLoader } from '@clerk/react-router/server'
import { ClerkApp } from '@clerk/react-router'
import type { Route } from './+types/root'

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

export default ClerkApp(function App() {
  return <Outlet />
})

2. Middleware (root route or entry.server.ts)

import { clerkMiddleware } from '@clerk/react-router/server'
export const middleware = [clerkMiddleware()]

Required: rootAuthLoader must be called in root.tsx's loader. Without it, getAuth throws in nested loaders.

Auth in Loaders

import { getAuth } from '@clerk/react-router/server'
import type { Route } from './+types/dashboard'

export async function loader(args: Route.LoaderArgs) {
  const { userId } = await getAuth(args)
  if (!userId) throw redirect('/sign-in')

  const data = await fetchUserData(userId)
  return { data }
}

Auth in Actions

import { getAuth } from '@clerk/react-router/server'

export async function action(args: Route.ActionArgs) {
  const { userId, orgId } = await getAuth(args)
  if (!userId) throw new Response('Unauthorized', { status: 401 })

  const formData = await args.request.formData()
  await saveData(userId, orgId, formData)
  return redirect('/dashboard')
}

Client Components

import { useAuth, useUser } from '@clerk/react-router'

export function Profile() {
  const { userId, isSignedIn } = useAuth()
  const { user } = useUser()
  if (!isSignedIn) return null
  return <p>{user?.firstName}</p>
}

Org Switching

import { OrganizationSwitcher } from '@clerk/react-router'

export function Nav() {
  return <OrganizationSwitcher afterSelectOrganizationUrl="/dashboard" />
}
export async function loader(args: Route.LoaderArgs) {
  const { userId, orgId } = await getAuth(args)
  if (!userId) throw redirect('/sign-in')
  if (!orgId) throw redirect('/select-org')

  return { data: await fetchOrgData(orgId) }
}

Common Pitfalls

| Symptom | Cause | Fix | |---------|-------|-----| | clerkMiddleware() not detected | Missing middleware | Export middleware = [clerkMiddleware()] from root route | | getAuth returns empty userId | rootAuthLoader not called | Call rootAuthLoader(args) in root.tsx loader | | Infinite redirect loop | Redirect target is also protected | Exclude /sign-in from protection check | | redirect not working in action | Using Response instead of throw redirect() | Use throw redirect('/path') from react-router |

Import Map

| What | Import From | |------|-------------| | getAuth | @clerk/react-router/server | | rootAuthLoader | @clerk/react-router/server | | clerkMiddleware | @clerk/react-router/server | | ClerkApp | @clerk/react-router | | useAuth, useUser | @clerk/react-router | | OrganizationSwitcher | @clerk/react-router |

See Also

  • clerk-setup - Initial Clerk install
  • clerk-custom-ui - Custom flows & appearance
  • clerk-orgs - B2B organizations

Docs

React Router SDK

From the file to a first result

The download contains exactly the content displayed on this page. This copy may differ from the latest version in the source repository.

View the source and supporting files

This download contains SKILL.md only. Any scripts, references, templates and dependencies are not included. Get the required files from the source, preserving their directory structure, before continuing.

1. Download the file

Download SKILL.md

From the root of a test project, save the file as .skill-downloads/clerk-auth-patterns-for-react-router-v7-msh3ut0y/SKILL.md, or use the command below. This folder is for inspecting the skill before installation.

Command for macOS/Linux or WSL: requires a POSIX shell and curl. On Windows without WSL, use the download button and create the folder manually.

mkdir -p '.skill-downloads/clerk-auth-patterns-for-react-router-v7-msh3ut0y' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/clerk-auth-patterns-for-react-router-v7-msh3ut0y/download' --output '.skill-downloads/clerk-auth-patterns-for-react-router-v7-msh3ut0y/SKILL.md.part' && mv '.skill-downloads/clerk-auth-patterns-for-react-router-v7-msh3ut0y/SKILL.md.part' '.skill-downloads/clerk-auth-patterns-for-react-router-v7-msh3ut0y/SKILL.md'

2. Check prerequisites

Read SKILL.md before using it. If it references scripts or external services, inspect them and prepare the required access in your test environment.

Tools declared by the author (check availability in your agent): WebFetch

No recognized prerequisites section in this file. This does not mean it is self-contained: libraries, tools and access requirements may be mentioned elsewhere in the content or source repository.

The platforms on this page are catalog indications. The paths below follow tool documentation; they do not prove this skill has been run in those tools. No minimum tool version is confirmed for this listing.

3. Load the skill

After inspection, copy the complete folder into your project using one of the commands below, then open a new tool session. The command stops if a folder with the same name already exists: compare the files before replacing it.

Claude Code
test -f '.skill-downloads/clerk-auth-patterns-for-react-router-v7-msh3ut0y/SKILL.md' && test -s '.skill-downloads/clerk-auth-patterns-for-react-router-v7-msh3ut0y/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/clerk-react-router-patterns' && cp -R '.skill-downloads/clerk-auth-patterns-for-react-router-v7-msh3ut0y' '.claude/skills/clerk-react-router-patterns'

Cursor
test -f '.skill-downloads/clerk-auth-patterns-for-react-router-v7-msh3ut0y/SKILL.md' && test -s '.skill-downloads/clerk-auth-patterns-for-react-router-v7-msh3ut0y/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/clerk-react-router-patterns' && cp -R '.skill-downloads/clerk-auth-patterns-for-react-router-v7-msh3ut0y' '.cursor/skills/clerk-react-router-patterns'

Codex
test -f '.skill-downloads/clerk-auth-patterns-for-react-router-v7-msh3ut0y/SKILL.md' && test -s '.skill-downloads/clerk-auth-patterns-for-react-router-v7-msh3ut0y/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/clerk-react-router-patterns' && cp -R '.skill-downloads/clerk-auth-patterns-for-react-router-v7-msh3ut0y' '.agents/skills/clerk-react-router-patterns'

OpenSkills

OpenSkills must already be installed. The local install/read procedure is checked with OpenSkills 1.5.0, which requires Node.js ≥ 20.6.0. Catalog slugs are not resolved automatically.

Official OpenSkills installation
openskills install './.skill-downloads/clerk-auth-patterns-for-react-router-v7-msh3ut0y'

openskills read 'clerk-auth-patterns-for-react-router-v7-msh3ut0y'

Reading should display the installed file content and its base directory. It does not run the skill or install its dependencies.

For an agent that reads AGENTS.md, then sync the index. This command changes AGENTS.md: review the diff before using it.

openskills sync

Manual method or another tool: attach SKILL.md to a conversation, or open it in an agent that can read files. Include any required supporting resources. No universal folder is recognized by every tool.

4. Try a first task

Use a short, synthetic input: an API endpoint, a small document or an interface brief. In a new conversation, attach the file or give the agent its path, then adapt this request:

Read .skill-downloads/clerk-auth-patterns-for-react-router-v7-msh3ut0y/SKILL.md and apply its instructions to this example: [describe a test input]. Identify any missing files, dependencies or access. Produce the result requested by the skill without inventing data or running unreviewed scripts.

Expected result: output matching the skill instructions, or a precise list of missing prerequisites. A read confirmation alone does not validate a first use. If an external resource is unavailable, that path remains untested.

Related skills