Skip to content

Next.js

Use @hyper.authio/provider-nextauth 6.2.0 in production: Auth.js v5 or NextAuth v4, configured like the client, scopes, roles and permissions, refresh, sessions kept on the server, logout, back-channel logout and sign-in in a popup.

@hyper.authio/provider-nextauth is the Authio provider for Auth.js v5 and NextAuth v4, version 6.2.0 on npm. The protocol work is done by @hyper.authio/client 0.13, the version @hyper.authio/server, express and bff 0.13 depend on, so an app that uses one of them as well installs one copy: the sign-in is validated in full (the checks you configure, the iss parameter and the ID token), and the package renews the session, reads roles and permissions into it, keeps its tokens in the cookie or on the server, ends it at Authio, receives back-channel logouts and opens encrypted tokens, on both majors. What the client configures in Authio is set where NextAuth itself reads it — checks and client — and the package fixes none of it.

This page picks up where the Quickstart ends: the right entry point, more scopes, longer sessions, roles, logout and routes only signed-in people reach.

Upgrading from 5.x

6.0.0 breaks compatibility in the types only. token.authio.claims becomes optional, since a cookie written with sessionClaims: 'store' holds no claims: under strict, code that reads that field directly has to narrow it, or read session.authio or await authio.getClaims(token). Without sessionClaims: 'store', nothing changes at run time: the cookie keeps its claims, as in 5.2.0.

Upgrading from 4.x

5.0.0 is a breaking release. getAccessToken(token) is asynchronous on both majors and answers Promise<string | null>: write await authio.getAccessToken(token). token.authio is typed AuthioTokenState | AuthioSessionReference, so token.authio.accessToken is string | undefined: read the access token with getAccessToken instead of handing that field on. Without sessionStore nothing else changes. With it, see Server-side sessions.

Upgrading from 3.x

4.0.0 is a breaking release. checks is NextAuth’s option again and is no longer imposed: left out, NextAuth v4 checks only state and Auth.js v5 only pkce, so pass checks: ['pkce', 'state', 'nonce'] to keep 3.x’s behaviour (a client with PKCE on refuses a v4 sign-in without pkce). clientAuthentication is removed with no alias: the method is client.token_endpoint_auth_method. An ID token signed with HS256, HS384 or HS512 is refused unless client.id_token_signed_response_alg names it. codeChallengeMethod: 'plain' is refused, because NextAuth only sends S256. On v4, checks, client and jwks are NextAuth’s options again and clientSecret is optional. Built on @hyper.authio/client 0.8.0; Node.js 20.19 or later.

Set it up from the terminal

In a client’s integration guide, the Next.js · Auth.js v5 recipe offers Set it up from your terminal. Generate command gives you one command that applies the whole recipe to your project, on your machine, with @hyper.authio/cli. The code in it works once and for 10 minutes, and it only reads this client’s integration plan: it changes nothing and carries no secret.

TerminalBash
npx "@hyper.authio/cli@latest" init --ticket ait_…
  • What it detects. The Next.js major, which decides between proxy.ts and middleware.ts, the App Router, a src/ folder and your package manager. A project on the pages router or already on NextAuth v4 is stopped with an explanation.
  • What it writes. auth.ts, the app/api/auth/[...nextauth]/route.ts route and proxy.ts (or middleware.ts), after showing you each one. A file you already have is never overwritten: the CLI shows what to merge into it. In .env.local it only adds the keys that are missing.
  • The secrets. The client secret is never part of the plan: the CLI asks for it in a hidden prompt and writes it only to .env.local. AUTH_SECRET is generated on your machine, and the CLI checks that .env.local is in .gitignore.
  • What it never does. Commit, push, send your code to Authio or change the client. The redirect URI and the secret are changed in the console.
  • Look first, confirm after. --dry-run shows the plan without writing anything. Once you sign in through the app, npx "@hyper.authio/cli" verify confirms the first sign-in, as the last step of the guide does.
  • On Windows PowerShell, keep the quotes. PowerShell reads an argument that starts with @ as splatting and refuses the line; with the package in double quotes, as the console writes it, the same command runs in PowerShell, cmd, bash and zsh.

