---
title: "How to add authentication to a Next.js SaaS app"
description: "Add authentication to a Next.js App Router app with WorkOS AuthKit, then layer on organizations, roles, enterprise SSO (SAML and OIDC), and SCIM for B2B SaaS."
url: https://workos.com/blog/how-to-add-authentication-to-a-nextjs-saas-app
published: "Dec 01, 2026"
---

# How to add authentication to a Next.js SaaS app

Adding sign-in to a Next.js app is a solved problem. The harder question comes later, when your first enterprise prospect sends a security questionnaire asking for SAML single sign-on, SCIM provisioning, and per-customer roles.

This guide covers the full path for a B2B Next.js App Router app with WorkOS AuthKit: setup, sessions, protected routes and server actions, organizations and roles, and then the part where B2B differs, enterprise SSO and directory sync. It is one integration, so you add the enterprise features without replacing the login you started with.

## How do you add authentication to a Next.js app with AuthKit?

To add authentication to a Next.js App Router app with WorkOS AuthKit, you need five pieces:

1. **The SDK.** Install `@workos-inc/authkit-nextjs`.
2. **A callback route.** `handleAuth()` exchanges the authorization code for a session.
3. **A proxy.** `proxy.ts` with `authkitProxy` keeps the session fresh on every request.
4. **A sign-in route.** It redirects to AuthKit using `getSignInUrl()`.
5. **`withAuth` calls.** Use them wherever server code needs the current user.

For B2B, you then add two more things:

- **Organizations and roles** for each customer account.
- **Enterprise SSO and directory sync**, turned on per customer when they ask for them.

You can generate the setup with `npx workos@latest install`, or write it by hand with the steps below.

