# Next.js 16 Authentication with WorkOS AuthKit: A Practical Guide

> Next.js authentication done right: WorkOS AuthKit on Next.js 16 with proxy.ts, protected routes and server actions, organizations, SSO, and the common pitfalls.

Author: [Pavle Aleksic](https://pavlealeksic.com/about)
Published: 2026-04-26
Updated: 2026-11-03
Source: https://pavlealeksic.com/blog/nextjs-16-authentication-workos-authkit

Authentication is where most Next.js projects get ugly. It starts clean, one login form and one session cookie, and three sprints later you've got client-side token juggling, race conditions on refresh, and a `useEffect` somewhere quietly causing a redirect loop. I've built Next.js authentication on the App Router more times than I'd like to admit, and for B2B products the cleanest path I've found is WorkOS AuthKit. It keeps the session on the server where it belongs, it understands Next.js 16's request model, and it gives you organizations and enterprise SSO without a rewrite later.

This guide is for developers and technical founders setting up Next.js 16 auth, or revisiting an older setup. The short answer: in Next.js 16, `middleware.ts` is deprecated and renamed to `proxy.ts`, so AuthKit now goes in `proxy.ts` via `authkitProxy()`. The proxy keeps the session fresh, but it is not your security boundary. Check the session again with `withAuth()` in every page, Server Action, and Route Handler that touches protected data.

I updated this post in November 2026 against the current [AuthKit for Next.js README](https://github.com/workos/authkit-nextjs) and the [Next.js 16 proxy docs](https://nextjs.org/docs/app/api-reference/file-conventions/proxy). If you followed an older version of this guide, two things changed: the middleware file is now the proxy file, and sign-in URLs must be generated in a Route Handler, not while rendering a page.

## Next.js authentication options compared

Before the setup, the honest comparison. These are the five options I see most on Next.js projects. Pricing is from each vendor's pricing page as of November 2026 and changes often, so check before you commit.

| Option | Model | Where user data lives | Organizations / B2B | Enterprise SSO | Free tier (as of Nov 2026) |
|---|---|---|---|---|---|
| WorkOS AuthKit | Hosted service | WorkOS | Built in | SAML/OIDC, priced per connection | First 1M MAUs ([pricing](https://workos.com/pricing)) |
| Clerk | Hosted service with prebuilt UI | Clerk | Built in, with a B2B add-on for advanced features | One connection on Pro, more per connection | 50,000 monthly retained users ([pricing](https://clerk.com/pricing)) |
| Better Auth | Open-source library | Your database | [Organization plugin](https://www.better-auth.com/docs/plugins/organization) | [SSO plugin](https://www.better-auth.com/docs/plugins/sso) (OIDC, OAuth2, SAML) | Free (you host it) |
| Auth.js (NextAuth) | Open-source library | Your database or stateless JWT | Build it yourself | Via OIDC providers; build the rest | Free (you host it) |
| Supabase Auth | Hosted, part of Supabase | Your Supabase Postgres | Build it yourself | SAML on paid plans | 50,000 MAUs ([pricing](https://supabase.com/pricing)) |

How I choose:

- **WorkOS AuthKit** when the product is B2B and enterprise customers are likely. Organizations, SSO, and directory sync are the core of the product rather than add-ons, and the free MAU allowance is generous. You pay when customers need SSO connections, which is usually when they're paying you.
- **Clerk** when you want polished, prebuilt UI components and the fastest possible start, especially for B2C or prosumer apps. Read the per-retained-user pricing carefully if you expect a large free user base.
- **Better Auth** when you want to own your user data, avoid a per-user bill, and are happy to run it yourself. It's the open-source option I'd pick for new projects today.
- **Auth.js** for existing projects already on it. In September 2025 the Auth.js project [moved under the Better Auth team](https://www.better-auth.com/blog/authjs-joins-better-auth), who say they'll keep shipping security patches and urgent fixes but recommend Better Auth for new projects. I follow that advice.
- **Supabase Auth** when you're already on Supabase and want auth tied into its Postgres and row-level security. Outside Supabase, I wouldn't adopt it just for auth.

The rest of this post is the AuthKit setup. If you're still deciding between session strategies in general, my post on [JWTs versus session cookies](/blog/jwt-vs-session-cookies) covers the tradeoffs underneath all of these.

## Why AuthKit, and not roll-your-own

I'm not religious about auth libraries, but I am religious about not storing tokens in `localStorage` and not writing my own session refresh logic. AuthKit gives you a hosted sign-in flow (or your own UI via the API), encrypted session cookies, and server-side helpers that read the session from the request without you touching cookies directly. You get SSO, magic links, social login, and MFA behind one integration, and you can defer the "do we need enterprise SSO" decision instead of rebuilding auth when a customer asks for SAML.

Under the hood, every sign-in uses PKCE plus an encrypted OAuth state parameter for CSRF protection, per the README. That's the kind of detail I want a library to own rather than reimplement.

The tradeoffs: you're tied to WorkOS as your identity provider, and your users live in their system. If your IdP must be self-hosted or user data can't leave your infrastructure, use Better Auth instead.

## Installing and configuring

Install the package alongside the WorkOS Node SDK, which is a peer dependency:

```bash
npm install @workos-inc/authkit-nextjs @workos-inc/node
```

Then the environment variables. Get the client ID and API key from the WorkOS dashboard, and generate a cookie password of **at least 32 characters**. This is the key that encrypts your session cookie, so treat it like a secret, not a config value.

```bash
# Generate the cookie password once, then paste it into .env.local
openssl rand -base64 32
```

```bash
# .env.local
WORKOS_CLIENT_ID=client_...
WORKOS_API_KEY=sk_test_...
WORKOS_COOKIE_PASSWORD=paste-the-generated-value-here
NEXT_PUBLIC_WORKOS_REDIRECT_URI=http://localhost:3000/callback
```

A note on that last block: `.env` files don't execute shell commands, so writing `$(openssl rand ...)` inside one gives you a literal string, not a random password. Generate it, then paste it.

The API key is technically optional now. Without it, AuthKit runs as a public PKCE client that can sign users in, refresh sessions, and switch organizations, but can't call WorkOS management APIs, feature flags, or API key validation. For a real SaaS you'll want the key.

In the WorkOS dashboard, open your application's Redirects settings and configure three things:

1. The **redirect URI**, matching `NEXT_PUBLIC_WORKOS_REDIRECT_URI` exactly.
2. The **Initiate login URI**, pointing at the sign-in route we'll create below. The README notes that dashboard-initiated flows like impersonation fail without it.
3. A default **sign-out URI**, which `signOut()` needs.

A redirect URI mismatch is still the single most common reason a first integration fails: the callback comes back, WorkOS rejects the redirect, and you get a cryptic error instead of a session.

## The proxy (formerly middleware)

This is the biggest change since this post first went out. In Next.js 16, [the `middleware` file convention is deprecated and renamed to `proxy`](https://nextjs.org/docs/app/api-reference/file-conventions/proxy), and the proxy defaults to the Node.js runtime. You can't set the `runtime` option in a proxy file at all; Next.js throws if you try. If you're upgrading an app, Next.js ships a codemod:

```bash
npx @next/codemod@canary middleware-to-proxy .
```

AuthKit follows suit. On Next.js 16 you use `authkitProxy()` in `proxy.ts`; on Next.js 15 and earlier it's `authkitMiddleware()` in `middleware.ts`:

```ts
// proxy.ts (project root, next to app/)
import { authkitProxy } from "@workos-inc/authkit-nextjs";

export default authkitProxy();

export const config = {
  matcher: [
    // Everything except static assets and Next internals
    "/((?!_next/static|_next/image|favicon.ico|.*\\.(?:png|jpg|svg|webp|ico)$).*)",
  ],
};
```

The proxy does two jobs. It refreshes the session proactively when the access token is close to expiring (60 seconds before by default, configurable with `refreshBufferSeconds`), and it passes the session to your Server Components through internal request headers. That second job is why the proxy is required: `withAuth()` depends on a header the proxy sets, so **any route where you call `withAuth()` must be covered by the matcher**. If a page throws an error about AuthKit middleware not running, check the matcher before anything else.

Exclude static assets from the matcher. The README specifically warns that a catch-all matcher can intercept CSS and fonts and break styles, particularly with Tailwind CSS v4.

### Secure by default with proxy auth

By default, AuthKit checks auth per page when you call `withAuth()`. If you'd rather every matched route require a session unless you say otherwise, turn on `middlewareAuth`:

```ts
// proxy.ts
import { authkitProxy } from "@workos-inc/authkit-nextjs";

export default authkitProxy({
  middlewareAuth: {
    enabled: true,
    unauthenticatedPaths: ["/", "/pricing", "/blog/:path*", "/sign-in", "/callback"],
  },
});

export const config = {
  matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
};
```

I like this for apps where almost everything is behind login: forgetting to protect a new page fails closed. Remember to list the callback and sign-in routes as unauthenticated, or you'll build a redirect loop.

### Composing the proxy with your own logic

If you need rate limiting, redirects, or rewrites in the same file, use the lower-level `authkit()` function with `handleAuthkitHeaders()`:

```ts
// proxy.ts
import type { NextRequest } from "next/server";
import { authkit, handleAuthkitHeaders } from "@workos-inc/authkit-nextjs";

export default async function proxy(request: NextRequest) {
  const { session, headers, authorizationUrl } = await authkit(request);

  if (request.nextUrl.pathname.startsWith("/app") && !session.user && authorizationUrl) {
    return handleAuthkitHeaders(request, headers, { redirect: authorizationUrl });
  }

  return handleAuthkitHeaders(request, headers);
}

export const config = { matcher: ["/", "/app/:path*"] };
```

Always return through `handleAuthkitHeaders()`. It forwards the session to your pages, strips internal headers so they never reach the browser, and sets `Cache-Control: no-store` when cookies are present.

## Wrapping the app

The provider goes in your root layout and powers the client-side helpers like `useAuth`:

```tsx
// app/layout.tsx
import { AuthKitProvider } from "@workos-inc/authkit-nextjs/components";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <AuthKitProvider>{children}</AuthKitProvider>
      </body>
    </html>
  );
}
```

You can pass `initialAuth` from a server-side `withAuth()` call to skip a client fetch on mount, but that makes the whole layout dynamic. On a marketing-heavy site I leave the provider bare and keep the root layout static.

## Sign-in, callback, and sign-out

You need a callback route to complete the OAuth handshake. AuthKit ships the handler; put it at the path you registered as your redirect URI:

```ts
// app/callback/route.ts
import { handleAuth } from "@workos-inc/authkit-nextjs";

export const GET = handleAuth({ returnPathname: "/dashboard" });
```

`handleAuth` also takes `onSuccess` (useful for creating your own user or membership row on first login) and `onError`. If you run in Docker or behind a proxy where the request hostname differs from the public one, set `baseURL` explicitly.

For sign-in, the older version of this guide called `getSignInUrl()` inside a page component. Don't do that anymore. The README is explicit that `getSignInUrl()` and `getSignUpUrl()` set a PKCE cookie, so they belong in a Route Handler or Server Action, not in a render. Create a sign-in route and link to it:

```ts
// app/sign-in/route.ts
import { getSignInUrl } from "@workos-inc/authkit-nextjs";
import { redirect } from "next/navigation";

export async function GET() {
  redirect(await getSignInUrl());
}
```

```tsx
// Anywhere in your UI: a plain anchor, so prefetching never starts a sign-in
<a href="/sign-in">Sign in</a>
```

Use a plain `<a>`, not `next/link`, for this. You want a real navigation to start the flow, not a prefetch. Point the dashboard's Initiate login URI at this same route.

Sign-out is a Server Action calling `signOut()`, which clears the session and redirects to your sign-out URI (or `returnTo` if you pass one):

```tsx
// app/components/sign-out-button.tsx
import { signOut } from "@workos-inc/authkit-nextjs";

export function SignOutButton() {
  return (
    <form
      action={async () => {
        "use server";
        await signOut();
      }}
    >
      <button type="submit">Sign out</button>
    </form>
  );
}
```

## Protecting pages, Server Actions, and Route Handlers

Here's the rule I build every Next.js app around, and it's the same one the [Next.js authentication guide](https://nextjs.org/docs/app/guides/authentication) recommends: the proxy is an optimistic check, and the real check happens next to the data. The Next.js docs are blunt about why. Server Functions are POST requests to the route they're used on, so a matcher change or a refactor that moves an action can silently remove proxy coverage. Check auth inside each one.

### A small data access layer

I wrap `withAuth()` once and call the wrapper everywhere:

```ts
// lib/auth.ts
import "server-only";
import { cache } from "react";
import { withAuth } from "@workos-inc/authkit-nextjs";

export const requireSession = cache(async () => {
  const auth = await withAuth({ ensureSignedIn: true });
  return auth; // user, sessionId, organizationId, role, permissions, ...
});

export async function requireOrgPermission(permission: string) {
  const auth = await withAuth();
  if (!auth.user || !auth.organizationId) {
    throw new Error("UNAUTHENTICATED");
  }
  if (!auth.permissions?.includes(permission)) {
    throw new Error("FORBIDDEN");
  }
  return auth;
}
```

The `server-only` import makes the build fail if this file ever ends up in a client bundle. React's `cache` dedupes the call within a single render; per the Next.js docs it does nothing in Server Actions and Route Handlers, which is fine, because those run once per request anyway.

### Pages

```tsx
// app/dashboard/page.tsx
import { requireSession } from "@/lib/auth";

export default async function DashboardPage() {
  const { user } = await requireSession();

  return <h1>Welcome back, {user.firstName ?? user.email}</h1>;
}
```

`ensureSignedIn: true` redirects to AuthKit when there's no session. Use plain `withAuth()` and branch on `user` when you want to render a signed-out state instead.

Don't put your only auth check in a layout. Next.js docs point out that layouts don't re-render on client navigation and don't control whether child segments render. Check in the page or, better, in the data function.

### Server Actions

Treat every Server Action as a public HTTP endpoint, because that's what it is:

```ts
// app/projects/actions.ts
"use server";

import { requireOrgPermission } from "@/lib/auth";
import { db } from "@/lib/db";
import { revalidatePath } from "next/cache";

export async function deleteProject(projectId: string) {
  const { organizationId } = await requireOrgPermission("projects:delete");

  // Scope the write to the caller's organization, never trust the id alone.
  await db.project.deleteMany({ where: { id: projectId, organizationId } });

  revalidatePath("/projects");
}
```

Two things there are doing the security work: the permission check, and the `organizationId` in the `where` clause. Without the second, any signed-in user who guesses an ID can delete another customer's project. I wrote more about the action-specific pitfalls in [Server Actions in Next.js 16](/blog/nextjs-server-actions-forms-mutations).

For destructive operations (deleting an account, changing billing, rotating keys), AuthKit has `checkRecentAuth({ maxAge })`, which reports whether the user authenticated recently and fails closed. If the session is stale, send them through `getSignInUrl({ maxAge })` to force a fresh login.

### Route Handlers

Route Handlers are consumed by clients, not browsers following redirects, so return status codes instead of redirecting:

```ts
// app/api/projects/route.ts
import { withAuth } from "@workos-inc/authkit-nextjs";
import { NextResponse } from "next/server";

export async function GET() {
  const { user, organizationId, permissions } = await withAuth();

  if (!user || !organizationId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  if (!permissions?.includes("projects:read")) {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  }

  const projects = await getProjectsForOrg(organizationId);
  return NextResponse.json({ projects });
}
```

`401` means "who are you?", `403` means "I know who you are, and no." Clients handle them differently, so don't collapse them.

### Client Components

Client Components get the session through `useAuth()` from `@workos-inc/authkit-nextjs/components`. Use it for UI only: showing a name, hiding a button. A hidden button is not access control. The Server Action behind it still checks.

## Organizations, roles, and SSO

This is where AuthKit earns its place in B2B products. A WorkOS user can belong to multiple organizations, and the session is scoped to one of them at a time. `withAuth()` returns the active `organizationId` along with `role`, `roles`, and `permissions` from the access token, which means your authorization checks read from the session instead of hitting a database on every request.

Switching organizations is a Server Action:

```ts
// app/org/actions.ts
"use server";

import { switchToOrganization } from "@workos-inc/authkit-nextjs";

export async function switchOrg(organizationId: string) {
  // Refreshes the session for the new org; if that org requires SSO or MFA,
  // AuthKit redirects the user through it.
  await switchToOrganization(organizationId, { returnTo: "/dashboard" });
}
```

On the client, `refreshAuth({ organizationId })` from `useAuth()` does the same. And when you change a user's role in WorkOS, call `refreshSession()` so the new permissions show up without forcing a sign-out.

Enterprise SSO is mostly configuration: you create an SSO connection for the customer's organization in WorkOS, and users from that domain sign in through their identity provider. Your Next.js code doesn't change. That's the whole argument for picking an SSO-ready provider early: the first enterprise deal shouldn't turn into an auth migration. If you're designing the role model itself, my post on [designing a permissions system](/blog/designing-a-permissions-system) covers how to structure roles and permissions so custom roles are possible later.

One design point: keep your own `organizations` table keyed on the WorkOS organization ID, and use it as the tenant key for your data. WorkOS owns identity; your database owns everything else. I go deeper on tenancy in [building a SaaS that scales](/blog/building-a-saas-that-scales).

## Session handling and caching

AuthKit stores the session in an encrypted, HTTP-only cookie. The access token is short-lived and the proxy refreshes it before it expires. If a refresh fails while the access token is still valid, AuthKit keeps using the current token, and only clears the session once it actually expires. That makes transient network blips a non-event.

Things to know about how this interacts with Next.js 16 rendering:

- **`withAuth()` makes the route dynamic.** It reads request headers, so the page can't be prerendered. That's correct: an authenticated page shouldn't be cached at build time. But calling it in a shared layout makes every page under that layout dynamic, so keep auth reads as close to the protected leaf as you can.
- **Never cache per-user data across users.** Runtime APIs like `cookies()` and `headers()` can't be used inside a `"use cache"` scope. Read the session outside, then pass the user or organization ID into the cached function as an argument so it becomes part of the cache key. My post on [Next.js 16 caching](/blog/nextjs-16-caching-demystified) covers the model in detail.
- **Stream around the session.** If only a user menu needs the session, put it in its own Server Component inside `Suspense` so the rest of the page isn't blocked. See [streaming and Suspense in the App Router](/blog/nextjs-streaming-suspense-app-router).
- **Don't ship the access token to the client** unless a client-side API call genuinely needs it. If one does, `useAccessToken()` handles refresh for you, and the token stays in memory rather than in `localStorage`.

## Common pitfalls

The issues I see most often when I'm asked to fix someone's Next.js auth:

1. **Still using `middleware.ts` on Next.js 16.** It's deprecated. Rename to `proxy.ts`, switch to `authkitProxy()`, and run the codemod.
2. **Trying to force the Edge runtime.** Proxy runs on Node.js, and setting `runtime` in a proxy file throws.
3. **Calling `withAuth()` on a route the matcher doesn't cover.** It needs the proxy's header. Widen the matcher.
4. **Generating sign-in URLs during render.** `getSignInUrl()` sets a PKCE cookie. Use a Route Handler.
5. **Linking to sign-in with `next/link`.** Prefetching can start flows you didn't intend. Use a plain anchor.
6. **Wrapping `withAuth({ ensureSignedIn: true })` in try/catch.** The redirect is implemented by throwing, so you'll catch it and get a `NEXT_REDIRECT` error. Let redirects propagate.
7. **Importing `withAuth` into a Client Component.** You'll get a `node:crypto` build error. Use `useAuth()` there.
8. **Relying on the proxy alone.** Every Server Action and Route Handler checks the session and the organization itself.
9. **Queries scoped by record ID only.** Always include the organization ID. Authentication tells you who; the `where` clause enforces what.
10. **A reverse proxy or CDN stripping `Set-Cookie` on redirects.** You'll see "Sign-in session could not be verified" errors because the PKCE verifier cookie never comes back. Make sure cookies survive the redirect round-trip.

## Security checklist

Before you ship, walk this:

- `WORKOS_COOKIE_PASSWORD` is 32+ characters, unique per environment, and stored as a secret, never committed. More on that in [secrets management](/blog/secrets-management).
- Redirect URI, Initiate login URI, and sign-out URI are registered for each environment, with production separate from local.
- `proxy.ts` uses `authkitProxy()` and its matcher covers every route that calls `withAuth()`, while excluding static assets.
- Every protected page, Server Action, and Route Handler reads the session itself and handles the no-user case.
- Every data query is scoped by organization, not only by record ID.
- Route Handlers return `401` or `403` rather than redirecting or leaking data.
- No per-user response is cached across users.
- Session cookies stay HTTP-only and `Secure` in production, and `WORKOS_COOKIE_SAMESITE` isn't set to `none` unless you truly need cross-site cookies.
- Sensitive actions use `checkRecentAuth()`.
- Sign-out clears the session server-side, not just client state.

Get those right and auth stops being the ugly part of the project. It becomes the boring part, which, for authentication, is exactly what you want. For the broader security picture, the [OWASP Top 10 for full-stack developers](/blog/owasp-top-10-fullstack-2026) is a good next read.

## Frequently asked questions

### Is middleware.ts deprecated in Next.js 16?

Yes. Next.js 16 deprecates the `middleware` file convention and renames it to `proxy`, so you create `proxy.ts` and export a `proxy` function (or a default export). The behavior is the same, it defaults to the Node.js runtime, and Next.js provides a `middleware-to-proxy` codemod for the rename.

### What is the best authentication library for Next.js?

It depends on who your customers are. For B2B SaaS that will need organizations and enterprise SSO, I use WorkOS AuthKit. For the fastest start with prebuilt UI, Clerk. To own your user data without a per-user bill, Better Auth. For new projects I no longer start on Auth.js, since its maintainers now recommend Better Auth.

### How do I protect Server Actions in Next.js?

Check the session inside every Server Action, not just in the proxy or the page that renders the form. Server Actions are POST endpoints anyone can call. Verify the user, check the specific permission, and scope every database write to the user's organization.

### Can I use WorkOS AuthKit without an API key?

Yes. Without `WORKOS_API_KEY`, AuthKit runs as a public PKCE client and still supports sign-in, session refresh, `withAuth()`, organization switching, and sign-out. You need the key for WorkOS management APIs, the feature flag runtime client, and API key validation.

### Does WorkOS AuthKit support organizations and SSO?

Yes, and that's the main reason I pick it for B2B products. Users can belong to multiple organizations, the session carries the active organization with its role and permissions, and `switchToOrganization()` moves between them. SSO connections are configured per organization, and the Next.js code doesn't change.

### How much does WorkOS AuthKit cost?

As of November 2026, WorkOS lists AuthKit as free for the first million monthly active users, with enterprise SSO and directory sync priced per connection. Check the [WorkOS pricing page](https://workos.com/pricing) for current numbers, since vendor pricing changes.

### Why does withAuth() make my page dynamic?

Because it reads the request to find the session, and anything request-specific can't be prerendered at build time. That's the correct behavior for an authenticated page. Avoid calling it in shared layouts, so public pages under the same layout can stay static.

## Working with me

If you're adding auth to a Next.js app, migrating off an older setup, or getting a B2B product ready for its first enterprise SSO request, I've done this many times across SaaS products. I build and rescue Next.js applications end to end, including the multi-tenant and permissions work that sits behind the login screen. See how I approach [SaaS development](/services/saas) and [frontend work](/services/frontend), or [get in touch](/contact) and tell me where your auth stands today.