With your own agent

Connected to Authio in Agents (MCP), Claude Code, Cursor or VS Code can ask for the same plan with the integration_plan tool and apply it to the project you have open, showing you each change.

Pick an entry point

Your next-auth versionImport fromBuilt on
5.0.0-beta (Auth.js)@hyper.authio/provider-nextauth/v5The oidc provider type, with the ID token validated by @hyper.authio/client; reads its settings from the environment.
^4.24.0@hyper.authio/provider-nextauthThe oauth provider type with discovery, with the code exchange done by @hyper.authio/client; every setting is passed in code.
Either@hyper.authio/provider-nextauth/popupThe popup sign-in helpers, which import nothing from next-auth.

Both majors export the same names: createAuthio, Authio, checkAccess, hasRole, hasPermission, hasScope and the types. createAuthio returns the provider, the callbacks and events that keep the session healthy, and the logout helpers; Authio is the provider alone, for an app that needs no refresh, claims or logout. next-auth is a peer dependency: install the version you use, and pin the Auth.js beta rather than tracking the beta tag, which moves between breaking releases.

Auth.js v5Bash
npm install @hyper.authio/provider-nextauth@^6.2.0 next-auth@5.0.0-beta.32

Environment variables

VariableWhat it holds
AUTH_AUTHIO_ISSUERThe realm’s issuer, such as https://authio.api.hyperio.tech/realms/acme.
AUTH_AUTHIO_IDThe client ID, such as acme-web.
AUTH_AUTHIO_SECRETThe client secret. Leave it out for a public client.
AUTH_AUTHIO_ENCRYPTION_KEYOnly when the client encrypts its tokens to its own key: the private key, read as clientEncryptionKey — see Encrypted tokens.
AUTH_SECRETThe key that encrypts the session cookie, from npx auth secret. NEXTAUTH_SECRET on v4.
AUTH_URLYour app’s public address, such as https://app.example.com. NEXTAUTH_URL on v4.

On Auth.js v5, issuer, clientId, clientSecret and clientEncryptionKey default to the AUTH_AUTHIO_ variables: Auth.js upper-cases the provider ID, authio, and looks up exactly these names. On v4, pass issuer, clientId and clientSecret in code; clientEncryptionKey still defaults to AUTH_AUTHIO_ENCRYPTION_KEY.

Two variables people mix up

On v5, set AUTH_URL, not NEXTAUTH_URL: only AUTH_URL (or AUTH_TRUST_HOST=true) marks the host as trusted, and without it a self-hosted deploy fails with UntrustedHost. And AUTH_SECRET is never the client secret: share one value and rotating the client secret signs out every open session.

Configure Auth.js v5

With the variables in place the provider needs no credentials in code. Spread the package’s callbacks and events into Auth.js: they keep the tokens in the encrypted cookie (or, with a session store, on the server), renew the access token, expose the claims and let a sign-out continue to Authio.

auth.tsTypeScript
import NextAuth from 'next-auth'
import { createAuthio } from '@hyper.authio/provider-nextauth/v5'

export const authio = createAuthio({
  checks: ['pkce', 'state', 'nonce'],
  authorization: { params: { scope: 'openid profile email roles offline_access' } },
  postLogoutRedirectUri: new URL('/', process.env.AUTH_URL).toString(),
})

export const { handlers, signIn, signOut, auth } = NextAuth({
  providers: [authio.provider],
  callbacks: authio.callbacks,
  events: authio.events,
})

The redirect URI to register on the client is https://app.example.com/api/auth/callback/authio, one per environment, and the post-logout redirect URI is the address in postLogoutRedirectUri.

Configure NextAuth v4

On v4, issuer, clientId and clientSecret are passed explicitly; issuer is required, because the discovery URL is built from it, and clientSecret only for a client that authenticates with a secret. The code exchange and the ID token validation are done by @hyper.authio/client, the same as on v5, and the provider maps sub, name (or preferred_username), email and picture onto the user.

