# Agent file: add sign-in to a Next.js app with Clerk

This file is written for an AI coding agent working in a repository with its owner present. Follow the steps in order and run the check at the end of each step before starting the next. It is complete without the guide it accompanies.

Every fact about Clerk here was checked against the pages under Sources on October 10, 2026. Commands, flags and dashboard labels change. If one fails, read the linked page before trying again. Do not guess.

The code below is from the current Clerk documentation and from our own app. Every TypeScript sample type-checks against version 7 of `@clerk/nextjs` and version 2 of `@clerk/express`, the versions our app runs. The `Show` component is not in version 6 of `@clerk/nextjs`. If the repository pins an older major version, read its installed types before copying anything.

## Goal

Visitors can sign up, sign in and sign out. Every page, route handler and server action that touches user data checks the session itself. If there is a separate API, it verifies the session on every request. The app keeps its own user rows in sync through a signed webhook. All of it runs on a Clerk development instance.

## Preconditions

Check each one in the repository before changing anything.

- Search for existing authentication (another auth library, a session cookie, a users table with passwords). If you find any, stop and report it. Get approval before going further.
- Read the Next.js version in `package.json`. It decides the middleware filename: `middleware.ts` on Next.js 15 and earlier, `proxy.ts` on 16 and later.
- Confirm `.env.local` is ignored by git.
- Find the health check route, if there is one. It must stay outside the middleware.
- List every page, route handler and server action that reads or writes user data. You will need the list in step 4.

## Environment variables

Names only.

| Name | Where | Notes |
| --- | --- | --- |
| `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY` | Next.js app | Public by design. Written to `.env.local` by the CLI. |
| `CLERK_SECRET_KEY` | Next.js app and API | Secret. Server only. Never in client code or git. |
| `CLERK_PUBLISHABLE_KEY` | Express API | The same publishable key, under the name the Express SDK reads. |
| `CLERK_WEBHOOK_SIGNING_SECRET` | Whichever service receives the webhook | Secret. Copied by the human from the endpoint in the Clerk Dashboard. |
| `NEXT_PUBLIC_CLERK_SIGN_IN_URL`, `NEXT_PUBLIC_CLERK_SIGN_UP_URL` | Next.js app | Only when the app renders its own sign-in and sign-up pages. |

Development keys start with `pk_test_` and `sk_test_`. Production keys start with `pk_live_` and `sk_live_`. This file never needs a production key.

## Stop and ask the human

- Any secret value. Ask for the variable to be set by the human. Never print, log, commit or echo a secret, and never ask for one to be pasted into the conversation.
- Any sign-in, account creation, plan choice or payment method.
- Anything that deletes data or cannot be undone.
- Creating the webhook endpoint in the Clerk Dashboard and copying its signing secret. Give them the URL and the event names.
- Everything about a production instance: creating it, production keys, OAuth credentials for social sign-in, DNS records and the Deploy certificates step. Clerk states that user data cannot be transferred between instances and that development instances are capped at 100 users, so real customers must not be invited before production exists.
- Creating test users in an application the human already uses.
- Removing or replacing existing authentication.

## Steps

### 1. Run the Clerk CLI

```bash
npx -y clerk@latest init     # detects Next.js, writes dev keys to .env.local
npx -y clerk@latest doctor   # checks the setup
```

The CLI detects the framework and package manager, applies the Next.js setup and writes the two development keys to `.env.local`. Do not ask the human to copy keys for this step. Fall back to manual setup (install `@clerk/nextjs`, add the middleware, wrap the app) only if `init` has run and failed.

Check: `.env.local` contains both variable names and `git status` does not list the file.

### 2. Check the middleware

By default `clerkMiddleware()` does not protect any routes. Its job is to make the session available to the checks in step 4. Keep the health check out of its matcher: the middleware fails requests it handles when the secret key is missing, which would fail a deploy for a reason unrelated to the app.

```ts
// middleware.ts on Next.js 15 and earlier, proxy.ts on 16 and later
import { clerkMiddleware } from '@clerk/nextjs/server'

export default clerkMiddleware()

export const config = {
  matcher: [
    // Skip Next.js internals, static files and the health check
    '/((?!_next|api/health|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)',
    // Always run for API routes, except the health check
    '/(api(?!/health)|trpc)(.*)',
    // Always run for Clerk-specific frontend API routes
    '/__clerk/(.*)',
  ],
}
```

This is the matcher from the Clerk reference with `api/health` excluded in the first two patterns. Do not add `createRouteMatcher()`. Clerk marks it as deprecated and says to protect access next to the data.

Check: the file has the right name for this Next.js version and the health route still answers 200 with no session.

### 3. Wrap the app and show the controls

`ClerkProvider` goes inside `body`. If the app already has a header, put the controls there instead of adding a second one.

```tsx
// app/layout.tsx
import { ClerkProvider, SignInButton, SignUpButton, Show, UserButton } from '@clerk/nextjs'
import './globals.css'

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <ClerkProvider>
          <header>
            <Show when="signed-out">
              <SignInButton />
              <SignUpButton />
            </Show>
            <Show when="signed-in">
              <UserButton />
            </Show>
          </header>
          {children}
        </ClerkProvider>
      </body>
    </html>
  )
}
```

Check: the signed-out page shows sign-in and sign-up, and the signed-in page shows the user button.

### 4. Protect every resource that touches user data

Add a check inside each item on the list from the preconditions. A layout check is not enough, because layouts do not re-render on client-side navigation.

A page. `auth.protect()` redirects a signed-out visitor to sign-in:

```tsx
// app/example/page.tsx
import { auth } from '@clerk/nextjs/server'

export default async function Page() {
  // Redirects to the sign-in route if the user is not signed in
  await auth.protect()

  return <h1>Hello world</h1>
}
```

