### Required Environment Variables Setup (.env.local) Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/configuration.md Example of setting up all required and some optional environment variables for local development. ```bash # Required variables WORKOS_CLIENT_ID="client_01ARZ3NDEKTSV4RRFFQ69G5FAV" WORKOS_API_KEY="sk_test_51234567890abcdefghijklmnopqrst" WORKOS_COOKIE_PASSWORD="M7vK9pQ2nL4mJxW6yZ1bC3dE5fG7hI9jK2lM5nO8q" NEXT_PUBLIC_WORKOS_REDIRECT_URI="http://localhost:3000/auth/callback" # Optional variables WORKOS_COOKIE_MAX_AGE="34560000" WORKOS_COOKIE_NAME="wos-session" WORKOS_COOKIE_SAMESITE="lax" WORKOS_API_HOSTNAME="api.workos.com" WORKOS_API_HTTPS="true" ``` -------------------------------- ### Run Next.js Development Server Source: https://github.com/workos/authkit-nextjs/blob/main/examples/next/README.md Start the Next.js development server to view the example application locally. ```bash pnpm dev ``` -------------------------------- ### Production Environment Variables Setup (.env.production) Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/configuration.md Example of setting up required and specific optional environment variables for a production environment. ```bash WORKOS_CLIENT_ID="client_prod_01ARZ3NDEKTSV4RRFFQ69G5FAV" WORKOS_API_KEY="sk_live_51234567890abcdefghijklmnopqrst" WORKOS_COOKIE_PASSWORD="GeneratedSecurePassword1234567890" NEXT_PUBLIC_WORKOS_REDIRECT_URI="https://myapp.com/auth/callback" WORKOS_COOKIE_SAMESITE="strict" ``` -------------------------------- ### Install AuthKit Next.js Package Source: https://github.com/workos/authkit-nextjs/blob/main/README.md Install the AuthKit Next.js package using either pnpm or yarn. ```bash pnpm i @workos-inc/authkit-nextjs ``` ```bash yarn add @workos-inc/authkit-nextjs ``` -------------------------------- ### Install Dependencies with pnpm Source: https://github.com/workos/authkit-nextjs/blob/main/examples/vinext/README.md Install project dependencies using pnpm. This command should be run from the repository root. ```bash pnpm install ``` -------------------------------- ### Copy Environment File Source: https://github.com/workos/authkit-nextjs/blob/main/examples/vinext/README.md Copy the example environment file to .env.local and fill in your WorkOS credentials. Ensure all required variables are set. ```bash cp .env.local.example .env.local ``` -------------------------------- ### Setup Middleware (Next.js ≤15) Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/quick-reference.md Set up the AuthKit middleware for Next.js versions 15 and below using `authkitMiddleware`. This is the standard middleware setup for older Next.js versions. ```typescript // middleware.ts import { authkitMiddleware } from '@workos-inc/authkit-nextjs'; export default authkitMiddleware(); export const config = { matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'], }; ``` -------------------------------- ### Function Signature Example Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/INDEX.md Illustrates the standard format for documenting function signatures, including name, parameters with types, and return types. ```typescript function name(param: Type): ReturnType ``` -------------------------------- ### Setup Middleware (Next.js 16+) Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/quick-reference.md Configure the AuthKit proxy for Next.js versions 16 and above using `authkitProxy`. This setup allows for custom middleware configurations. ```typescript // proxy.ts import { authkitProxy } from '@workos-inc/authkit-nextjs'; export default authkitProxy({ debug: false, middlewareAuth: { enabled: false, unauthenticatedPaths: [], }, }); export const config = { matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'], }; ``` -------------------------------- ### Basic Proxy Setup for Next.js 16+ Source: https://github.com/workos/authkit-nextjs/blob/main/README.md Use this for Next.js 16 and later. Create a `proxy.ts` file in your project root to enable session management. ```typescript // proxy.ts (Next.js 16+) import { authkitProxy } from '@workos-inc/authkit-nextjs'; export default authkitProxy(); // Match against pages that require auth export const config = { matcher: ['/', '/admin'] }; ``` -------------------------------- ### Middleware signUpPaths Example Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/configuration.md Configure an array of routes that should trigger the sign-up flow instead of the sign-in screen, using Next.js middleware matcher glob patterns. ```typescript signUpPaths: [ '/register', '/onboarding', '/signup/:path*' ] ``` -------------------------------- ### Basic Middleware Setup for Next.js ≤15 Source: https://github.com/workos/authkit-nextjs/blob/main/README.md Use this for Next.js versions 15 and earlier. Create a `middleware.ts` file in your project root to enable session management. ```typescript // middleware.ts (Next.js ≤15) import { authkitMiddleware } from '@workos-inc/authkit-nextjs'; export default authkitMiddleware(); // Match against pages that require auth export const config = { matcher: ['/', '/admin'] }; ``` -------------------------------- ### authkitProxy Usage Example Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/middleware-functions.md Demonstrates how to use the authkitProxy function in a Next.js 16+ application. This example configures debug logging and middleware authentication with specific unauthenticated paths. ```typescript // proxy.ts (Next.js 16+) import { authkitProxy } from '@workos-inc/authkit-nextjs'; export default authkitProxy({ debug: false, middlewareAuth: { enabled: true, unauthenticatedPaths: ['/', '/about', '/pricing'] } }); export const config = { matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'], }; ``` -------------------------------- ### Basic Callback Route Setup Source: https://github.com/workos/authkit-nextjs/blob/main/README.md Expose an API route to handle the authentication callback from WorkOS. Ensure this route matches your configured `WORKOS_REDIRECT_URI`. ```typescript import { handleAuth } from '@workos-inc/authkit-nextjs'; export const GET = handleAuth(); ``` -------------------------------- ### Setup Callback Handler Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/quick-reference.md Implement the callback handler using `handleAuth` to process authentication callbacks. This route is typically used after a user completes the OAuth flow. ```typescript // app/auth/callback/route.ts import { handleAuth } from '@workos-inc/authkit-nextjs'; export const GET = handleAuth({ returnPathname: '/dashboard', onSuccess: async ({ user, oauthTokens }) => { // Save user or tokens }, }); ``` -------------------------------- ### Strict Security Setup with Middleware Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/configuration.md Enables middleware authentication and defines specific unauthenticated paths for enhanced security. The matcher configuration is also included. ```typescript // middleware.ts import { authkitMiddleware } from '@workos-inc/authkit-nextjs'; export default authkitMiddleware({ middlewareAuth: { enabled: true, unauthenticatedPaths: ['/', '/contact', '/privacy'], }, }); export const config = { matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'], }; ``` -------------------------------- ### Advanced AuthKit Integration with Rewrites Source: https://github.com/workos/authkit-nextjs/blob/main/README.md For advanced use cases like rewrites, use `partitionAuthkitHeaders` and `applyResponseHeaders`. This example demonstrates how to use these functions in a Next.js middleware or proxy. ```typescript import { NextRequest, NextResponse } from 'next/server'; import { authkit, partitionAuthkitHeaders, applyResponseHeaders } from '@workos-inc/authkit-nextjs'; export default async function proxy(request: NextRequest) { // For Next.js ≤15, use: export default async function middleware(request: NextRequest) { const { headers } = await authkit(request); const { requestHeaders, responseHeaders } = partitionAuthkitHeaders(request, headers); // Create your own response (rewrite, etc.) const response = NextResponse.rewrite(new URL('/app/dashboard', request.url), { request: { headers: requestHeaders }, }); // Apply AuthKit response headers (Set-Cookie, etc.) applyResponseHeaders(response, responseHeaders); return response; } ``` -------------------------------- ### handleAuth Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/core-functions.md Creates a route handler for the OAuth callback endpoint. Returns a GET handler function. ```APIDOC ## handleAuth ### Description Creates a route handler for the OAuth callback endpoint. Returns a GET handler function. ### Method `function` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **options** (object) - Optional - Callback configuration - **returnPathname** (string) - Optional - Path to redirect after successful auth (default: `/`) - **baseURL** (string) - Optional - Base URL for redirects (useful for Docker) - **onSuccess** (function) - Optional - Callback after successful authentication - **onError** (function) - Optional - Custom error handler ### Returns A GET handler function for the route ### Usage: ```typescript // app/auth/callback/route.ts import { handleAuth } from '@workos-inc/authkit-nextjs'; export const GET = handleAuth({ returnPathname: '/dashboard', onSuccess: async ({ user, oauthTokens }) => { // Save OAuth tokens or user metadata await db.users.update(user.id, { oauthTokens }); } }); ``` ``` -------------------------------- ### Environment Variable Setup for AuthKit Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/quick-reference.md Configure your Next.js application's environment variables by adding these keys to your `.env.local` file. Ensure you replace placeholder values with your actual WorkOS credentials and a secure cookie password. ```bash # .env.local WORKOS_CLIENT_ID="client_01234567890" WORKOS_API_KEY="sk_test_01234567890" WORKOS_COOKIE_PASSWORD="YourSecure32CharacterPasswordHere" NEXT_PUBLIC_WORKOS_REDIRECT_URI="http://localhost:3000/auth/callback" ``` -------------------------------- ### handleAuth onSuccess Callback Example Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/configuration.md Implement the onSuccess callback to handle user data, tokens, and state after successful authentication. This is useful for persisting OAuth tokens or recording user signups. ```typescript onSuccess: async ({ user, oauthTokens, state }) => { await db.users.create({ id: user.id, email: user.email }); if (oauthTokens) { await db.oauthTokens.save(user.id, oauthTokens); } } ``` -------------------------------- ### Docker Setup for AuthKit Proxy Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/configuration.md Configures the authkitProxy for use within a Docker environment. Specifies the redirect URI to be accessible from the Docker host and enables debug mode. ```typescript // proxy.ts or middleware.ts import { authkitProxy } from '@workos-inc/authkit-nextjs'; export default authkitProxy({ redirectUri: 'http://host.docker.internal:3000/auth/callback', debug: true, }); ``` -------------------------------- ### Get PKCE Cookie Options Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/internal-helpers.md Retrieves options for PKCE verifier cookies, similar to session cookies but with shorter maxAge and adjusted SameSite for cross-origin redirects. Use for short-lived, single-use PKCE verification. ```typescript function getPKCECookieOptions(redirectUri?: string | null, asString?: boolean, expired?: boolean): CookieOptions | string ``` -------------------------------- ### Get Current User in Client Component with useAuth Hook Source: https://github.com/workos/authkit-nextjs/blob/main/README.md Use the `useAuth` hook in client components to get the current user session. It returns the user object and a loading state. ```jsx 'use client'; // Note the updated import path import { useAuth } from '@workos-inc/authkit-nextjs/components'; export default function MyComponent() { // Retrieves the user from the session or returns `null` if no user is signed in const { user, loading } = useAuth(); if (loading) { return
Loading...
; } return
{user?.firstName}
; } ``` -------------------------------- ### Get Current User in Server Component with WorkOS Source: https://github.com/workos/authkit-nextjs/blob/main/README.md Use `withAuth` in server components to retrieve the user session from WorkOS. This is useful for displaying signed-in and signed-out views. It also provides functions to get sign-in/sign-up URLs and to sign out. ```jsx import Link from 'next/link'; import { getSignInUrl, getSignUpUrl, withAuth, signOut } from '@workos-inc/authkit-nextjs'; export default async function HomePage() { // Retrieves the user from the session or returns `null` if no user is signed in const { user } = await withAuth(); if (!user) { // Get the URL to redirect the user to AuthKit to sign in const signInUrl = await getSignInUrl(); // Get the URL to redirect the user to AuthKit to sign up const signUpUrl = await getSignUpUrl(); // You can also pass custom state data through the auth flow const signInUrlWithState = await getSignInUrl({ state: JSON.stringify({ teamId: 'team_123', referrer: 'homepage', }), }); return ( <> Log in Sign Up ); } return (
{ 'use server'; await signOut(); }}>