lib/auth.tsTypeScript
import type { NextAuthOptions } from 'next-auth'
import { createAuthio } from '@hyper.authio/provider-nextauth'

export const authio = createAuthio({
  issuer: process.env.AUTH_AUTHIO_ISSUER!,
  clientId: process.env.AUTH_AUTHIO_ID!,
  clientSecret: process.env.AUTH_AUTHIO_SECRET!,
  checks: ['pkce', 'state', 'nonce'],
  authorization: { params: { scope: 'openid profile email roles offline_access' } },
  postLogoutRedirectUri: `${process.env.NEXTAUTH_URL}/`,
})

export const authOptions: NextAuthOptions = {
  providers: [authio.provider],
  callbacks: authio.callbacks,
  events: authio.events,
}

Configure it like the client

Each setting of the client in the console goes where NextAuth (v4) or Auth.js (v5) reads it, and a setting left out is off, or NextAuth’s own default, as with any other provider. Authio refuses a request that does not match the client and accepts one that sends more than it requires, such as PKCE to a client that does not require it.

In the consoleOption (v4 and v5)Left out
PKCE onchecks: ['pkce', …]v4: no PKCE (checks defaults to state); v5: PKCE (checks defaults to pkce)
PKCE methodsS256 only: NextAuth sends nothing else, and codeChallengeMethod: 'plain' is refusedS256: keep it allowed on the client
state and noncechecks: [..., 'state', 'nonce']v4: state only; v5: neither
Token endpoint auth methodclient.token_endpoint_auth_method: client_secret_basic, client_secret_post, private_key_jwt or noneclient_secret_basic
ID token & userinfo signatureclient.id_token_signed_response_alg; for HS256, HS384 or HS512 it is required, and verified with clientSecretThe asymmetric algorithms the realm publishes; HS refused
Signed UserInfoclient.userinfo_signed_response_algclient.id_token_signed_response_alg
Maximum authentication ageclient.default_max_age (v4 also reads authorization.params.max_age)Not checked

PKCE with `plain` only does not work with NextAuth

NextAuth and Auth.js only generate S256 challenges. A client with PKCE on that allows only plain refuses every sign-in from them: allow S256 on the client. How HS signing fits with your APIs is covered in Token signing.

Scopes

The provider asks for openid email profile unless you say otherwise. Every scope you request must also be allowed on the client in Clients.

ScopeWhat it adds
openidThe ID token. Required unless the client turns Require OpenID Connect off.
profile, email, phoneNames and username; the address and whether it is verified; the phone number.
rolesThe user’s roles and permissions in the access token, which the package reads into session.authio — see Roles and permissions.
offline_accessA refresh token — see Refresh tokens.

Set authorization.params.scope to change the list. Options are merged key by key, but scope is one string and is replaced whole, so write the complete list, as in the examples above.

To call an API of yours registered as a resource server, add its identifier, such as https://api.example.com, as resource in the same params. The access token then carries it as aud instead of the client’s Client ID, and refreshes keep it.

The session and its claims

The package declares its fields on NextAuth’s types, so there is nothing to declare yourself. session.authio holds who signed in and what Authio lets them do, read from the access token (decrypted when encrypted) over the ID token; session.error says when the session can no longer be used. The tokens stay in the encrypted cookie, under token.authio, or with a session store on the server, and /api/auth/session never serves them to the browser.

FieldFromWhat it says
subject, clientId, sessionIdsub, client_id (or azp), sidThe user’s stable ID in the realm, the client and the Authio session.
scopesscopeThe granted scopes.
roles, permissions, resourceAccessThe *_resource_access claims (roles scope)Every role, every permission per resource, and each role with where it was granted.
organizationId, organizationAliasorg_id, org_aliasThe organization of the session.
organizationRoles (6.1.0)org_roles (the access token’s, with org_id and the roles scope)The roles the person holds in that organization, without repeats and in the token’s order. They hold in that organization alone: roles, permissions, hasRole and checkAccess never read them. A Lightweight access token leaves them to introspection, so they need accessTokenClaims: 'introspection'. Left out when the token carries none.
acr, authenticationLevel, authenticationMethods, authTime, identityProvideracr, amr, auth_time, idpHow strongly (1 to 3) and with which methods (pwd, otp, swk, fed, mfa…) the person authenticated, when, and through which external provider.
delegationChain (6.1.0)delegation_chain (delegation_id alone on a token issued before the claim)Every delegation grant the token rests on, the first exchange’s first and the one delegationId names last: withdrawing any of them stops the token. Left out when the token was not delegated.

