All skills
clerk avatar

/clerk-react-patterns

@ca5e365 official
by clerkclerk/skills83 stars
5

React SPA auth patterns with @clerk/react for Vite/CRA - ClerkProvider setup, useAuth/useUser/useClerk hooks, React Router protected routes, custom sign-in flows. Triggers on: Vite Clerk setup, React Router auth, useAuth hook, protected route, custom sign-in form React.

Use this Skill: https://skilld.dev/gh/clerk/skills/clerk-react-patterns

This session only. Nothing lands on disk.

referenceshooks.md

≈592 tokens on demand. Your agent reads this file only when SKILL.md points to it.

Hooks (CRITICAL)

isLoaded Guard

Always check isLoaded before trusting auth state. Rendering before Clerk initializes gives wrong results:

import { useAuth } from '@clerk/react'

export function Page() {
  const { isLoaded, isSignedIn, userId } = useAuth()

  if (!isLoaded) return <div>Loading...</div>
  if (!isSignedIn) return <div>Please sign in</div>

  return <div>Hello {userId}</div>
}

useAuth()

Returns auth primitives:

Property Type Description
isLoaded boolean false while Clerk initializes
isSignedIn boolean | undefined undefined until isLoaded is true
userId string | null Current user ID
sessionId string | null Current session ID
orgId string | null Active organization ID
orgRole string | null Active org role
getToken Function Fetches session JWT
signOut Function Signs the user out

useUser()

Returns full user profile:

import { useUser } from '@clerk/react'

export function Profile() {
  const { isLoaded, isSignedIn, user } = useUser()

  if (!isLoaded || !isSignedIn) return null

  return (
    <div>
      <img src={user.imageUrl} alt={user.fullName ?? ''} />
      <p>{user.firstName} {user.lastName}</p>
      <p>{user.emailAddresses[0]?.emailAddress}</p>
    </div>
  )
}

useClerk()

Access the Clerk instance for programmatic control:

import { useClerk } from '@clerk/react'

export function NavBar() {
  const { signOut, openUserProfile, openOrganizationProfile } = useClerk()

  return (
    <nav>
      <button onClick={() => openUserProfile()}>Profile</button>
      <button onClick={() => signOut()}>Sign out</button>
    </nav>
  )
}

getToken() for API Calls

import { useAuth } from '@clerk/react'

export function useAuthFetch() {
  const { getToken } = useAuth()

  return async function authFetch(url: string, init?: RequestInit) {
    const token = await getToken()
    if (!token) throw new Error('Not authenticated')

    return fetch(url, {
      ...init,
      headers: {
        ...init?.headers,
        Authorization: `Bearer ${token}`,
      },
    })
  }
}

getToken() returns null when unauthenticated — always null-check.

Docs

Source: SKILL.md on GitHub

No alerts17d4 checks · Risk SAFE
  • Gen Agent Trust Hub17d

    This skill provides standard documentation, reference patterns, and templates for implementing Clerk authentication in React single-page applications. It follows best practices for authentication flows and uses official dependencies.

  • Socket17d

    No alerts

  • Snyk17d

    Risk: LOW · No issues

  • ZeroLeaks5mo

    Score: 93/100 · 2 sections analyzed

Signed by skilld at ca5e365. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub yesterday.

Activeupdated 6 months ago
What it can do
Network
metadata
{
  "author": "clerk",
  "version": "1.0.0"
}
All 1 allowed tools
WebFetch
  • React
  • clerk
  • authentication
  • vite
  • react-router
  • hooks
  • spa
  • protected-routes

README badge

README badge for clerk/skills/clerk-react-patterns

Provides patterns for @clerk/react authentication in Vite and Create React App SPAs, including ClerkProvider setup, useAuth/useUser/useClerk hooks, React Router protected routes, and custom sign-in flows. Covers client-side auth state management and token retrieval for API calls with React Router v6/v7.

Generated from the current SKILL.md.

Does this skill work with Next.js?
No. This skill is for Vite and Create React App SPAs using @clerk/react. For Next.js, use the clerk-nextjs-patterns skill instead.
Do I need to check isLoaded before using isSignedIn?
Yes. isLoaded must be true before trusting isSignedIn. Always guard on isLoaded first to avoid undefined values.
How do I get a JWT token to send with API requests?
Call getToken() from the useAuth hook, which returns a session JWT. Always null-check the result before using it.
How do I protect routes with React Router?
Create a ProtectedRoute component that checks isLoaded and isSignedIn with useAuth, then redirects unsigned users or renders an Outlet for protected children.

Generated from the current SKILL.md. These answers refresh after source changes.