Welcome back {user?.firstName && `, ${user?.firstName}`}

); } ``` -------------------------------- ### Configure Sign-Up Paths Source: https://github.com/workos/authkit-nextjs/blob/main/README.md Specify paths that should use the 'sign-up' screen hint when redirecting to AuthKit using the `signUpPaths` option in `authkitMiddleware`. Useful for paths that mandate authentication. ```typescript import { authkitMiddleware } from '@workos-inc/authkit-nextjs'; export default authkitMiddleware({ signUpPaths: ['/account/sign-up', '/dashboard/:path*'], }); ``` -------------------------------- ### Development Environment Variables Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/configuration.md Sets up environment variables for local development using a .env.local file. Ensure to use test keys and a local redirect URI. ```bash # .env.local WORKOS_CLIENT_ID="client_test_01234567890" WORKOS_API_KEY="sk_test_01234567890" WORKOS_COOKIE_PASSWORD="ThisIsA32CharacterLongPasswordHere" NEXT_PUBLIC_WORKOS_REDIRECT_URI="http://localhost:3000/auth/callback" WORKOS_COOKIE_SAMESITE="lax" WORKOS_API_HOSTNAME="api.workos.com" ``` -------------------------------- ### Get Organization Server Action Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/server-actions.md Fetches organization details by its ID. Used internally by the `Impersonation` component to display organization information. ```typescript async function getOrganizationAction( organizationId: string ): Promise ``` -------------------------------- ### Configure Local Development with Wrangler Source: https://github.com/workos/authkit-nextjs/blob/main/examples/vinext/README.md Create a .dev.vars file to configure local development with the Workers runtime instead of vinext dev. ```bash cp .dev.vars.example .dev.vars ``` -------------------------------- ### Middleware unauthenticatedPaths Example Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/configuration.md Specify an array of glob patterns for routes that should be accessible without authentication using Next.js middleware matcher syntax. ```typescript unauthenticatedPaths: [ '/', // Home page '/about', '/api/public/:path*', // Public API routes '/(auth|login)', // Multiple paths ] ``` -------------------------------- ### Deprecated authkitMiddleware for Next.js <= 15 Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/middleware-functions.md Use `authkitMiddleware` in `middleware.ts` for Next.js versions 15 and below. This is an alias for `authkitProxy` and is deprecated starting from Next.js 16. ```typescript import { authkitMiddleware } from '@workos-inc/authkit-nextjs'; export default authkitMiddleware({ debug: false, }); export const config = { matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'], }; ``` -------------------------------- ### Configuration Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/DELIVERY_MANIFEST.txt This section outlines the configuration options available for the AuthKit Next.js library, including environment variables, handler options, and middleware settings. ```APIDOC ## Configuration This section outlines the configuration options available for the AuthKit Next.js library, including environment variables, handler options, and middleware settings. ### Configuration Details: - 4 required environment variables - 6 optional environment variables - `handleAuth()` options - `authkitProxy()` / `authkitMiddleware()` options - Matcher patterns - Example configurations (dev, prod, docker) ``` -------------------------------- ### Environment Variables for Next.js Source: https://github.com/workos/authkit-nextjs/blob/main/examples/next/README.md Configure your WorkOS credentials and redirect URI in the .env.local file. Ensure the cookie password is at least 32 characters long. ```bash WORKOS_CLIENT_ID= WORKOS_API_KEY= WORKOS_COOKIE_PASSWORD= NEXT_PUBLIC_WORKOS_REDIRECT_URI=http://localhost:3000/callback ``` -------------------------------- ### Configure Sign-Up Paths Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/quick-reference.md Defines specific paths within your application that are designated for user sign-up. This helps AuthKit manage sign-up flows correctly. ```typescript // middleware.ts authkitMiddleware({ signUpPaths: ['/register', '/signup/:path*'], }); ``` -------------------------------- ### Dashboard Component using useAuth Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/react-hooks.md An example of a client-side React component that uses the `useAuth` hook with `ensureSignedIn: true` to display user-specific content or an unauthenticated message. ```typescript 'use client'; import { useAuth } from '@workos-inc/authkit-nextjs/components'; export function Dashboard() { const { user, loading, refreshAuth, signOut } = useAuth({ ensureSignedIn: true }); if (loading) { return
Loading...
; } if (!user) { return
Not authenticated
; } return (

Welcome {user.firstName}

); } ``` -------------------------------- ### Create AuthKit Next.js Sign-in Endpoint Source: https://github.com/workos/authkit-nextjs/blob/main/README.md Use this route handler to initiate the AuthKit sign-in flow. Configure this route in your WorkOS dashboard as the 'Sign-in endpoint' (initiate_login_uri). Ensure the path matches your application's routing. ```typescript import { getSignInUrl } from '@workos-inc/authkit-nextjs'; import { redirect } from 'next/navigation'; export const GET = async () => { const signInUrl = await getSignInUrl(); return redirect(signInUrl); }; ``` -------------------------------- ### Get AuthKit Package Version Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/quick-reference.md Import and access the VERSION constant to retrieve the current package version of AuthKit for Next.js. This is useful for debugging or ensuring compatibility. ```typescript import { VERSION } from '@workos-inc/authkit-nextjs/workos'; // Current: '2.14.0' (check package.json for latest) ``` -------------------------------- ### Get Access Token Server Action Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/server-actions.md Fetches the current access token from the session. Returns undefined if not authenticated. This action is called internally by the `useAccessToken` hook. ```typescript async function getAccessTokenAction(): Promise ``` -------------------------------- ### AuthkitMiddlewareOptions Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/types.md Configuration options for authkitProxy() and authkitMiddleware(). This includes settings for debugging, middleware authentication, redirect URIs, sign-up paths, and eager authentication. ```APIDOC ## AuthkitMiddlewareOptions ### Description Configuration options for `authkitProxy()` and `authkitMiddleware()`. This includes settings for debugging, middleware authentication, redirect URIs, sign-up paths, and eager authentication. ### Fields - **debug** (boolean) - Optional - Enable debug logging. Default: `false` - **middlewareAuth** (AuthkitMiddlewareAuth) - Optional - Enable/configure middleware auth. Default: `{enabled: false}` - **redirectUri** (string) - Optional - Custom redirect URI override. - **signUpPaths** (string[]) - Optional - Paths that use sign-up instead of sign-in. Default: `[]` - **eagerAuth** (boolean) - Optional - Enable synchronous token access via cookie. Default: `false` ``` -------------------------------- ### Basic Impersonation Component Usage Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/react-hooks.md Demonstrates how to integrate the Impersonation component into a Next.js layout with AuthKitProvider. ```typescript 'use client'; import { AuthKitProvider, Impersonation } from '@workos-inc/authkit-nextjs/components'; export default function RootLayout({ children }) { return ( {children} ); } ``` -------------------------------- ### handleAuth onError Callback Example Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/configuration.md Define a custom error handler using the onError callback to manage authentication failures. This function should return a Response to be sent to the client. ```typescript onError: async ({ error, request }) => { console.error('Auth failed:', error); return new Response( JSON.stringify({ error: 'Authentication failed' }), { status: 500 } ); } ``` -------------------------------- ### handleAuth Options Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/configuration.md Configuration options for the `handleAuth` function, which handles the authentication callback and redirects. ```APIDOC ## handleAuth Options ### Description Configuration options for the `handleAuth` function, which handles the authentication callback and redirects. ### Parameters #### Request Body - **returnPathname** (string) - Optional - Path to redirect after successful authentication. Defaults to `/`. Can be overridden by state parameter from client. Example: `/dashboard` or `/onboarding`. - **baseURL** (string) - Optional - Base URL for OAuth redirect. Defaults to derived from request URL. Use Case: Docker containers where hostname differs from request. Requirements: Must be valid absolute URL. Example: `http://localhost:3000` or `https://myapp.com`. - **onSuccess** ((data: HandleAuthSuccessData) => void | Promise) - Optional - Callback after successful authentication. Data includes: user, tokens, OAuth tokens, custom state. Use Case: Persist OAuth tokens, record signup, add to team. Example: ```typescript onSuccess: async ({ user, oauthTokens, state }) => { await db.users.create({ id: user.id, email: user.email }); if (oauthTokens) { await db.oauthTokens.save(user.id, oauthTokens); } } ``` - **onError** ((params: { error?: unknown; request: NextRequest }) => Response | Promise) - Optional - Custom error handler. Returns: Response to send to client. Example: ```typescript onError: async ({ error, request }) => { console.error('Auth failed:', error); return new Response( JSON.stringify({ error: 'Authentication failed' }), { status: 500 } ); } ``` ``` -------------------------------- ### Get WorkOS Client Instance Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/core-functions.md Retrieves the singleton WorkOS client instance. This is useful for direct access to WorkOS SDK methods when not using the higher-level AuthKit abstractions. ```typescript import { getWorkOS } from '@workos-inc/authkit-nextjs'; export async function GetOrganizations() { const workos = getWorkOS(); const organizations = await workos.organizations.listOrganizations({ limit: 10, }); return organizations; } ``` -------------------------------- ### File Sizes Overview Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/INDEX.md This snippet provides a summary of the file sizes and line counts for each markdown file within the AuthKit Next.js documentation. ```text README.md 367 lines 14 KB Architecture & navigation quick-reference.md 525 lines 11 KB Copy-paste patterns & config core-functions.md 492 lines 13 KB Server functions react-hooks.md 387 lines 11 KB Client hooks types.md 463 lines 13 KB Type definitions middleware-functions.md 392 lines 11 KB Middleware setup configuration.md 366 lines 9.6 KB Environment & options errors.md 437 lines 9.5 KB Error handling server-actions.md 285 lines 7.7 KB Server actions internal-helpers.md 434 lines 11 KB Internal utilities --- TOTAL 4148 lines 128 KB ``` -------------------------------- ### Get Access Token for API Requests Source: https://github.com/workos/authkit-nextjs/blob/main/README.md Retrieve the access token directly using the `withAuth` higher-order function. This token can then be used to make authenticated API requests to other services. ```jsx import { withAuth } from '@workos-inc/authkit-nextjs'; export default async function HomePage() { const { accessToken } = await withAuth(); if (!accessToken) { return
Not signed in
; } const serviceData = await fetch('/api/path', { headers: { Authorization: `Bearer ${accessToken}`, }, }); return
{serviceData}
; } ``` -------------------------------- ### Configure Environment Variables for AuthKit Source: https://github.com/workos/authkit-nextjs/blob/main/README.md Set up essential environment variables in your .env.local file for WorkOS authentication. Ensure WORKOS_CLIENT_ID, WORKOS_API_KEY, WORKOS_COOKIE_PASSWORD, and NEXT_PUBLIC_WORKOS_REDIRECT_URI are correctly configured. ```sh WORKOS_CLIENT_ID="client_..." # retrieved from the WorkOS dashboard WORKOS_API_KEY="sk_test_..." # retrieved from the WorkOS dashboard WORKOS_COOKIE_PASSWORD="" # generate a secure password here NEXT_PUBLIC_WORKOS_REDIRECT_URI="http://localhost:3000/callback" # configured in the WorkOS dashboard ``` -------------------------------- ### Configure Redirect Options in AuthKit Source: https://github.com/workos/authkit-nextjs/blob/main/README.md Use `handleAuthkitHeaders` to specify a redirect URL and status code. The default redirect status is 307 for GET requests and 303 for POST requests. ```typescript handleAuthkitHeaders(request, headers, { redirect: '/login', redirectStatus: 307, }); ``` -------------------------------- ### Run Local Development Server with Wrangler Source: https://github.com/workos/authkit-nextjs/blob/main/examples/vinext/README.md Use `wrangler dev` to run your application in the local workerd runtime. This provides a more accurate simulation of the production environment compared to `vinext dev`. ```bash wrangler dev ``` -------------------------------- ### authkitProxy / authkitMiddleware Options Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/configuration.md Configure the authkitProxy or authkitMiddleware with options for debugging, middleware authentication settings, redirect URIs, sign-up paths, and eager authentication. ```typescript authkitProxy({ debug?: boolean; middlewareAuth?: { enabled: boolean; unauthenticatedPaths: string[]; }; redirectUri?: string; signUpPaths?: string[]; eagerAuth?: boolean; }) ``` -------------------------------- ### Get Feature Flags Runtime Client Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/core-functions.md Returns a shared Feature Flags runtime client. This client should be created once per server process, not per request, to ensure efficient reuse. ```typescript function getFeatureFlagsRuntimeClient( options?: RuntimeClientOptions ): FeatureFlagsRuntimeClient ``` ```typescript import { getFeatureFlagsRuntimeClient, withAuth } from '@workos-inc/authkit-nextjs'; const featureFlags = getFeatureFlagsRuntimeClient(); export default async function Dashboard() { const { user, organizationId } = await withAuth({ ensureSignedIn: true }); await featureFlags.waitUntilReady({ timeoutMs: 5000 }); const isEnabled = featureFlags.isEnabled('new-feature', { userId: user.id, organizationId, }); return isEnabled ? : ; } ``` -------------------------------- ### Import Client Components and Hooks Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/quick-reference.md Import React client components and hooks for integrating authentication into your frontend. Remember to use the 'use client' directive. ```typescript // React Client exports (use 'use client' directive) import { AuthKitProvider, useAuth, useAccessToken, useTokenClaims, Impersonation, } from '@workos-inc/authkit-nextjs/components'; import type { UseAccessTokenReturn } from '@workos-inc/authkit-nextjs/components'; ``` -------------------------------- ### Basic Callback Route Implementation Source: https://github.com/workos/authkit-nextjs/blob/main/README.md This is the basic implementation of the callback route. It uses the `handleAuth` function from WorkOS AuthKit to process the authentication callback. ```APIDOC ## GET /auth/callback ### Description Handles the callback from WorkOS after user authentication. ### Method GET ### Endpoint /auth/callback ### Request Body None ### Response Redirects the user to the configured return path. ### Code Example ```ts import { handleAuth } from '@workos-inc/authkit-nextjs'; export const GET = handleAuth(); ``` ``` -------------------------------- ### Get Token Claims for Role Checking Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/quick-reference.md Retrieve token claims using `getTokenClaims` to access user roles and permissions. This is useful for implementing role-based access control within your application. ```typescript import { getTokenClaims } from '@workos-inc/authkit-nextjs'; export async function CheckRole() { const claims = await getTokenClaims(); const isAdmin = claims.role === 'admin'; const permissions = claims.permissions || []; return isAdmin ? : ; } ``` -------------------------------- ### Client-side Redirect with Server Actions Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/server-actions.md Shows how to handle redirects initiated by server actions in a client component. By returning a `signInUrl`, the client can perform the redirect using `window.location.href`, avoiding CORS issues. ```typescript const auth = await refreshAuthAction({ ensureSignedIn: true }); if ('signInUrl' in auth) { window.location.href = auth.signInUrl; // ← Client-side redirect } ``` -------------------------------- ### Get Authentication State Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/server-actions.md Fetches the current authentication state. Use this when you need to know the user's sign-in status on the client. It sanitizes sensitive information like the access token. ```typescript async function getAuthAction(options?: { ensureSignedIn?: boolean }): Promise & { signInUrl?: string }> ``` -------------------------------- ### Access Token Synchronously in Client Component Source: https://github.com/workos/authkit-nextjs/blob/main/README.md Use the `useAccessToken` hook in client components to get the authentication token immediately. Useful for initializing third-party clients that require synchronous token access. ```tsx 'use client'; import { useAccessToken } from '@workos-inc/authkit-nextjs/components'; function MyComponent() { const { getAccessToken } = useAccessToken(); async function handleClick() { // Token is available immediately on initial page load const token = await getAccessToken(); // Use with third-party services that need immediate token access if (token) { // Initialize your third-party client with the token thirdPartyClient.authenticate(token); } } return ; } ``` -------------------------------- ### Configure Sign-in Endpoint and Route Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/errors.md Set the sign-in endpoint in the WorkOS Dashboard and create a corresponding route to handle the impersonation flow correctly. ```typescript // app/auth/sign-in/route.ts import { getSignInUrl } from '@workos-inc/authkit-nextjs'; import { redirect } from 'next/navigation'; export const GET = async () => { const url = await getSignInUrl(); redirect(url); }; ``` -------------------------------- ### Using useAccessToken for API Calls Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/react-hooks.md Demonstrates how to use the useAccessToken hook to fetch a guaranteed fresh token and include it in API request headers. Handles loading and error states. ```typescript 'use client'; import { useAccessToken } from '@workos-inc/authkit-nextjs/components'; export function ApiClient() { const { accessToken, loading, error, getAccessToken } = useAccessToken(); async function fetchData() { try { const token = await getAccessToken(); const response = await fetch('/api/data', { headers: { Authorization: `Bearer ${token}` } }); return response.json(); } catch (err) { console.error('Failed to fetch:', err); } } if (loading) return
Loading token...
; if (error) return
Token error: {error.message}
; return (

Token available: {accessToken?.substring(0, 10)}...

); } ``` -------------------------------- ### SwitchToOrganizationOptions Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/types.md Options for the `switchToOrganization()` function, controlling redirection and cache revalidation after an organization switch. ```APIDOC ## SwitchToOrganizationOptions ### Description Options for the `switchToOrganization()` function. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **returnTo** (string) - Optional - URL to redirect after switch - **revalidationStrategy** (string) - Optional - How to revalidate cache ('path', 'tag', or 'none'). Defaults to 'path'. - **revalidationTags** (string[]) - Optional - Tags to revalidate if using 'tag' strategy. Defaults to `[]`. ``` -------------------------------- ### Get Session Cookie Options Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/internal-helpers.md Retrieves session cookie options, returning either a configuration object or a formatted string. Use this to manage session cookies, considering security flags like HTTPS, SameSite, and HttpOnly. ```typescript function getCookieOptions(redirectUri?: string | null, asString?: boolean, expired?: boolean): CookieOptions | string ``` -------------------------------- ### Wrap App with AuthKitProvider Source: https://github.com/workos/authkit-nextjs/blob/main/README.md Wrap your application's root layout with `AuthKitProvider` to enable client-side authentication methods and protect against auth edge cases. ```jsx import { AuthKitProvider } from '@workos-inc/authkit-nextjs/components'; export default function RootLayout({ children }: { children: React.ReactNode }) { return ( {children} ); } ``` -------------------------------- ### authkitProxy / authkitMiddleware Options Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/configuration.md Configuration options for `authkitProxy` and `authkitMiddleware`, controlling middleware behavior, authentication enforcement, and path handling. ```APIDOC ## authkitProxy / authkitMiddleware Options ### Description Configuration options for `authkitProxy` and `authkitMiddleware`, controlling middleware behavior, authentication enforcement, and path handling. ### Parameters #### Request Body - **debug** (boolean) - Optional - Enable debug logging in middleware. Defaults to `false`. Output: Logs to console during middleware execution. Example: `debug: true`. - **middlewareAuth.enabled** (boolean) - Optional - Enable "secure by default" mode. Defaults to `false`. Behavior: All routes require auth unless in `unauthenticatedPaths`. Alternative: Call `withAuth()` per page instead. - **middlewareAuth.unauthenticatedPaths** (string[]) - Optional - Glob patterns for routes accessible without auth. Defaults to `[]`. Syntax: Next.js middleware matcher syntax. Examples: ```typescript unauthenticatedPaths: [ '/', // Home page '/about', '/api/public/:path*', // Public API routes '/(auth|login)', // Multiple paths ] ``` - **redirectUri** (string) - Optional - Custom redirect URI. Defaults to `WORKOS_REDIRECT_URI` env var. Use Case: Dynamic redirect URIs for preview deployments. Example: `https://preview-123.example.com/auth/callback`. - **signUpPaths** (string[]) - Optional - Routes that use sign-up instead of sign-in screen. Defaults to `[]`. Syntax: Next.js middleware matcher glob patterns. Example: ```typescript signUpPaths: [ '/register', '/onboarding', '/signup/:path*' ] ``` - **eagerAuth** (boolean) - Optional - Enable synchronous access token via cookie. Defaults to `false`. Duration: 30-second cookie window. Use Case: Third-party services needing immediate token. Security: Token briefly exposed to JavaScript (mitigated by CSP). Example: `eagerAuth: true`. ``` -------------------------------- ### Exported Functions Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/DELIVERY_MANIFEST.txt This section details the core server-side functions that can be directly invoked by users of the AuthKit Next.js library. Each function includes its TypeScript signature, parameter table, return type, behavior, error conditions, and code examples. ```APIDOC ## Exported Functions This section details the core server-side functions that can be directly invoked by users of the AuthKit Next.js library. Each function includes its TypeScript signature, parameter table, return type, behavior, error conditions, and code examples. ### Functions Documented: - `withAuth` - `getSignInUrl` - `getSignUpUrl` - `signOut` - `refreshSession` - `saveSession` - `getTokenClaims` - `handleAuth` - `switchToOrganization` - `authkit` - `authkitProxy` - `authkitMiddleware` - `handleAuthkitProxy` - `partitionAuthkitHeaders` - `applyResponseHeaders` - `getFeatureFlagsRuntimeClient` - `validateApiKey` - `getWorkOS` - All server actions, helpers, and utilities. ``` -------------------------------- ### Set up AuthKitProvider for Authentication Context Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/react-hooks.md The AuthKitProvider is a client-side component that must wrap your application to provide authentication context to descendant hooks. It fetches auth data on mount if initialAuth is not provided and monitors tab visibility to detect session expirations. ```typescript function AuthKitProvider(props: { children: ReactNode; onSessionExpired?: false | (() => void); initialAuth?: Omit; }): ReactElement ``` ```typescript // app/layout.tsx import { AuthKitProvider } from '@workos-inc/authkit-nextjs/components'; export default function RootLayout({ children }) { return ( {children} ); } ``` ```typescript // app/layout.tsx import { AuthKitProvider } from '@workos-inc/authkit-nextjs/components'; import { withAuth } from '@workos-inc/authkit-nextjs'; export default async function RootLayout({ children }) { const auth = await withAuth(); const { accessToken, ...initialAuth } = auth; // Exclude token for client return ( {children} ); } ``` ```typescript export default function RootLayout({ children }) { return ( { // Show notification instead of reload console.log('Session expired'); window.location.href = '/login'; }} > {children} ); } ``` ```typescript {children} ``` -------------------------------- ### Get User Session with AuthKit Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/core-functions.md Retrieves the current user session from an authenticated request. Must be called from a server component or server action and requires AuthKit middleware to be active. Use `ensureSignedIn: true` to redirect to sign-in if no user is authenticated. ```typescript async function withAuth(options: { ensureSignedIn: true }): Promise async function withAuth(options?: { ensureSignedIn?: boolean }): Promise ``` ```typescript import { withAuth } from '@workos-inc/authkit-nextjs'; export default async function Dashboard() { const { user, accessToken, organizationId } = await withAuth(); if (!user) { return
Please sign in
; } return
Welcome {user.firstName}
; } ``` -------------------------------- ### Create OAuth Callback Handler with handleAuth Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/core-functions.md The `handleAuth` function generates a GET handler for your OAuth callback endpoint. Configure redirection paths, base URLs, and success/error callbacks to customize the authentication flow. The `onSuccess` callback receives user and OAuth token data. ```typescript function handleAuth(options?: { returnPathname?: string; baseURL?: string; onSuccess?: (data: HandleAuthSuccessData) => void | Promise; onError?: (params: { error?: unknown; request: NextRequest }) => Response | Promise; }): (request: NextRequest) => Promise ``` ```typescript // app/auth/callback/route.ts import { handleAuth } from '@workos-inc/authkit-nextjs'; export const GET = handleAuth({ returnPathname: '/dashboard', onSuccess: async ({ user, oauthTokens }) => { // Save OAuth tokens or user metadata await db.users.update(user.id, { oauthTokens }); } }); ``` -------------------------------- ### getSignUpUrl Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/core-functions.md Generates a URL to redirect users to the WorkOS AuthKit sign-up page. It behaves identically to `getSignInUrl` but displays the sign-up screen. ```APIDOC ## getSignUpUrl ### Description Generates a URL to redirect users to the WorkOS AuthKit sign-up page. Behaves identically to `getSignInUrl` but displays the sign-up screen. ### Parameters `authUrlOptions` (object, optional) - Options for generating the authentication URL. - `state` (string, optional) - `returnTo` (string, optional) - `organizationId` (string, optional) - `redirectUri` (string, optional) - `loginHint` (string, optional) - `prompt` ('consent', optional) ### Returns A URL string pointing to the WorkOS AuthKit sign-up page. ### Example ```typescript import { getSignUpUrl } from '@workos-inc/authkit-nextjs'; import Link from 'next/link'; export default async function Home() { const signUpUrl = await getSignUpUrl({ returnTo: '/onboarding' }); return Create Account; } ``` ``` -------------------------------- ### AuthkitOptions Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/types.md Options for configuring the `authkit()` function. These settings control aspects like eager authentication, debugging, redirect URIs, and session refresh callbacks. ```APIDOC ## AuthkitOptions ### Description Options for configuring the `authkit()` function. These settings control aspects like eager authentication, debugging, redirect URIs, and session refresh callbacks. ### Fields #### eagerAuth - **Type**: boolean - **Required**: No - **Description**: Enable synchronous token access #### debug - **Type**: boolean - **Required**: No - **Description**: Enable debug logging #### redirectUri - **Type**: string - **Required**: No - **Description**: Custom redirect URI #### screenHint - **Type**: 'sign-up' | 'sign-in' - **Required**: No - **Description**: Which screen to show at AuthKit #### onSessionRefreshSuccess - **Type**: function - **Required**: No - **Description**: Called when session refresh succeeds #### onSessionRefreshError - **Type**: function - **Required**: No - **Description**: Called when session refresh fails ``` -------------------------------- ### handleAuthkitProxy Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/middleware-functions.md Creates a properly configured NextResponse with AuthKit headers. It automatically handles header filtering, cookie setting, and redirects, making it essential for composable middleware. ```APIDOC ## handleAuthkitProxy ### Description Creates a properly configured NextResponse with AuthKit headers. Essential for composable middleware. Automatically handles header filtering, cookie setting, and redirects. ### Method ```typescript function handleAuthkitProxy( request: NextRequest, authkitHeaders: Headers, options?: { redirect?: string | URL; redirectStatus?: 302 | 303 | 307 | 308; } ): NextResponse ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | request | NextRequest | Yes | — | The incoming request | | authkitHeaders | Headers | Yes | — | Headers from `authkit()` | | options | object | No | `{}` | Response options | | redirect | string \| URL | No | — | URL to redirect to | | redirectStatus | number | No | `307 for GET, 303 for POST` | HTTP status code | ### Returns A NextResponse with properly handled AuthKit headers. ### Header Filtering This function automatically: - Filters headers to allow-list (Set-Cookie, Cache-Control, Vary, etc.) - Strips internal headers from browser (x-workos-*, x-url, etc.) - Deduplicates Vary headers - Appends Set-Cookie headers correctly for multi-value headers ### Example ```typescript import { NextRequest } from 'next/server'; import { authkit, handleAuthkitProxy } from '@workos-inc/authkit-nextjs'; export default async function proxy(request: NextRequest) { const { session, headers, authorizationUrl } = await authkit(request); const { pathname } = request.nextUrl; // Redirect unauthenticated users if (pathname === '/admin' && !session.user && authorizationUrl) { return handleAuthkitProxy(request, headers, { redirect: authorizationUrl }); } // Custom redirects if (pathname === '/old-path') { return handleAuthkitProxy(request, headers, { redirect: '/new-path' }); } return handleAuthkitProxy(request, headers); } ``` ``` -------------------------------- ### Next.js Project Structure Source: https://github.com/workos/authkit-nextjs/blob/main/_autodocs/README.md Overview of the file structure for WorkOS AuthKit in a Next.js project, indicating the location of key modules and components. ```tree src/ ├── index.ts # Main exports ├── session.ts # withAuth, refreshSession, getTokenClaims, saveSession ├── auth.ts # getSignInUrl, getSignUpUrl, signOut, switchToOrganization ├── middleware.ts # authkit, authkitProxy, authkitMiddleware ├── middleware-helpers.ts # handleAuthkitProxy, partitionAuthkitHeaders, applyResponseHeaders ├── authkit-callback-route.ts # handleAuth ├── feature-flags.ts # getFeatureFlagsRuntimeClient ├── validate-api-key.ts # validateApiKey ├── get-authorization-url.ts # getAuthorizationUrl (internal) ├── workos.ts # getWorkOS ├── errors.ts # AuthKitError, TokenRefreshError ├── cookie.ts # getCookieOptions, getPKCECookieOptions (internal) ├── pkce.ts # PKCE management (internal) ├── interfaces.ts # All type definitions ├── env-variables.ts # Environment variable loading ├── components/ │ ├── authkit-provider.tsx # AuthKitProvider, useAuth │ ├── useAccessToken.ts # useAccessToken │ ├── useTokenClaims.ts # useTokenClaims │ ├── impersonation.tsx # Impersonation component │ ├── tokenStore.ts # Token store (internal) │ └── index.ts # Components exports └── actions.ts # Server actions ``` -------------------------------- ### Callback Route with Base URL Configuration Source: https://github.com/workos/authkit-nextjs/blob/main/README.md Explicitly set the `baseURL` option when running in environments like Docker to ensure redirect URIs point to the correct location. ```APIDOC ## GET /auth/callback with baseURL ### Description Handles the callback from WorkOS, ensuring correct redirect URIs by explicitly setting the `baseURL`, which is crucial for containerized environments. ### Method GET ### Endpoint /auth/callback ### Parameters #### Query Parameters - **baseURL** (string) - Required if running in a container like Docker - The base URL to use for the redirect URI instead of the one in the request. ### Code Example ```ts import { handleAuth } from '@workos-inc/authkit-nextjs'; export const GET = handleAuth({ baseURL: 'http://localhost:3000', }); ``` ```