authio.callbacks are plain functions: call them from your own to keep fields of yours, such as a claim from the ID token. AuthioProfile types the profile argument, which the jwt callback receives on sign-in only.

auth.tsTypeScript
import NextAuth from 'next-auth'
import { createAuthio, type AuthioProfile } from '@hyper.authio/provider-nextauth/v5'

export const authio = createAuthio()

export const { handlers, signIn, signOut, auth } = NextAuth({
  providers: [authio.provider],
  events: authio.events,
  callbacks: {
    ...authio.callbacks,
    async jwt(params) {
      const token = await authio.callbacks.jwt(params)

      if (token && params.profile) {
        token.username = (params.profile as AuthioProfile).preferred_username
      }

      return token
    },
    async session(params) {
      const session = await authio.callbacks.session(params)

      session.user.username = params.token.username as string | undefined

      return session
    },
  },
})
These callbacks work with the JWT session strategy, the default without an adapter. With a database session the jwt callback does not run: session.authio is not filled and refresh is up to the app.

Confidential and public clients

A Next.js app exchanges the code on its server, so a confidential client is the usual choice; the token endpoint method is NextAuth’s client_secret_basic unless you set client.token_endpoint_auth_method (client_secret_post, private_key_jwt or none). It must match the client in Authio, which compares it exactly, and the same method is used to redeem the code, refresh, revoke and introspect. For a public client, set none and leave clientSecret out.

auth.tsTypeScript
createAuthio({
  checks: ['pkce', 'state'],
  client: { token_endpoint_auth_method: 'none' },
})

Refresh tokens

Authio issues a refresh_token only when the granted scopes include offline_access — no lifetime setting produces one. Allow the scope on the client and request it; the package does the rest in the jwt callback. Sixty seconds before the access token expires (tokenRefreshSkew), it redeems the refresh token, keeps the rotated one and reads the claims again, so a role granted or removed in the console reaches the session on the next refresh.

  • Concurrent requests share one refresh. A request still carrying the old cookie in the next 30 seconds gets the same result instead of presenting a spent refresh token, which Authio’s reuse detection would treat as theft.
  • A refusal ends the session. When Authio refuses the refresh token, session.error becomes RefreshAccessTokenError, session.authio disappears and the refresh token is dropped. A network failure, a 429 or a 5xx sets the same error but keeps the refresh token, and the next request tries again.
  • The cookie has to be writable. A refresh is only kept where the response can set the cookie: route handlers, server actions, the proxy and getServerSession in API routes can; a server component cannot.
  • No new ID token unless the client turns on ID Token on Refresh. Lifetimes are per client: the refresh token lasts 60 minutes by default.

When session.error is RefreshAccessTokenError, start the sign-in again: if the person’s Authio session is still alive, they go straight through. To call your API on the server, take the access token with await authio.getAccessToken(await authio.getSessionToken(...)), which answers null once it expired or the session failed: getSessionToken({ headers }, { secret }) on Auth.js v5, getSessionToken(req, res) on NextAuth v4. Unlike getToken, it already reads the token the jwt callback just renewed, so the first call after a refresh does not carry the expired one. getAccessToken is asynchronous since 5.0.0, with or without a session store.

Server-side sessions

