Clerk guide · About an hour · Free to start
Add sign-in to a Next.js app with Clerk
Sign-in screens, protected pages, an authenticated API and a user table kept in sync by webhook, on a plan that is free to start.

Last verified against the official Clerk documentation on October 10, 2026. Prices and free tiers change, so open the linked pages before you rely on a number.
Working with a coding agent? Get the agent file for this guide. It covers the same setup as exact steps an agent can follow.
The customer app we are building uses Clerk for sign-in, organizations and invitations. It is a Next.js client talking to a separate Express API, so this guide covers both halves: the screens a user sees, and the API that has to know who is calling. The app is not live yet. What follows is how the code is wired and what Clerk's documentation says today.
What it costs
At the time of writing, Clerk's pricing page lists a free Hobby plan with no credit card required and a limit of 50,000 monthly retained users per app. Clerk defines a monthly retained user as one who visits your app in a given month at least one day after signing up, so someone who signs up and never returns does not count. The Pro plan is listed at $25 a month, or $20 a month billed annually, with additional retained users at $0.02 each.
The same page lists an Enhanced B2B Authentication add-on at $100 a month. If your product depends on organizations, read that section before you design around them.
Two instances, and why it matters early
Every Clerk application has a development instance and, when you create it, a production instance. Clerk's page on managing environments states three things worth knowing on day one: development instances are capped at 100 users, some social sign-in options run on shared credentials there, and user data cannot be transferred between instances. Build and test on development. Do not invite real customers until the production instance exists, because their accounts will not move.
Step 1: create the application and install the SDK
Clerk's Next.js quickstart now starts from its CLI. In the root of the app, run npx -y clerk@latest init. It detects the framework and package manager, applies the Next.js setup and writes two development keys to .env.local:
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY, which is public by design and ships to the browser.CLERK_SECRET_KEY, which stays on the server and never goes in client code or in git.
If you run it signed out, the quickstart says it provisions an application you can claim later by signing in. When the setup looks wrong, npx -y clerk@latest doctor checks it.
npx -y clerk@latest init # detects Next.js, writes dev keys to .env.local
npx -y clerk@latest doctor # checks the setup
Step 2: add the middleware
Clerk needs a middleware file that calls clerkMiddleware(), imported from @clerk/nextjs/server. The middleware reference gives the naming rule: the file is proxy.ts on Next.js 16 and later, and middleware.ts on Next.js 15 and earlier, with the same contents. Our app is on Next.js 16, so ours is proxy.ts.
We changed one thing in the default matcher: it skips /api/health. The middleware throws on every request it handles when the secret key is missing or rotated, and a health check that passes through it turns a key problem into a failed deploy.
The file from Clerk's reference, with that one exclusion added to the first two matcher patterns:
// 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/(.*)',
],
}
Step 3: wrap the app and add the sign-in controls
In the root layout, put <ClerkProvider> inside <body>. The quickstart's example header uses four components: SignInButton and SignUpButton inside <Show when="signed-out">, and UserButton inside <Show when="signed-in">. That is a working sign-in flow, with Clerk hosting the forms.
// 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>
)
}
We render our own sign-in and sign-up screens at /sign-in and /sign-up, and tell Clerk where they are with NEXT_PUBLIC_CLERK_SIGN_IN_URL and NEXT_PUBLIC_CLERK_SIGN_UP_URL. Start with Clerk's components and move to your own screens only when the design calls for it. One build detail from that work: pages that render Clerk hooks export dynamic = 'force-dynamic', which lets the app build in CI with no Clerk keys present.
Step 4: protect pages and routes
The middleware from the quickstart contains no route checks, so you decide what requires a signed-in user. In a server component, route handler or server action, call auth() and read isAuthenticated and userId, or call auth.protect(), which sends a signed-out visitor to the sign-in page.
A page, from Clerk's guide to protecting content:
// 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 an API request auth.protect() answers a signed-out caller with a 404, so the same guide checks isAuthenticated directly when you want a 401:
// 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 })
}
Put the check next to the data. Clerk's middleware reference says middleware is not the best place to protect routes and that access should be protected as close to the resource as possible. It also marks createRouteMatcher() as deprecated. Our own app started with a public-route matcher in middleware and has since moved off it. Its middleware is now the plain clerkMiddleware() shown in step 2, and each protected page calls auth.protect() itself. A test lists every page and route handler in the app and fails when one is added without being marked public or protected, which is the guarantee the matcher used to give us.
Step 5: authenticate your API
If the app has its own backend, the backend must verify the session itself. For Express, Clerk's Express quickstart installs @clerk/express, sets CLERK_PUBLISHABLE_KEY and CLERK_SECRET_KEY, and adds app.use(clerkMiddleware()). In each handler, getAuth(req) returns the verified user, and the handler answers 401 when isAuthenticated is false. Our client sends the Clerk session token as a bearer token on every API call.
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 })
})
Clerk's reference for requireAuth() says not to use it for API routes, because it redirects a signed-out caller instead of returning a status code.
The rules our API keeps, which matter more than the library calls:
- Identity comes from the verified token. A user id, organization id or role in a request body is never trusted.
- Route order is public routes, then the auth guard, then everything else. A route mounted before the guard is public, so webhooks and the health check are the only things above it.
- An organization id in the URL selects the organization and grants nothing. Every request checks that the caller is a member, and a caller who is not gets a 404.
- Every database query filters by the organization from the verified session. Another organization's row answers 404.
Step 6: keep your database in sync with a webhook
Sooner or later you need users in your own tables, for foreign keys and for queries Clerk cannot answer. Clerk's guide to syncing data with webhooks gives the steps:
- On the Webhooks page of the Clerk Dashboard, select Add Endpoint and enter the public URL of your handler.
- Subscribe to the events you need. For users those are
user.created,user.updatedanduser.deleted. - Copy the endpoint's Signing Secret into an environment variable. Clerk's examples name it
CLERK_WEBHOOK_SIGNING_SECRET. - Make sure the webhook route is not behind your auth checks. It is authenticated by its signature.
- In the handler, verify the request before reading it. In Next.js that is
verifyWebhook(req)from@clerk/nextjs/webhooks.
The handler from Clerk's guide, trimmed:
// 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 })
}
}
The guide is direct about the limits: deliveries are not guaranteed, events can arrive out of order or more than once, and the sync is eventually consistent. Our handler is built around those three warnings. Our API is Express, so it calls the same helper from @clerk/express/webhooks, as the Express version of that guide shows. The signature is checked over the raw request bytes, which in Express means mounting a raw body parser on the webhook path before the JSON parser runs. It records each event id in a table and skips one it has already processed, and an event that failed is allowed to run again on retry. And no request waits for a webhook: the first authenticated call from a new user creates their row if the webhook has not arrived yet.
The raw body parser, from our API's entry file. The Stripe webhook needs the same treatment, so both are mounted together:
// 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' }));
And the duplicate check at the top of our handler:
// 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;
}
We also treat Clerk as the owner of identity fields. Names, photos and organization names are written to Clerk, and the webhook copies them into our tables. Writing them in both places is how the two drift apart.
Step 7: go to production
Clerk's production deployment guide lists what changes. You need a domain you own, and your own OAuth credentials for each social sign-in provider, because the shared development ones are not for production.
- In the Clerk Dashboard, use the environment dropdown at the top to create the production instance. SSO connections, integrations and paths do not copy over from development, so set them again.
- Replace the keys in your hosting provider's variables. Production keys start with
pk_live_andsk_live_, then redeploy. - Add the DNS records shown on the dashboard's Domains page. Clerk says they can take up to 48 hours to propagate. On Cloudflare, set them to DNS only so Clerk's check passes.
- Create the webhook endpoint again on the production instance and store its new signing secret.
- When the dashboard checklist is complete, select Deploy certificates.
Hand this to your agent
This guide is also written out for a coding agent, as one Markdown file. It has the checks to run in your repository first, each step with its commands and code, the environment variables by name, a check after every step, and the points where the agent has to stop and ask you. Get the agent file and give your agent the file or its address.
The file keeps the agent on a development instance. Creating the webhook endpoint in the Clerk Dashboard, production keys and DNS stay with you.
Next
Once people can sign in, the next step is usually to charge them: see taking payments with Stripe. If the app is not hosted yet, start with deploying to Railway.
Sources
- Pricing, Clerk
- Managing environments, Clerk Docs
- Next.js quickstart, Clerk Docs
- clerkMiddleware() reference, Clerk Docs
- auth() reference, Clerk Docs
- Express quickstart, Clerk Docs
- requireAuth() reference, Clerk Docs
- Sync Clerk data with webhooks, Clerk Docs
- Deploy to production, Clerk Docs
Want this already wired together?
This stack is packaged as production kits you can buy and build on. If you would rather have us build it with you, book a call.
