How to add authentication to a Next.js SaaS app
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.
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:
- The SDK. Install
@workos-inc/authkit-nextjs. - A callback route.
handleAuth()exchanges the authorization code for a session. - A proxy.
proxy.tswithauthkitProxykeeps the session fresh on every request. - A sign-in route. It redirects to AuthKit using
getSignInUrl(). withAuthcalls. 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.

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.
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 (free to start), with your API key and client ID from the dashboard.
- Node.js 22.11 or later. Check the
enginesfield 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 walks through each step with troubleshooting.
Set up automatically with the AuthKit installer
Run this from the root of your project:
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
@workos-inc/node is a peer dependency of the AuthKit library.
Step 2: Set your environment variables
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 matchNEXT_PUBLIC_WORKOS_REDIRECT_URIexactly. - 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
Step 5: Wrap your app in the provider
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.
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.
In a client component, use the useAuth hook instead. Do not import withAuth into a client component, since it is server-only code.
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 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.
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.
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:
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.
For a JSON route handler, call withAuth() without ensureSignedIn and return a 401 yourself:
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.
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.

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.
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 for how roles and permissions are modeled.
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:
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.
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.

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 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.
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.
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:
For a broader view of what changes when SSO reaches production, the Express.js version of this guide 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 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:
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 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.
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.
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.
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.
Current prices are on the WorkOS pricing page. 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/staticintercepts your CSS and images. Exclude static paths, as in the example above. - Reading the tenant from the URL or a form field. Take
organizationIdfromwithAuth, 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
unauthenticatedPathsor 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 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 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 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.
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 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. The AuthKit Next.js SDK reference 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 for roles and permissions, already flowing through the session
- Audit Logs for the compliance events security reviews ask about
- Admin Portal so customer IT admins manage their own connections
Related posts
- How to add AuthKit to a Next.js app: the full step-by-step setup
- How to add multi-tenant authentication to your Next.js SaaS: invitations, switching, and tenant scoping
- Building authentication in Next.js App Router: The complete guide for 2026: patterns and security practices
- Top 5 authentication solutions for secure Next.js apps in 2026: a comparison of providers
- Migrating from Better Auth to WorkOS AuthKit: A Next.js guide: moving an existing app over
- How to add enterprise SSO to an 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: a provider-specific SCIM walkthrough