By default the session cookie holds the access, refresh and ID tokens. When the client encrypts its tokens, each one weighs several KB: the cookie passes what one cookie carries, NextAuth splits it into pieces (authjs.session-token.0, .1…), and the request headers can pass what proxies and hosts accept — 8 KB per header line on nginx, 16 KB on Vercel, 16 KB in all on Node, which answers 431. With sessionStore (5.0.0) the tokens stay on the server, in a store every instance of the app shares, and the cookie keeps a reference to them.

  • Turn it on when the session cookie is split into pieces, when a proxy or host refuses large headers (431, 400 Request Header Or Cookie Too Large), when several instances renew the same session, or when signing out has to end the session on the server, so a copy of the cookie stops working.
  • The package tells you. Without a store, it warns once per process (console.warn) when a session passes about 2,900 bytes of JSON, the size past which NextAuth splits the cookie.
  • Turning it on or off signs everyone out once. Each mode reads only its own cookie: a cookie of the other format is no session, and the person signs in again.
WhereWhat
The session cookie, encrypted by NextAuthref and key (random), expiresAt, refreshAt, signedInAt and the claims: one cookie of a fixed, small size, whatever the client’s token encryption.
Redis, under {prefix}{ref}The access, refresh and ID tokens as Authio issued them, JWE included, sealed with AES-256-GCM under the cookie’s key: whoever reads Redis without the cookie opens nothing. Kept for sessionMaxAge plus an hour after each write.
Redis, under {prefix}{ref}:refreshThe renewal lock, for 15 seconds at most: one refresh token exchange per session across every instance.

createRedisSessionStore, from @hyper.authio/provider-nextauth/redis, takes any ioredis-compatible client (get, set, del and eval); the package does not depend on one. Give the client short timeouts and few retries, so a Redis that does not answer fails fast. Pass NextAuth’s session.maxAge as sessionMaxAge. By default the claims stay in the cookie, so session.authio, checkAccess in the proxy and useSession keep working, and pages keep rendering, while it is down; see Three session models to keep them in Redis instead. To read other access token claims from the session, name them in extraClaims: they land in session.authio.extra, since the access token is no longer in the cookie to open.

auth.tsTypeScript
import NextAuth from 'next-auth'
import Redis from 'ioredis'
import { createAuthio } from '@hyper.authio/provider-nextauth/v5'
import { createRedisSessionStore } from '@hyper.authio/provider-nextauth/redis'

const SESSION_MAX_AGE = 30 * 24 * 60 * 60

const redis = new Redis(process.env.SESSION_REDIS_URL!, {
  connectTimeout: 1000,
  commandTimeout: 500,
  maxRetriesPerRequest: 1,
})

export const authio = createAuthio({
  checks: ['pkce', 'state', 'nonce'],
  authorization: { params: { scope: 'openid profile email roles offline_access' } },
  sessionStore: createRedisSessionStore(redis, { prefix: 'my-app:session:' }),
  sessionMaxAge: SESSION_MAX_AGE,
  extraClaims: ['subscription'],
})

export const { handlers, signIn, signOut, auth } = NextAuth({
  providers: [authio.provider],
  callbacks: authio.callbacks,
  events: authio.events,
  session: { maxAge: SESSION_MAX_AGE },
})

await authio.getAccessToken(token) is the same call with or without a store. With one, it reads the session’s record and renews it first when it is due; it answers null when the session is over (no session, an error, a refused refresh, a record that is gone), and rejects with AuthioSessionStoreUnavailableError when the store does not answer or an expired access token cannot be renewed yet. Answer that one with 503, not as signed out: the session is not over.

  • Renewal is shared. When the cookie’s refreshAt is due, the jwt callback takes the record’s lock, renews at Authio and writes the record, or adopts the renewal another instance already wrote. The renewal is kept even where the response cannot write the cookie, such as a server component.
  • The store down at sign-in fails the sign-in. The jwt callback rejects and NextAuth shows its error page (error=Configuration on v5, error=Callback on v4), without a session cookie. Down while navigating, the session goes on with the cookie’s claims, after the store client’s own timeout; down when a token is needed, getAccessToken rejects as above and the next request tries again.
  • Signing out ends the session on the server. authio.events.signOut deletes the record and revokes the refresh token, and endSessionUrl reads the ID token from the record (and leaves id_token_hint out when the store does not answer).
  • A session without a record ends at its next read (5.2.0). With a store, every read of the session confirms the record is still there: a session signed out, discarded or lost with the store’s data ends on the next screen, without waiting for the next data call. That includes the cookie an answer already on its way writes again after the sign-out. With the store down, the session goes on as it is.
  • A new sign-in replaces a session. authio.discard(previous) deletes the previous session’s record and revokes its refresh token. Call it only when Authio issued the new session under another session (session.authio.sessionId differs): when Authio let the person straight through on the same one, revoking the old refresh token ends that Authio session, and the new app session with it.

