CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-clerk--nextjs

Clerk SDK for Next.js providing authentication and user management with support for both App Router and Pages Router architectures

Overview
Eval results
Files

Clerk Next.js SDK

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.

Package Information

  • Package Name: @clerk/nextjs
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @clerk/nextjs
  • Requirements: Next.js ^13.5.7 || ^14.2.25 || ^15.2.3 || ^16, React 18+, Node.js >=18.17.0

Core Imports

// 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');

Basic Usage

App Router Setup

// 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 Router Setup

// 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 });
}

Architecture

The Clerk Next.js SDK is built around several key components:

  • ClerkProvider: Root provider component that initializes Clerk and provides authentication context
  • Authentication State: Accessed via auth() (App Router) or getAuth() (Pages Router) on the server, and via hooks on the client
  • Middleware: Processes authentication on every request, enabling server-side auth checks
  • UI Components: Pre-built, customizable components for authentication flows (SignIn, SignUp, UserButton, etc.)
  • Route Protection: Server-side protection via auth.protect() and client-side via <Protect> component
  • Hooks: Client-side React hooks for accessing auth state and Clerk methods
  • Backend API: Server-side client for user/organization management via clerkClient()

Entry Points

The package provides multiple entry points for different use cases:

  • @clerk/nextjs: Client components, hooks, and adaptive components
  • @clerk/nextjs/server: Server-only utilities, middleware, and backend API
  • @clerk/nextjs/webhooks: Webhook verification
  • @clerk/nextjs/errors: Error detection utilities
  • @clerk/nextjs/experimental: Experimental features including billing components, payment elements, and experimental hooks (subject to change)
  • @clerk/nextjs/internal: Internal utilities (not for public use)

Capabilities

Setup and Provider

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;
}

Setup and Provider

Client Components

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;

Client Components

Client Hooks

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>;
}

Client Hooks

Server-Side Authentication (App Router)

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 (Pages 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)

Middleware and Route Protection

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

Backend API Client

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>;

Backend API Client

Webhooks

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;

Webhooks

Error Handling

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;
};

Error Handling

Types

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
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@clerk/nextjs@6.36.x