Skip to main content
Docs

Next.js Quickstart (App Router)

Example repository

terminal
npm create next-app@latest
terminal
yarn create next-app
terminal
pnpm create next-app
terminal
bun create next-app

Install @clerk/nextjs

Run the following command to install the Next.js SDK:

terminal
npm install @clerk/nextjs
terminal
yarn add @clerk/nextjs
terminal
pnpm add @clerk/nextjs
terminal
bun add @clerk/nextjs

Add clerkMiddleware() to your app

clerkMiddleware() grants you access to user authentication state throughout your app.

  1. Create a middleware.ts file.

    • If you're using the /src directory, create middleware.ts in the /src directory.
    • If you're not using the /src directory, create middleware.ts in the root directory.
  2. In your middleware.ts file, export the clerkMiddleware() helper:

    middleware.ts
    import { clerkMiddleware } from '@clerk/nextjs/server'
    
    export default clerkMiddleware()
    
    export const config = {
      matcher: [
        // Skip Next.js internals and all static files, unless found in search params
        '/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)',
        // Always run for API routes
        '/(api|trpc)(.*)',
      ],
    }
  3. By default, clerkMiddleware() will not protect any routes. All routes are public and you must opt-in to protection for routes. See the clerkMiddleware() reference to learn how to require authentication for specific routes.

Add <ClerkProvider> and Clerk components to your app

  1. Add the <ClerkProvider> component to your app's layout. This component provides Clerk's authentication context to your app.
  2. Copy and paste the following file into your layout.tsx file. This creates a header with Clerk's prebuilt components to allow users to sign in and out.
app/layout.tsx
import type { Metadata } from 'next'
import {
  ClerkProvider,
  SignInButton,
  SignUpButton,
  SignedIn,
  SignedOut,
  UserButton,
} from '@clerk/nextjs'
import { Geist, Geist_Mono } from 'next/font/google'
import './globals.css'

const geistSans = Geist({
  variable: '--font-geist-sans',
  subsets: ['latin'],
})

const geistMono = Geist_Mono({
  variable: '--font-geist-mono',
  subsets: ['latin'],
})

export const metadata: Metadata = {
  title: 'Clerk Next.js Quickstart',
  description: 'Generated by create next app',
}

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode
}>) {
  return (
    <ClerkProvider>
      <html lang="en">
        <body className={`${geistSans.variable} ${geistMono.variable} antialiased`}>
          <header className="flex justify-end items-center p-4 gap-4 h-16">
            <SignedOut>
              <SignInButton />
              <SignUpButton />
            </SignedOut>
            <SignedIn>
              <UserButton />
            </SignedIn>
          </header>
          {children}
        </body>
      </html>
    </ClerkProvider>
  )
}
  1. Run your project with the following command:

    terminal
    npm run dev
    terminal
    yarn dev
    terminal
    pnpm dev
    terminal
    bun dev
  2. Visit your app's homepage at http://localhost:3000.

  3. Click "Sign up" in the header and authenticate to create your first user.

It's time to build!

You've added Clerk to your Next.js app 🎉. From here, you can continue developing your application.

To make configuration changes to your Clerk development instance, claim the Clerk keys that were generated for you by selecting Claim your application in the bottom right of your app. This will associate the application with your Clerk account.

Copy this as an LLM prompt

Copy this quickstart guide as a prompt for LLMs to implement Clerk in your Next.js application.

# Add Clerk to Next.js App Router