Three session models

On the client’s page in the console, Security › Application Session declares the Application Session Model of the app that signs people in through it: a confidential client with authorization_code, or the platform’s own client. Authio only stores the choice, and nothing changes in the tokens; the client’s Guide writes the createAuthio of the chosen model, with the Redis variable.

ModelIn the cookieWith Redis downIn createAuthio
Cookie, the defaultThe access, refresh and ID tokens themselves: past 4 KB and split into pieces once they are encrypted, with 431 past 16 KB of headersNothing changes: there is no RedisNo sessionStore
HybridThe reference, the key, the times and the claims: about 1 KB to 3.5 KB with the person’s roles and permissionsPages keep opening from the cookie’s claims; getAccessToken rejects until it is backsessionStore: createRedisSessionStore(redis)
ServerOnly the reference, the key and the times: a few hundred bytes, always the same sizeThe session comes without claims and with error: 'SessionStoreUnavailable', not signed out: protected pages are unavailable until it is backsessionStore and sessionClaims: 'store' (6.0.0)

sessionClaims (6.0.0) only applies with sessionStore, and defaults to 'cookie'. With 'store', the claims go to the session’s record with the tokens, and every read of the session reads the record (about 1 ms): session.authio, checkAccess and useSession work as before. While the store does not answer, the session is served without session.authio and with session.error set to SessionStoreUnavailable, and nothing is signed out: show the page as temporarily unavailable instead of sending the person to sign in, and read the session again in a moment. A record that is gone ends the session, as in the other modes. Moving from Cookie to Hybrid or Server, or back, makes everybody sign in again once, since with and without a store each mode reads only its own cookie.

auth.tsTypeScript
export const authio = createAuthio({
  checks: ['pkce', 'state', 'nonce'],
  sessionStore: createRedisSessionStore(redis, { prefix: 'my-app:session:' }),
  // The claims in Redis too: the cookie keeps a few hundred bytes.
  sessionClaims: 'store',
})

Roles and permissions

checkAccess, hasRole, hasPermission and hasScope take the session, the JWT or the claims, treat a session with an error as signed out, and import nothing from Node, so they run in the proxy too. Check permissions rather than role names: a role can be renamed in the console, the permissions it grants are what your code depends on.

Anywhere on the serverTypeScript
import { checkAccess, hasPermission, hasRole } from '@hyper.authio/provider-nextauth/v5'
import { auth } from '@/auth'

const session = await auth()

hasRole(session, 'billing-admin')
hasPermission(session, 'invoice', 'write')

checkAccess(session, {
  permissions: ['reports:read'],
  anyRole: ['admin', 'owner'],
  authenticationLevel: 2,
}) // 'allowed' | 'unauthenticated' | 'forbidden'

Lightweight and reference access tokens

With the Access Token Format on Lightweight, the token does not carry the roles, the permissions, subscription, the profile or the email. Pass accessTokenClaims: 'introspection' (5.1.0): at sign-in and on every refresh, the provider introspects the access token as the client and merges the answer over the ID token’s claims, extraClaims included. The claims stay in the cookie, so navigating costs no request. An Opaque (reference) token is introspected even without the option. Introspection needs a confidential client.

auth.tsTypeScript
export const authio = createAuthio({
  checks: ['pkce', 'state', 'nonce'],
  accessTokenClaims: 'introspection',
})

With 'introspection', an introspection that fails or answers active: false fails the sign-in; on a refresh, active: false ends the session and a failure keeps the claims until the next one. A token requested for a resource is active only to that resource server’s introspection client. A reference refresh token changes nothing: the provider does not read the refresh token. See the full table in Integrate with the libraries.