![Two flows in a Next.js app using WorkOS AuthKit. Sign-in: the browser requests your login route, which redirects to AuthKit hosted pages using getSignInUrl; AuthKit returns the user to your callback route, where handleAuth creates the session. Every later request: the browser sends the session cookie to proxy.ts, where authkitProxy refreshes the session, then to a page, server action or route handler that calls withAuth.](https://cdn.prod.website-files.com/621f84dc15b5ed16dc85a18a/6b0f1c7d2045444de787d7f9_authkit-nextjs-request-flow.webp)

*How the five pieces fit together: sign-in happens once, the proxy and withAuth run on every request.*

## What should you look for in authentication for a Next.js app?

Look for a provider that understands where your code actually runs. In the App Router that is four places: the proxy (called middleware before Next.js 16), server components, server actions and route handlers, and client components. An auth layer built for client-side single-page apps tends to fit awkwardly across all four.

Four things are worth checking:

- **Server-side session reads.** You should be able to get the current user inside a server component or server action without an extra client round trip.
- **Proxy integration.** Session refresh should happen in the proxy, so pages and actions see a valid session on every request.
- **Cookie and token handling.** Look for encrypted, HTTP-only session cookies, short-lived access tokens with refresh, and sign-out that ends the session at the provider rather than only clearing your own cookie.
- **Tenant context in the session.** If your product has customers rather than just users, the active organization and role should arrive with the session instead of coming from a database lookup on every request.

WorkOS AuthKit's Next.js SDK, `@workos-inc/authkit-nextjs`, is built around that model. For a broader look at how providers compare on these criteria, see [Top 5 authentication solutions for secure Next.js apps in 2026](https://workos.com/blog/top-authentication-solutions-nextjs-2026).

### When does a B2B app need more than social login?

Social login and email-and-password cover most consumer and prosumer apps. They stop being enough when a customer's security team gets involved.

The usual triggers are the same across B2B products:

- A buyer requires sign-in through their own identity provider (Okta, Microsoft Entra ID, Google Workspace, and so on) over SAML or OIDC.
- A buyer wants accounts created and removed automatically from their directory through SCIM, so leavers lose access without a support ticket.
- Different customers need different roles, and one person may belong to more than one customer.
- The person configuring it is a customer IT admin, not your engineer.

The structural difference is that social login is one integration per provider, while enterprise SSO is one integration per customer. That is why the later sections of this guide center on organizations, not just users.

## How do you set up AuthKit in a Next.js app?

Before you start, you need:

- **A** [**WorkOS account**](https://dashboard.workos.com/) (free to start), with your API key and client ID from the dashboard.
- **Node.js 22.11 or later.** Check the `engines` field of the SDK version you install, since it can require a newer Node release.
- **A Next.js app that uses the App Router.**

There are two paths. This section is the short version; [How to add AuthKit to a Next.js app](https://workos.com/blog/add-authkit-to-a-nextjs-app) walks through each step with troubleshooting.

### Set up automatically with the AuthKit installer

Run this from the root of your project:

```js
npx workos@latest install
```

The installer detects Next.js, installs `@workos-inc/authkit-nextjs`, configures your dashboard redirects, creates the callback route and `proxy.ts`, wraps your root layout in `AuthKitProvider`, writes your keys to `.env.local`, and runs a build to confirm everything compiles. Run `git diff` afterward to review what it changed.

### Set up manually in five steps

The manual path is five small steps, and it is worth reading even if you use the installer, so you know what the generated code does.

#### Step 1: Install the SDK

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

`@workos-inc/node` is a peer dependency of the AuthKit library.

#### Step 2: Set your environment variables

```js
# .env.local
WORKOS_API_KEY='sk_test_...'
WORKOS_CLIENT_ID='client_...'
WORKOS_COOKIE_PASSWORD='<at least 32 characters>'
NEXT_PUBLIC_WORKOS_REDIRECT_URI='http://localhost:3000/callback'
```

The cookie password encrypts the session cookie. Generate one with `openssl rand -base64 32`. The `NEXT_PUBLIC_` prefix on the redirect URI makes it readable in the proxy, which matters for setups like Vercel preview deployments.

#### Step 3: Configure redirects in the dashboard

In the WorkOS dashboard, open **Applications**, select your app, and go to the **Redirects** tab. Set three things:

- **Redirect URI:** `http://localhost:3000/callback`. It must match `NEXT_PUBLIC_WORKOS_REDIRECT_URI` exactly.
- **Initiate login URI:** `http://localhost:3000/login`. Sign-in does not always start in your app, for example when a user follows an invitation or password reset email. AuthKit sends those requests here, and this route has to start an AuthKit sign-in rather than render your own form.
- **Sign-out URI:** a default page to land on after sign-out. Without one, users see an error when they sign out.

#### Step 4: Add the callback route

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

// Exchanges the authorization code for a session, then redirects to `/`.
// Customize the destination with handleAuth({ returnPathname: '/dashboard' }).
export const GET = handleAuth();
```

#### Step 5: Wrap your app in the provider

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

`AuthKitProvider` supplies client-side auth state and handles auth edge cases. Next comes the sign-in flow, followed by the proxy that `withAuth` depends on.

## How do sign-in, sign-up, and sessions work in the App Router?

Sign-in and sign-up run on AuthKit's hosted pages, so you do not build forms for passwords, email verification, MFA, or social login. Your app does three things: send the user to AuthKit, handle the callback you set up above, and read the session on the server.

### How do you add the sign-in and sign-up routes?

Generate the AuthKit URL in a route handler and redirect to it. This is the route you registered as the Initiate login URI.

```js
// app/login/route.ts
import { getSignInUrl } from '@workos-inc/authkit-nextjs';
import { redirect } from 'next/navigation';

export const GET = async () => {
  const signInUrl = await getSignInUrl();
  return redirect(signInUrl);
};
```

```js
// app/sign-up/route.ts
import { getSignUpUrl } from '@workos-inc/authkit-nextjs';
import { redirect } from 'next/navigation';

export const GET = async () => redirect(await getSignUpUrl());
```

Two details matter here. `getSignInUrl()` and `getSignUpUrl()` set a short-lived PKCE cookie, so call them from a route handler or server action, not while rendering a server component. And link to these routes with a plain `<a>` tag so that a click, not a prefetch, starts the flow.

### Get the current user in server and client components

In a server component, call `withAuth`. It returns the user from the session, or `null` if nobody is signed in.

```js
// app/page.tsx
import { signOut, withAuth } from '@workos-inc/authkit-nextjs';

export default async function HomePage() {
  const { user } = await withAuth();

  if (!user) {
    return (
      <main>
        <h1>Welcome</h1>
        <a href="/login">Sign in</a> | <a href="/sign-up">Sign up</a>
      </main>
    );
  }

  return (
    <main>
      <h1>Welcome back{user.firstName && `, ${user.firstName}`}</h1>
      <form
        action={async () => {
          'use server';
          await signOut();
        }}
      >
        <button type="submit">Sign out</button>
      </form>
    </main>
  );
}
```

In a client component, use the `useAuth` hook instead. Do not import `withAuth` into a client component, since it is server-only code.

```js
'use client';
import { useAuth } from '@workos-inc/authkit-nextjs/components';

export function UserBadge() {
  const { user, loading } = useAuth();

  if (loading) return <span>Loading...</span>;
  return <span>{user ? user.email : 'Signed out'}</span>;
}
```

### Session refresh and sign-out

After the callback, the session lives in an encrypted cookie (named `wos-session` by default) that holds the user, an access token, and a refresh token. The proxy decrypts it on each request and refreshes it shortly before the access token expires, 60 seconds by default, so server components rarely see an expired token. You can tune that window with the `refreshBufferSeconds` option.

If a user's role or permissions change while they are signed in, call `refreshSession()` from a server action or route handler to pull the latest values into the session.

`signOut()` ends the session at WorkOS and then redirects to your Sign-out URI. Ending it at WorkOS matters because clearing only your own cookie can leave an identity provider session alive, which silently signs the user back in.

## How do you protect routes and server actions?

Use two layers. The proxy keeps the session fresh and redirects signed-out users away from pages. The pages, server actions, and route handlers that touch data then check the session themselves. The proxy alone is not a security boundary, which [the App Router guide](https://workos.com/blog/nextjs-app-router-authentication-guide-2026) covers in detail.

### How do you protect routes with the proxy?

Create `proxy.ts` in the project root for Next.js 16 and later. In Next.js 15 and earlier the file is `middleware.ts` and the code is identical: `authkitMiddleware` is only a deprecated alias of `authkitProxy`, so use `authkitProxy` in both. The example below uses middleware auth mode, which protects every matched route unless you list it as public.

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

export default authkitProxy({
  middlewareAuth: {
    enabled: true,
    unauthenticatedPaths: ['/', '/pricing', '/login', '/sign-up', '/callback'],
  },
});

// Exclude static assets so a broad matcher does not break your CSS and images.
export const config = {
  matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
};
```

If you would rather decide per page, leave `middlewareAuth` out and call `withAuth({ ensureSignedIn: true })` in the pages that need it. Either way, the matcher must include every path that calls `withAuth`, because `withAuth` relies on the proxy having run first.

```js
// app/dashboard/page.tsx
import { withAuth } from '@workos-inc/authkit-nextjs';

export default async function DashboardPage() {
  // Redirects to AuthKit if there is no session.
  const { user } = await withAuth({ ensureSignedIn: true });
  return <h1>Dashboard for {user.email}</h1>;
}
```

If your proxy also does rate limiting, redirects, or rewrites, use the composable `authkit()` function and return responses through `handleAuthkitProxy()`, which keeps the session cookie and internal headers intact:

```js
// proxy.ts
import { NextRequest } from 'next/server';
import { authkit, handleAuthkitProxy } 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 handleAuthkitProxy(request, headers, { redirect: authorizationUrl });
  }

  return handleAuthkitProxy(request, headers);
}

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

### How do you protect server actions and route handlers?

Check the session inside every server action and route handler that reads or writes data. A server action is a request your server accepts on its own, so a page-level redirect does not protect it.

```js
// app/actions/projects.ts
'use server';

import { withAuth } from '@workos-inc/authkit-nextjs';
import { db } from '@/lib/db'; // your data layer

export async function renameProject(projectId: string, name: string) {
  const { organizationId, permissions } = await withAuth({ ensureSignedIn: true });

  if (!organizationId) throw new Error('No active organization');
  if (!permissions?.includes('projects:write')) throw new Error('Forbidden');

  // Scope the lookup to the active organization, never to an ID from the client.
  const project = await db.project.findFirst({ where: { id: projectId, organizationId } });
  if (!project) throw new Error('Not found');

  await db.project.update({ where: { id: project.id }, data: { name } });
}
```

For a JSON route handler, call `withAuth()` without `ensureSignedIn` and return a 401 yourself:

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

export async function GET() {
  const { user, organizationId } = await withAuth();
  if (!user || !organizationId) {
    return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
  }
  // ...query reports where organizationId matches
  return NextResponse.json({ ok: true });
}
```

Two more notes. Do not wrap `withAuth({ ensureSignedIn: true })` in a `try/catch`, because it redirects by throwing, and the catch will swallow the redirect. And for sensitive actions such as deleting an account, `checkRecentAuth({ maxAge: 300 })` lets you require a recent sign-in, as described in the [AuthKit Next.js docs](https://workos.com/docs/sdks/authkit-nextjs).

## How do organizations and roles work in a multi-tenant app?

In WorkOS, an organization represents one of your customers. A user joins an organization through a membership, and each membership has a role. The session carries the active organization, so `withAuth` returns `organizationId`, `role`, and `permissions` for the organization the user is currently acting in. A user can be an admin in one organization and a viewer in another, and the session reflects whichever one is active.

![Data model for a multi-tenant B2B app on WorkOS AuthKit. Each customer is an organization. Users join an organization through a membership that carries a role and permissions. An organization has a verified domain, one SSO connection (SAML or OIDC), and can have a directory connected through SCIM, which provisions memberships.](https://cdn.prod.website-files.com/621f84dc15b5ed16dc85a18a/6b0f1cad05e6beed995742c4_organization-sso-directory-model.webp)

*One organization per customer. SSO, directory sync, and roles all hang off the same object.*

This section covers the essentials. The full treatment, including invitations, organization switchers, and subdomain routing, is in [How to add multi-tenant authentication to your Next.js SaaS](https://workos.com/blog/nextjs-multi-tenant-authentication-guide).

### How do you create an organization?

Create the organization and the first membership, then switch the session to it. Use a role slug that you have defined under **Roles** in the WorkOS dashboard. See the [roles and permissions docs](https://workos.com/docs/authkit/roles-and-permissions) for how roles and permissions are modeled.

```js
// app/actions/create-organization.ts
'use server';

import { getWorkOS, refreshSession, withAuth } from '@workos-inc/authkit-nextjs';
import { redirect } from 'next/navigation';

export async function createOrganization(formData: FormData) {
  const { user } = await withAuth({ ensureSignedIn: true });
  const workos = getWorkOS();

  const organization = await workos.organizations.createOrganization({
    name: String(formData.get('name')),
  });

  await workos.userManagement.createOrganizationMembership({
    organizationId: organization.id,
    userId: user.id,
    roleSlug: 'admin',
  });

  // Store organization.id in your own database here, keyed to your tenant record.

  // Make the new organization the active one in the session.
  await refreshSession({ organizationId: organization.id });
  redirect('/dashboard');
}
```

New users who sign up without an invitation have a valid session but no active organization. Send them to a create-organization step rather than rendering a dashboard with no tenant behind it.

### How do you check roles and permissions?

Permissions arrive with the session, so a check is a lookup, not a database query. Wrap it in a helper and call it at the top of every server action:

```js
// lib/auth.ts
import { withAuth } from '@workos-inc/authkit-nextjs';

export async function requirePermission(permission: string) {
  const { user, organizationId, permissions } = await withAuth({ ensureSignedIn: true });

  if (!organizationId) throw new Error('No active organization');
  if (!permissions?.includes(permission)) throw new Error('Forbidden');

  return { user, organizationId };
}
```

Always take `organizationId` from the session and never from a URL segment or form field. A user can edit those, and the session cannot be edited.

### How do users switch organizations?

Call `refreshSession` with the target `organizationId` from a server action. The session comes back with that organization's role and permissions. If the session is not authorized for the target organization, for example because that organization requires SSO, the call returns an authentication error that your code should handle.

```js
// app/actions/switch-organization.ts
'use server';

import { refreshSession } from '@workos-inc/authkit-nextjs';

export async function switchOrganization(organizationId: string) {
  await refreshSession({ organizationId });
}
```

## How do you add enterprise SSO (SAML or OIDC) for a customer?

This is the step where B2B apps differ from consumer apps, and the code you write for it is small. Your Next.js app already redirects to AuthKit and handles the callback. SSO adds a dashboard setting, an organization with a verified domain, and a way for the customer's IT admin to configure their own identity provider. The SAML and OIDC handshakes stay outside your codebase.

### How does AuthKit route users to the right identity provider?

Turn on **Single Sign-On** under **Authentication** in the WorkOS dashboard. From then on, AuthKit checks whether a user is eligible for SSO when they sign in or sign up, and routes them based on organizations that have verified their email domain:

- If an organization's domain policy requires SSO for that domain, the user goes straight to that organization's identity provider.
- If the user is an active member of exactly one organization that verified the domain, that organization's policy applies.
- Otherwise, when shared-domain discovery is enabled, AuthKit offers the eligible SSO connections on the domain and asks the user to choose when there is more than one.

![Decision flow for how AuthKit routes a sign-in when Single Sign-On is enabled. If an organization requires SSO for the email domain, the user goes straight to that organization's identity provider. Otherwise, if the user is an active member of exactly one organization that verified the domain, that organization's policy applies. Otherwise, if shared-domain discovery is enabled, AuthKit offers the eligible SSO connections and the user chooses when there is more than one.](https://cdn.prod.website-files.com/621f84dc15b5ed16dc85a18a/6b0f1cdaf1a4c58dcd71eb6e_authkit-sso-routing.webp)

*How AuthKit decides where to send a sign-in once SSO is on.*

None of this requires changes to your `/login` route or your callback. After an SSO sign-in, `withAuth` returns the same kind of `user` and session as any other method, with `organizationId` set to the organization the user signed in through. The [organization policies docs](https://workos.com/docs/authkit/organization-policies) describe the policy options in detail.

### How do you test SSO before you have a customer?

Every staging environment includes a test organization with an active SSO connection backed by a Test Identity Provider. Open the **Test SSO** page in the dashboard and run its scenarios: sign-in that starts in your app, sign-in that starts from the identity provider, a guest user whose email domain differs from the organization's, and an identity provider error. The identity-provider-initiated case is the one teams tend to forget, because it never starts at your `/login` route.

### How do you onboard a customer's IT admin?

Create an organization for the customer and record the domain they will verify. Keep `organization.id` in your own database.

```js
// app/actions/provision-customer.ts
'use server';

import { getWorkOS } from '@workos-inc/authkit-nextjs';
import { DomainDataState } from '@workos-inc/node';

export async function provisionCustomer(name: string, domain: string) {
  const organization = await getWorkOS().organizations.createOrganization({
    name,
    domainData: [{ domain, state: DomainDataState.Pending }],
  });

  // Persist organization.id with your tenant record.
  return organization.id;
}
```

Then give the IT admin a way into the Admin Portal, a hosted, WorkOS-maintained setup flow with step-by-step instructions for each identity provider. Generate a portal link from a route that only authorized admins can reach, and redirect immediately, because portal links expire after five minutes.

```js
// app/settings/sso/route.ts
import { NextResponse } from 'next/server';
import { getWorkOS, withAuth } from '@workos-inc/authkit-nextjs';

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

  // 'org:sso:configure' is a permission you define in the dashboard.
  if (!organizationId || !permissions?.includes('org:sso:configure')) {
    return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
  }

  const { link } = await getWorkOS().adminPortal.generateLink({
    organization: organizationId,
    externalUserId: user.id, // lets you revoke this admin's portal access later
    intent: 'sso',
  });

  return NextResponse.redirect(link);
}
```

The admin follows the guided steps, pastes in their identity provider's metadata, and the connection goes live. The same call supports other intents, including `dsync` for directory sync and `domain_verification` for the DNS record that proves domain ownership. Unless an organization allows any domain, SSO needs a verified domain to activate, and an organization has a single SSO connection. If a customer reports a broken connection, `workos debug-sso <connection_id>` from the WorkOS CLI shows the connection's state and recent authentication events.

### How do you scope sign-in to a known customer's organization?

When you already know the tenant, for example on a customer subdomain or behind a "Sign in with SSO" button, pass the organization to the sign-in URL so AuthKit scopes the sign-in to that organization, instead of relying on email-based discovery:

```js
// app/login/sso/route.ts
import { getSignInUrl } from '@workos-inc/authkit-nextjs';
import { redirect } from 'next/navigation';

export const GET = async (request: Request) => {
  const organizationId = new URL(request.url).searchParams.get('org') ?? undefined;
  return redirect(await getSignInUrl({ organizationId }));
};
```

For a broader view of what changes when SSO reaches production, the [Express.js version of this guide](https://workos.com/blog/how-to-add-enterprise-sso-express-js-api) covers pitfalls such as validating tenants by organization ID rather than by email domain, which applies equally to a Next.js app.

## How do you add SCIM directory sync?

SSO controls how people sign in. Directory sync controls who has an account at all. Once SSO is live, enterprise IT teams usually ask for the second half: when someone joins the company, they get access to your app, and when they leave, they lose it, without anyone filing a ticket.

### What does directory sync add on top of SSO?

Directory Sync connects your app to a customer's directory, such as Okta, Microsoft Entra ID, Google Workspace, or Workday, over SCIM. Each directory provider implements SCIM a little differently, so WorkOS normalizes them into one set of directories, groups, users, and events. See the [Directory Sync docs](https://workos.com/docs/directory-sync) for the full model.

With AuthKit there is one distinction worth knowing. Directory Sync alone does not create AuthKit users. **Directory provisioning** builds on it, and does:

| Behavior | Directory Sync alone | With directory provisioning |
| --- | --- | --- |
| AuthKit user created per directory user | No | Yes |
| Organization membership created | No | Yes, marked as directory-managed |
| Group-to-role mapping | Applied to the directory user | Applied to the membership and the access token claims |
| User removed in the directory | Directory user updated | Membership deactivated |

Directory groups are not mirrored into AuthKit groups, but group-to-role mappings still apply to the membership. A directory user needs a primary email address to be provisioned. The [directory provisioning docs](https://workos.com/docs/authkit/directory-provisioning) list each action and the events it emits.

### How do you turn on directory sync for a customer?

Use the same Admin Portal route as for SSO and change the intent. The IT admin then follows the guided setup for their directory provider.

```js
const { link } = await getWorkOS().adminPortal.generateLink({
  organization: organizationId,
  externalUserId: user.id,
  intent: 'dsync',
});
```

One operational point: deleting a directory in the Admin Portal does not automatically revoke access for users it provisioned. They keep their accounts, memberships, roles, and sessions, so remove access first if that is what the customer intends.

### Handle provisioning events with webhooks

WorkOS sends webhooks as directories change. Create a route handler, verify the signature, and update your own records. Keep your database keyed to WorkOS IDs, because email addresses change.

```js
// app/api/webhooks/workos/route.ts
import { getWorkOS } from '@workos-inc/authkit-nextjs';
import { NextResponse } from 'next/server';

export async function POST(request: Request) {
  const payload = await request.json();
  const sigHeader = request.headers.get('workos-signature') ?? '';

  let event;
  try {
    event = await getWorkOS().webhooks.constructEvent({
      payload,
      sigHeader,
      secret: process.env.WORKOS_WEBHOOK_SECRET!,
    });
  } catch {
    return NextResponse.json({ error: 'Invalid signature' }, { status: 400 });
  }

  switch (event.event) {
    case 'organization_membership.updated':
      // With directory provisioning, a deprovisioned user's membership becomes inactive.
      // Revoke access to anything your app tracks outside the session.
      break;

    case 'dsync.user.updated':
      // Most providers soft-delete: the user arrives here with state 'inactive'.
      break;

    case 'dsync.user.deleted':
      // A hard delete in the directory. Remove the user from your own records.
      break;
  }

  return NextResponse.json({ received: true });
}
```

Register the endpoint under **Webhooks** in the dashboard and store the signing secret as `WORKOS_WEBHOOK_SECRET`. Because WorkOS calls this route without a session, add `/api/webhooks/workos` to `unauthenticatedPaths` in your proxy, or exclude it from the matcher. During a directory's first sync you receive a `dsync.user.created` event for every existing user, so make your handler safe to run more than once for the same user.

For a provider-specific walkthrough, see [How to sync users from Entra ID to your app using Node and WorkOS](https://workos.com/blog/sync-users-from-entra-id-using-node-and-workos).

## How does AuthKit differ from consumer-focused auth providers?

Consumer-focused providers are designed around the individual user: sign-up, sign-in, social login, passwordless, and MFA. If that is all your app needs, the setup in the first half of this guide is similar in shape to what any of them requires, and you may not need more.

The differences show up once you sell to organizations. Some providers in this category also offer organizations and enterprise SSO, and the details change over time, so check each vendor's current documentation and pricing. The table lists the questions that separate the options, and how AuthKit answers each one.

| Concern | In AuthKit | What to check with any provider |
| --- | --- | --- |
| Tenant model | Organizations with memberships and per-organization roles. The session carries the active organization, role, and permissions. | Does the session carry an organization and role, or do you map them yourself? |
| Enterprise SSO | SAML and OIDC through the same sign-in flow, routed by verified domain or by organization. | Is SSO part of the same integration or a separate product? |
| Customer IT setup | A hosted Admin Portal link, generated per organization, with setup guides per identity provider. | Can a customer’s IT admin self-serve, or does your team handle each setup? |
| Provisioning | SCIM through Directory Sync, with directory provisioning into organization memberships. | Are deprovisioned users’ sessions revoked automatically? |
| Pricing unit | AuthKit is free up to 1 million monthly active users. Enterprise SSO connections are priced per connection. | What counts as a billable unit, and at what point do SSO and SCIM add cost? |

Current prices are on the [WorkOS pricing page](https://workos.com/pricing). The main trade-off is scope: AuthKit puts the organization at the center of the model from the start, which is more structure than a single-tenant consumer app needs.

## Common mistakes to avoid

- **Relying on the proxy alone.** The proxy handles redirects and session refresh. Re-check the session in every page, server action, and route handler that touches data.
- **Using a catch-all matcher without exclusions.** A pattern that matches `_next/static` intercepts your CSS and images. Exclude static paths, as in the example above.
- **Reading the tenant from the URL or a form field.** Take `organizationId` from `withAuth`, then scope every query to it.
- **Calling `getSignInUrl()` while rendering a server component, or linking with a prefetching `<Link>`.** Generate the URL in a route handler and link with a plain `<a>`.
- **Skipping the Initiate login URI or Sign-out URI.** Invitation and password reset links need the first, and users see an error on sign-out without the second.
- **Putting the webhook route behind the proxy.** WorkOS calls it without a session, so list it in `unauthenticatedPaths` or exclude it from the matcher.
- **Identifying a customer by email domain.** Enterprises have contractors and guests with other domains. Use the organization ID from the session.
- **Assuming deleting a directory removes access.** Users a directory provisioned keep their accounts and sessions until you remove them.

## Frequently asked questions

### What authentication providers should I consider for a Next.js app?

The right choice depends on whether you sell to individuals or to organizations. Self-managed libraries give you full control and leave you to build sessions, MFA, and any enterprise features yourself. Hosted consumer-focused providers cover sign-in, social login, and MFA for individual users. B2B-focused platforms such as WorkOS AuthKit add organizations, enterprise SSO, and SCIM to that base. Whichever you pick, check that it reads the session in server components and server actions and that it integrates with the Next.js proxy. [Top 5 authentication solutions for secure Next.js apps in 2026](https://workos.com/blog/top-authentication-solutions-nextjs-2026) compares several options.

### How do I add SSO to a Next.js app?

Install `@workos-inc/authkit-nextjs`, set up the callback route and proxy, and enable **Single Sign-On** in the WorkOS dashboard. Create an organization for the customer with their email domain, then send their IT admin to the Admin Portal with a link generated by `adminPortal.generateLink` and the `sso` intent. The admin configures their SAML or OIDC identity provider there, and AuthKit then routes that customer's users to it at sign-in. You can verify the whole flow first with the Test Identity Provider in your staging environment.

### How do I protect routes in the Next.js App Router?

Use the proxy for session refresh and coarse redirects, and call `withAuth({ ensureSignedIn: true })` in pages that require a user. Then check the session again inside each server action and route handler, scoping queries to the `organizationId` from the session.

### Does AuthKit work with server components and server actions?

Yes. In server components, server actions, and route handlers, call `withAuth` to get the user and the active organization. In client components, use the `useAuth` hook from `@workos-inc/authkit-nextjs/components`.

### What changed from middleware to proxy in Next.js 16?

Next.js 16 renamed `middleware.ts` to `proxy.ts`. In AuthKit's SDK you use `authkitProxy` either way, and only the file name changes: `proxy.ts` for Next.js 16 and later, `middleware.ts` for Next.js 15 and earlier. The options are the same.

### How do I add multi-tenancy and roles to a Next.js app?

Model each customer as a WorkOS organization, add users through memberships with a role, and read `organizationId`, `role`, and `permissions` from `withAuth`. [How to add multi-tenant authentication to your Next.js SaaS](https://workos.com/blog/nextjs-multi-tenant-authentication-guide) covers invitations, switching, and tenant scoping.

### How do I add SCIM user provisioning to a Next.js app?

Have the customer's IT admin connect their directory through the Admin Portal with the `dsync` intent. With directory provisioning enabled, directory users become AuthKit users and organization memberships, and removing someone in the directory deactivates their organization membership. Add a webhook route if your own database needs to react to those changes.

### Can I add SSO to an app that already has its own login?

Yes. WorkOS also offers a standalone SSO API that handles only the identity provider handshake and returns a profile you map onto your existing user records, so your current login keeps working alongside it. If you are replacing another auth library instead, [Migrating from Better Auth to WorkOS AuthKit: A Next.js guide](https://workos.com/blog/better-auth-to-authkit-nextjs) covers the code changes.

### Which identity providers are supported?

Any provider that speaks SAML or OIDC. WorkOS publishes setup guides for dozens of them, including Okta, Microsoft Entra ID, and Google Workspace, plus generic SAML and OIDC connectors. See the [integrations list](https://workos.com/docs/integrations).

### How much does it cost?

AuthKit is free up to 1 million monthly active users. Enterprise SSO connections are priced per connection, and the pricing page covers the other products. Staging environments are free to use. See the [pricing page](https://workos.com/pricing) for current numbers.

## Next steps

Start with `npx workos@latest install`, or follow the manual steps above, and read the full [AuthKit Next.js docs](https://workos.com/docs/authkit/nextjs). The [AuthKit Next.js SDK reference](https://workos.com/docs/sdks/authkit-nextjs) lists every helper, option, and environment variable.

Once SSO and directory sync are live, enterprise buyers tend to ask for the rest of the checklist, and it hangs off the same organization object:

- [Role-Based Access Control](https://workos.com/docs/authkit/roles-and-permissions) for roles and permissions, already flowing through the session
- [Audit Logs](https://workos.com/audit-logs) for the compliance events security reviews ask about
- [Admin Portal](https://workos.com/admin-portal) so customer IT admins manage their own connections

### Related posts

- [How to add AuthKit to a Next.js app](https://workos.com/blog/add-authkit-to-a-nextjs-app): the full step-by-step setup
- [How to add multi-tenant authentication to your Next.js SaaS](https://workos.com/blog/nextjs-multi-tenant-authentication-guide): invitations, switching, and tenant scoping
- [Building authentication in Next.js App Router: The complete guide for 2026](https://workos.com/blog/nextjs-app-router-authentication-guide-2026): patterns and security practices
- [Top 5 authentication solutions for secure Next.js apps in 2026](https://workos.com/blog/top-authentication-solutions-nextjs-2026): a comparison of providers
- [Migrating from Better Auth to WorkOS AuthKit: A Next.js guide](https://workos.com/blog/better-auth-to-authkit-nextjs): moving an existing app over
- [How to add enterprise SSO to an Express.js API](https://workos.com/blog/how-to-add-enterprise-sso-express-js-api): the same SSO flow for an Express backend
- [How to sync users from Entra ID to your app using Node and WorkOS](https://workos.com/blog/sync-users-from-entra-id-using-node-and-workos): a provider-specific SCIM walkthrough

### Sources

- [AuthKit Next.js quickstart](https://workos.com/docs/authkit/nextjs)
- [AuthKit Next.js SDK reference](https://workos.com/docs/sdks/authkit-nextjs)
- [AuthKit Single Sign-On](https://workos.com/docs/authkit/sso)
- [Admin Portal](https://workos.com/docs/admin-portal)
- [Directory Sync](https://workos.com/docs/directory-sync)
- [Directory provisioning](https://workos.com/docs/authkit/directory-provisioning)
- [Directory Sync event lifecycle](https://workos.com/docs/directory-sync/handle-events)
- [Sync data with webhooks](https://workos.com/docs/directory-sync/webhooks)