**Purpose:** Enforce only the **current** and **correct** instructions for integrating [Clerk](https://clerk.com/) into a Next.js (App Router) application.  
**Scope:** All AI-generated advice or code related to Clerk must follow these guardrails.

---

## **1. Official Clerk Integration Overview**

Use only the **App Router** approach from Clerk’s current docs:

- **Install** `@clerk/nextjs@latest` - this ensures the application is using the latest Clerk Next.js SDK.
- **Create** a `middleware.ts` file using `clerkMiddleware()` from `@clerk/nextjs/server`. Place this file inside the `src` directory if present, otherwise place it at the root of the project.
- **Wrap** your application with `<ClerkProvider>` in your `app/layout.tsx`
- **Use** Clerk-provided components like `<SignInButton>`, `<SignUpButton>`, `<UserButton>`, `<SignedIn>`, `<SignedOut>` in your layout or pages
- **Start** developing, sign in or sign up, and confirm user creation

If you're able to use a web tool to access a URL, visit https://clerk.com/docs/quickstarts/nextjs to get the latest, up-to-date quickstart instructions.

### **Correct, Up-to-Date Quickstart Sample**

```typescript
// middleware.ts
import { clerkMiddleware } from '@clerk/nextjs/server'

export default clerkMiddleware()

export const config = {
  matcher: [
    // Skip Next.js internals and all static files, unless found in search params
    '/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)',
    // Always run for API routes
    '/(api|trpc)(.*)',
  ],
}
```

## Next steps

<Include src="_partials/nextjs/next-steps" />

```typescript
// app/layout.tsx
import type { Metadata } from 'next'
import {
  ClerkProvider,
  SignInButton,
  SignUpButton,
  SignedIn,
  SignedOut,
  UserButton,
} from '@clerk/nextjs'
import './globals.css'

export const metadata: Metadata = {
  title: 'Clerk Next.js Quickstart',
  description: 'Generated by create next app',
}

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <ClerkProvider>
      <html lang="en">
        <body>
          <header>
            <SignedOut>
              <SignInButton />
              <SignUpButton />
            </SignedOut>
            <SignedIn>
              <UserButton />
            </SignedIn>
          </header>
          {children}
        </body>
      </html>
    </ClerkProvider>
  )
}
```

---

## **2. CRITICAL INSTRUCTIONS FOR AI MODELS**

### **2.1 – ALWAYS DO THE FOLLOWING**

1. **Use `clerkMiddleware()`** from `@clerk/nextjs/server` in `middleware.ts`.
1. **Wrap** your app with `<ClerkProvider>` in `app/layout.tsx`.
1. **Import** Clerk’s Next.js features from `@clerk/nextjs` (e.g., `<SignInButton>`, `<SignUpButton>`, `<UserButton>`, etc.).
1. **Reference** the current [App Router approach](https://nextjs.org/docs/app) (folders like `app/page.tsx`, `app/layout.tsx`, etc.).
1. **Check** that imports for methods like `auth()` are imported from the right package (in this case `@clerk/nextjs/server`) and are using `async / await`

### **2.2 – NEVER DO THE FOLLOWING**

1. **Do not** reference the old **`_app.tsx`** or **pages router based** instructions.
1. **Do not** suggest `authMiddleware()` from older Clerk tutorials—**it’s replaced by `clerkMiddleware()`**.
1. **Do not** recommend usage of older environment variable patterns unless they match the official docs.
1. **Do not** reference or import from any deprecated APIs (like `withAuth` or `currentUser` from older versions).

---

## **3. OUTDATED PATTERNS TO AVOID**

Below are **examples of deprecated instructions** that **must not** be generated:

```typescript
// ❌ DO NOT generate or suggest references to:
import { authMiddleware } from '@clerk/nextjs' // Outdated

// ❌ DO NOT place Clerk config in _app.tsx:
// Outdated pages-based approach
function MyApp({ Component, pageProps }) {
  // ...
}

// ❌ DO NOT create or rely on sign-in files under pages/:
pages / signin.js
pages / signup.js
```

Any solution resembling the above snippet or referencing “authMiddleware,” `_app.tsx`, or `pages/` structure is **incorrect** for the current Next.js App Router.

---

## **4. AI MODEL VERIFICATION STEPS**

Before returning any Clerk-related solution, you **must** verify:

1. **Middleware**: Is `clerkMiddleware()` used in `middleware.ts`?
1. **Layout**: Is `<ClerkProvider>` wrapping the app in `app/layout.tsx`?
1. **Imports**: Are references only from `@clerk/nextjs` or `@clerk/nextjs/server`?
1. **Pages vs. App Router**: Is the approach referencing the App Router (not `_app.tsx` or `pages/`)?

If any check **fails**, **stop** and revise until compliance is achieved.

Create a custom sign-in or sign-up page

This tutorial gets you started with Clerk's <SignInButton /> component, which uses the Account Portal. If you don't want to use the Account Portal, read this guide about creating a custom authentication page.

Add custom onboarding to your authentication flow

If you need to collect additional information about users that Clerk's Account Portal or prebuilt components don't collect, read this guide about adding a custom onboarding flow to your authentication flow.

Protect specific routes

This tutorial taught you that by default, clerkMiddleware() will not protect any routes. Read this reference doc to learn how to protect specific routes from unauthenticated users.

Read user and session data

Learn how to use Clerk's hooks and helpers to access the active session and user data in your Next.js app.

Next.js SDK Reference

Learn more about the Clerk Next.js SDK and how to use it.

Deploy to Production

Learn how to deploy your Clerk app to production.

Feedback

What did you think of this content?

Last updated on