Sign in

Start a sign-in with signIn('authio'). Its third argument is added to the authorization request, so one button can go straight to a provider with idp_hint (the alias of an identity provider the client offers; any other alias is ignored and Authio’s screen is drawn), force the credentials again with prompt: 'login', fill the username with login_hint, pick the screen’s language with ui_locales or sign in for one organization with organization.

app/sign-in-buttons.tsx (v5)TypeScript
import { signIn } from '@/auth'

export function SignInButtons() {
  return (
    <>
      <form action={async () => { 'use server'; await signIn('authio', { redirectTo: '/dashboard' }) }}>
        <button type="submit">Sign in</button>
      </form>
      <form action={async () => { 'use server'; await signIn('authio', { redirectTo: '/dashboard' }, { idp_hint: 'google' }) }}>
        <button type="submit">Continue with Google</button>
      </form>
    </>
  )
}

Protect routes

Wrap auth in the proxy to send anyone without a session to sign in before a page renders, and to turn away anyone without the permission. In Next.js 16 the file is proxy.ts; on Next.js 15 and earlier it is middleware.ts and the export is named middleware. On NextAuth v4, use withAuth from next-auth/middleware and pass req.nextauth.token to checkAccess.

proxy.tsTypeScript
import { NextResponse } from 'next/server'
import { checkAccess } from '@hyper.authio/provider-nextauth/v5'
import { auth } from '@/auth'

export const proxy = auth((req) => {
  const decision = checkAccess(req.auth, { permissions: ['reports:read'] })

  if (decision === 'unauthenticated') {
    const signInUrl = new URL('/api/auth/signin', req.nextUrl.origin)
    signInUrl.searchParams.set('callbackUrl', req.nextUrl.href)
    return NextResponse.redirect(signInUrl)
  }

  if (decision === 'forbidden') return new NextResponse('Forbidden', { status: 403 })
})

export const config = {
  matcher: ['/dashboard/:path*', '/settings/:path*'],
}

The proxy decides what renders, not what data may be read: call auth() again in server components, server actions and route handlers that return protected data, and let your API verify the access token itself, with @hyper.authio/express (Node.js) or Authio.AspNetCore (.NET); in another language, see token validation.

Sign out

Clearing the NextAuth cookie only signs the person out of the app; their Authio session stays open and the next sign-in goes straight through. To end it too, send the browser to Authio’s end-session endpoint: authio.endSessionUrl(token) builds the address with the session’s ID token as id_token_hint and postLogoutRedirectUri, and authio.callbacks.redirect lets signOut continue there. Read the URL before signOut clears the cookie.

app/actions.tsTypeScript
'use server'

import { headers } from 'next/headers'
import { authio, signOut } from '@/auth'

export async function signOutEverywhere() {
  const token = await authio.getSessionToken(
    { headers: await headers() },
    { secret: process.env.AUTH_SECRET!, secureCookie: process.env.AUTH_URL!.startsWith('https://') },
  )

  await signOut({ redirectTo: await authio.endSessionUrl(token) })
}

authio.events.signOut revokes the refresh token at Authio on every sign-out, even one that stays in the app. The post-logout redirect URI must be registered on the client; without a valid id_token_hint, Authio asks the person to confirm and ignores it.

Back-channel logout

When the person signs out at Authio, from another app or from the account pages, Authio posts a logout token to the client’s back-channel logout URI. Register https://app.example.com/api/auth/backchannel-logout on the client and serve the package’s endpoint there: it validates the token and records the logout, and the session it names ends on its next request (SessionEndedError on v4).

app/api/auth/backchannel-logout/route.tsTypeScript
import { authio } from '@/auth'

export const POST = authio.backchannelLogout

One server instance, or a shared store

The logouts wait in memory by default, which only works with one server instance. Serverless deployments and several containers need a logoutStore they share, such as Redis. With database sessions, delete the rows in onBackchannelLogout instead.

Encrypted tokens

