Clerk SDK for Next.js providing authentication and user management with support for both App Router and Pages Router architectures
Clerk provides authentication and user management for Next.js applications with full support for both App Router and Pages Router architectures. The SDK includes pre-built UI components, server-side and client-side authentication utilities, middleware for route protection, and webhook handling capabilities.
npm install @clerk/nextjs// Client components and hooks
import { ClerkProvider, SignIn, SignUp, UserButton, useAuth, useUser } from '@clerk/nextjs';
// Server-side utilities
import { auth, currentUser, clerkMiddleware } from '@clerk/nextjs/server';
// Webhook verification
import { verifyWebhook } from '@clerk/nextjs/webhooks';
// Error utilities
import { isClerkAPIResponseError } from '@clerk/nextjs/errors';For CommonJS:
const { ClerkProvider } = require('@clerk/nextjs');
const { auth } = require('@clerk/nextjs/server');// app/layout.tsx
import { ClerkProvider } from '@clerk/nextjs';
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<ClerkProvider>
<html lang="en">
<body>{children}</body>
</html>
</ClerkProvider>
);
}
// middleware.ts
import { clerkMiddleware } from '@clerk/nextjs/server';
export default clerkMiddleware();
export const config = {
matcher: [
'/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)',
'/(api|trpc)(.*)',
],
};
// app/dashboard/page.tsx - Server Component
import { auth } from '@clerk/nextjs/server';
export default async function Dashboard() {
const { userId } = await auth();
if (!userId) {
return <div>Not authenticated</div>;
}
return <div>Welcome {userId}</div>;
}// pages/_app.tsx
import { ClerkProvider } from '@clerk/nextjs';
import type { AppProps } from 'next/app';
export default function App({ Component, pageProps }: AppProps) {
return (
<ClerkProvider {...pageProps}>
<Component {...pageProps} />
</ClerkProvider>
);
}
// pages/api/protected.ts
import { getAuth } from '@clerk/nextjs/server';
import type { NextApiRequest, NextApiResponse } from 'next';
export default function handler(req: NextApiRequest, res: NextApiResponse) {
const { userId } = getAuth(req);
if (!userId) {
return res.status(401).json({ error: 'Unauthorized' });
}
return res.status(200).json({ userId });
}The Clerk Next.js SDK is built around several key components:
auth() (App Router) or getAuth() (Pages Router) on the server, and via hooks on the clientauth.protect() and client-side via <Protect> componentclerkClient()The package provides multiple entry points for different use cases:
The ClerkProvider component wraps your application and provides authentication context to all child components.
function ClerkProvider(props: NextClerkProviderProps): JSX.Element;
interface NextClerkProviderProps {
/** Optional override for NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY env variable */
publishableKey?: string;
/** If true, invokes middleware on client-side auth state changes (default: true) */
__unstable_invokeMiddlewareOnAuthStateChange?: boolean;
/** If true, opts into dynamic rendering for auth data (default: false) */
dynamic?: boolean;
/** All other ClerkProviderProps from @clerk/clerk-react */
[key: string]: any;
}Pre-built UI components for authentication flows including sign-in, sign-up, user profile, and organization management.
// Authentication UI Components
function SignIn(props: SignInProps): JSX.Element;
function SignUp(props: SignUpProps): JSX.Element;
function UserButton(props: UserButtonProps): JSX.Element;
function UserProfile(props: UserProfileProps): JSX.Element;
// Organization Components
function OrganizationSwitcher(props: OrganizationSwitcherProps): JSX.Element;
function OrganizationProfile(props: OrganizationProfileProps): JSX.Element;
function OrganizationList(props: OrganizationListProps): JSX.Element;
function CreateOrganization(props: CreateOrganizationProps): JSX.Element;
// Button Components
function SignInButton(props: SignInButtonProps): JSX.Element;
function SignUpButton(props: SignUpButtonProps): JSX.Element;
function SignOutButton(props: SignOutButtonProps): JSX.Element;
// Conditional Rendering Components
function SignedIn(props: { children: React.ReactNode }): JSX.Element | null;
function SignedOut(props: { children: React.ReactNode }): JSX.Element | null;
function Protect(props: ProtectProps): JSX.Element | null;React hooks for accessing authentication state, user data, and Clerk methods on the client side.
// Primary hooks
function useAuth(): UseAuthReturn;
function useUser(): UseUserReturn;
function useSession(): UseSessionReturn;
function useClerk(): Clerk;
// Organization hooks
function useOrganization(): UseOrganizationReturn;
function useOrganizationList(): UseOrganizationListReturn;
// Authentication flow hooks
function useSignIn(): UseSignInReturn;
function useSignUp(): UseSignUpReturn;
function useSessionList(): UseSessionListReturn;
interface UseAuthReturn {
userId: string | null | undefined;
sessionId: string | null | undefined;
orgId: string | null | undefined;
orgRole: string | null | undefined;
orgSlug: string | null | undefined;
orgPermissions: string[] | null | undefined;
actor: any | null | undefined;
getToken: (options?: GetTokenOptions) => Promise<string | null>;
has: (permission: string) => boolean;
signOut: () => Promise<void>;
}Server-side authentication utilities for App Router including auth state access and route protection.
// Get authentication state
function auth(options?: AuthOptions): Promise<SessionAuthWithRedirect>;
// Protect routes with authentication/authorization
auth.protect(params?: AuthProtectParams): Promise<SessionAuthObject>;
// Get current user object
function currentUser(): Promise<User | null>;
// Reverification utilities for sensitive operations
function reverificationErrorResponse<MC extends ReverificationConfig>(
missingConfig?: MC
): Response;
function reverificationError<MC extends ReverificationConfig>(
missingConfig?: MC
): ReverificationError<{ metadata?: { reverification?: MC } }>;
interface SessionAuthWithRedirect {
userId: string | null;
sessionId: string | null;
orgId: string | null;
orgRole: string | null;
orgSlug: string | null;
orgPermissions: string[] | null;
actor: any | null;
has: (permission: string) => boolean;
redirectToSignIn: (opts?: RedirectOptions) => never;
redirectToSignUp: (opts?: RedirectOptions) => never;
}Server-Side Authentication (App Router)
Server-side authentication utilities for Pages Router including getServerSideProps and API routes.
// Get authentication state from request
function getAuth(req: NextApiRequest): SessionAuthObject;
// Build Clerk props for SSR
function buildClerkProps(
req: NextApiRequest,
options?: BuildClerkPropsOptions
): Promise<ServerSideAuth>;
interface SessionAuthObject {
userId: string | null;
sessionId: string | null;
orgId: string | null;
orgRole: string | null;
orgSlug: string | null;
orgPermissions: string[] | null;
actor: any | null;
has: (permission: string) => boolean;
}Server-Side Authentication (Pages Router)
Next.js middleware for authentication and authorization with route matching capabilities.
// Create middleware with optional handler
function clerkMiddleware(
handler?: ClerkMiddlewareHandler,
options?: ClerkMiddlewareOptions | ClerkMiddlewareOptionsCallback
): NextMiddleware;
// Create route matcher for protecting specific routes
function createRouteMatcher(
routes: string | string[] | RegExp | ((req: NextRequest) => boolean)
): (req: NextRequest) => boolean;
type ClerkMiddlewareHandler = (
auth: ClerkMiddlewareAuth,
request: NextRequest,
event: NextFetchEvent
) => NextMiddlewareReturn;
interface ClerkMiddlewareOptions {
debug?: boolean;
contentSecurityPolicy?: ContentSecurityPolicyOptions;
publishableKey?: string;
secretKey?: string;
signInUrl?: string;
signUpUrl?: string;
afterSignInUrl?: string;
afterSignUpUrl?: string;
}Middleware and Route Protection
Access the Clerk Backend SDK for server-side operations like user management and organization operations.
// Get Clerk backend client
function clerkClient(): Promise<ClerkClient>;
// Create custom Clerk client
function createClerkClient(options: ClerkClientOptions): ClerkClient;
// Verify session token
function verifyToken(
token: string,
options?: VerifyTokenOptions
): Promise<JWTPayload>;Verify and handle webhook events from Clerk to sync data with your backend.
// Verify webhook request
function verifyWebhook(
request: RequestLike,
options?: VerifyWebhookOptions
): Promise<WebhookEvent>;
interface VerifyWebhookOptions {
signingSecret?: string;
}
type WebhookEvent =
| UserWebhookEvent
| SessionWebhookEvent
| OrganizationWebhookEvent
| OrganizationMembershipWebhookEvent
| OrganizationInvitationWebhookEvent
| EmailWebhookEvent
| SMSWebhookEvent;Utilities for detecting and handling different types of Clerk errors.
// Error detection functions
function isClerkAPIResponseError(err: unknown): boolean;
function isClerkRuntimeError(err: unknown): boolean;
function isEmailLinkError(err: unknown): boolean;
function isKnownError(err: unknown): boolean;
function isMetamaskError(err: unknown): boolean;
function isReverificationCancelledError(err: unknown): boolean;
// Error code constants
const EmailLinkErrorCode: {
[key: string]: string;
};Core types used throughout the SDK:
// Resource Types
interface User {
id: string;
emailAddresses: EmailAddress[];
phoneNumbers: PhoneNumber[];
externalAccounts: ExternalAccount[];
firstName: string | null;
lastName: string | null;
username: string | null;
imageUrl: string;
createdAt: Date;
updatedAt: Date;
// ... additional methods and properties
}
interface Organization {
id: string;
name: string;
slug: string;
imageUrl: string;
createdAt: Date;
updatedAt: Date;
// ... additional methods and properties
}
interface Session {
id: string;
userId: string;
status: SessionStatus;
lastActiveAt: Date;
expireAt: Date;
abandonAt: Date;
createdAt: Date;
updatedAt: Date;
// ... additional methods and properties
}
// Additional resource types: OrganizationMembership, EmailAddress,
// PhoneNumber, ExternalAccount, OrganizationInvitation, etc.Install with Tessl CLI
npx tessl i tessl/npm-clerk--nextjs