A route handler. For API requests `auth.protect()` returns a 404 to a signed-out caller, so check `isAuthenticated` yourself when you want a 401:

```ts
// app/api/me/route.ts
import { auth } from '@clerk/nextjs/server'

export const GET = async () => {
  const { isAuthenticated, userId } = await auth()

  if (!isAuthenticated) {
    return Response.json({ error: 'Unauthorized' }, { status: 401 })
  }

  return Response.json({ userId })
}
```

In a server action, `auth.protect()` rejects a signed-out caller with a 401.

Check: request each protected route with no session and confirm it does not return data.

### 5. Authenticate a separate API

Skip this step if the app has no backend of its own. Install `@clerk/express` and set `CLERK_PUBLISHABLE_KEY` and `CLERK_SECRET_KEY` on the API.

```ts
import express from 'express'
import { clerkMiddleware, getAuth } from '@clerk/express'

const app = express()

app.use(clerkMiddleware())

app.get('/protected', async (req, res) => {
  const { isAuthenticated, userId } = getAuth(req)

  if (!isAuthenticated) {
    res.status(401).json({ error: 'Unauthorized' })
    return
  }

  res.json({ userId })
})
```

Rules the API must keep:

- Do not use `requireAuth()` on API routes. Clerk documents that it redirects a signed-out caller instead of returning a status code.
- Take the user id, organization id and role from `getAuth(req)` only. Never from the request body, the query string or a header the client controls.
- Mount public routes first (health check, webhooks), then the auth check, then everything else.
- An organization id in a URL selects the organization. It grants nothing. Check membership on every request and answer 404 to a non-member.
- Filter every database query by the organization from the verified session.

Check: a request with no token gets 401, and a request for another organization gets 404.

### 6. Sync users with a webhook

Add a route outside every auth check. It is authenticated by its signature. In Next.js:

```ts
// app/api/webhooks/route.ts
import { verifyWebhook } from '@clerk/nextjs/webhooks'
import { NextRequest } from 'next/server'

export async function POST(req: NextRequest) {
  try {
    // Reads CLERK_WEBHOOK_SIGNING_SECRET and throws on a bad signature
    const evt = await verifyWebhook(req)

    if (evt.type === 'user.created') {
      // Upsert the user by evt.data.id. Must be safe to run twice.
    }

    return new Response('Webhook received', { status: 200 })
  } catch (err) {
    console.error('Error verifying webhook:', err)
    return new Response('Error verifying webhook', { status: 400 })
  }
}
```

In Express the same helper is imported from `@clerk/express/webhooks`. Signature verification needs the exact bytes that were sent, so mount a raw body parser on the webhook path before the JSON parser:

```ts
// Mount BEFORE express.json(): signature checks need the exact bytes that
// were sent, so the webhook handlers must receive req.body as a Buffer.
app.use('/api/webhooks/clerk', express.raw({ type: 'application/json', limit: '1mb' }));
app.use('/api/webhooks/stripe', express.raw({ type: 'application/json', limit: '1mb' }));
```

Clerk warns that deliveries are not guaranteed, that events can arrive out of order or more than once, and that the sync is eventually consistent. Build for that:

- Make each handler an upsert, so a repeat delivery changes nothing.
- Record each delivery and skip one that was already processed, while letting a failed one run again:

```ts
// eventId is the delivery id from the webhook request headers.
// Only a successfully processed event is a duplicate. A prior 'failed'
// record must not block reprocessing when Clerk retries.
const existing = await prisma.clerkWebhookEvent.findUnique({ where: { eventId } });

if (existing?.status === 'processed') {
  res.json({ received: true, message: 'Already processed' });
  return;
}
```

- Never make a request wait for a webhook. Create the user row on the first authenticated request if it does not exist yet.
- Treat Clerk as the owner of names, photos and organization names. Write them to Clerk and copy them into your tables from the webhook.

Then give the human the endpoint URL and the events (`user.created`, `user.updated`, `user.deleted`). They select Add Endpoint on the Webhooks page of the Clerk Dashboard, subscribe to those events, copy the Signing Secret and set `CLERK_WEBHOOK_SIGNING_SECRET`.

Check: on the endpoint Testing tab the human sends an example `user.created` event and its status is Succeeded. Send it twice and confirm one row.

### 7. Verify

Run `npx -y clerk@latest doctor`, then start the app and go through sign-up, sign-out and sign-in. Report what you tested and what you could not test.

## Done when

- Sign-up, sign-in and sign-out work on the development instance.
- Every item on the protected-resource list has its own check, and none relies on middleware alone.
- The API, if any, returns 401 without a token and never reads identity from the request body.
- The webhook verifies its signature and is safe to receive twice.
- `CLERK_SECRET_KEY` and the signing secret appear nowhere in git or in your output.
- The human has a written list of what is left for production.

## Sources

- [Next.js quickstart](https://clerk.com/docs/nextjs/getting-started/quickstart)
- [clerkMiddleware() reference](https://clerk.com/docs/reference/nextjs/clerk-middleware)
- [Protect content from unauthenticated users](https://clerk.com/docs/nextjs/guides/secure/protect-content)
- [auth() reference](https://clerk.com/docs/reference/nextjs/app-router/auth)
- [Express quickstart](https://clerk.com/docs/expressjs/getting-started/quickstart)
- [requireAuth() reference](https://clerk.com/docs/reference/express/require-auth)
- [Sync Clerk data with webhooks](https://clerk.com/docs/guides/development/webhooks/syncing)
- [Managing environments](https://clerk.com/docs/guides/development/managing-environments)
- [Deploy to production](https://clerk.com/docs/guides/development/deployment/production)
- [Pricing](https://clerk.com/pricing)