When the client encrypts its tokens to its own key, set AUTH_AUTHIO_ENCRYPTION_KEY (or pass clientEncryptionKey) to the private key. The algorithms are read from each token: RSA-OAEP-256, Authio’s default, and RSA-OAEP work on Auth.js v5 and NextAuth v4 alike; RSA1_5 is refused. See Encrypted tokens.

@hyper.authio/provider-nextauth/popup keeps the page where it is and runs the sign-in in a popup over it. The ordinary flow runs inside: Auth.js exchanges the code on your server, the session cookie lands on your origin, and Authio receives display=popup and fits its screens to the window. It needs two small pages and no extra redirect URI.

app/auth/popup/page.tsxTypeScript
'use client'

import { useEffect } from 'react'
import { signIn } from 'next-auth/react'
import { startPopupSignIn } from '@hyper.authio/provider-nextauth/popup'

export default function PopupStart() {
  useEffect(() => {
    startPopupSignIn(signIn)
  }, [])

  return null
}
  • signInWithPopup never rejects: it resolves { ok: true } or { ok: false, error } with popup_blocked (call it straight from the click), popup_closed, timeout (5 minutes) or the Auth.js error.
  • The pages default to /auth/popup and /auth/popup/done on the button’s origin; change them with signInWithPopup({ startPath }) and startPopupSignIn(signIn, { donePath }).
  • A refused sign-in lands on Auth.js’s error page: point pages.error at a page that calls completePopupSignIn() and the button receives the error.
  • Do not serve the page with Cross-Origin-Opener-Policy: same-origin; use same-origin-allow-popups.

The package does not use response_mode=web_message: the popup comes back through /api/auth/callback/authio like any sign-in, and your own done page tells the button. Without Auth.js, see the popup flow on the wire.

Troubleshooting

What you seeWhyWhat to do
Sign-in ends in access_denied: “<scope> has not been assigned to this user”The scope string asks for a scope that requires assignment, and the person (or their groups) does not have it: Authio then refuses the whole sign-in.Leave scopes that require assignment out of the scope string the app asks for by default, as the client’s guide and the terminal plan do, or assign the scope to the person or a group.
next build fails with “Route "/": Next.js encountered uncached or runtime data during prerendering”The app has cacheComponents on (the default of a new Next.js 16 app) and a page reads the session outside <Suspense>.Read the session in an async component rendered inside <Suspense>, as the guide’s pages do.
No refresh_token; the session ends when the access token expiresoffline_access was not granted.Allow it on the client and add it to the full scope string.
session.authio.roles is emptyThe roles scope was not granted, or the client’s access token format is Lightweight, which does not carry the roles.Request roles. With the Lightweight format, pass accessTokenClaims: 'introspection' (5.1.0), which reads the roles from the access token’s introspection, or keep the format on JWT (self-contained).
Sign-in fails with decryption_failed or legacy_algorithmThe encryption key is missing or wrong, or the client still encrypts with RSA1_5.Set AUTH_AUTHIO_ENCRYPTION_KEY; move the client to RSA-OAEP-256.
invalid_request: the client requires PKCEThe client has PKCE on and checks leaves pkce out (NextAuth v4 defaults to state).Pass checks: ['pkce', 'state', 'nonce'].
invalid_client: the client authenticates with another methodclient.token_endpoint_auth_method is not the client’s method in the console.Set the same method on both sides.
invalid_algorithm: the algorithm HS256 is not availableThe client signs its ID token with HS.Set client.id_token_signed_response_alg — see Token signing.
RefreshAccessTokenError right after a deploy with several instancesConcurrent refreshes on different instances presented the same refresh token.Route the session through the proxy so one request refreshes first, or keep sessions sticky.
Subsequent property declarations must have the same type on Session.errorYour own next-auth.d.ts still declares error or the 2.x token fields.Remove them: the package declares authio and error itself.
UntrustedHost in productionNEXTAUTH_URL set instead of AUTH_URL on v5.Set AUTH_URL to the app’s public address.
Please define a secretAUTH_SECRET is empty.Generate one with npx auth secret.
Type errors importing the root entry in a v5 appThe root entry is the v4 one.Import from @hyper.authio/provider-nextauth/v5.

Next steps