Skip to Content
Docs
SDK guides

Using Pontive with NextAuth.js (Auth.js)

Sign people in through Pontive from an app already on NextAuth.js (Auth.js v5), with the generic OIDC provider.

Pontive is a standard OpenID Connect provider, so an app already on NextAuth.js (Auth.js v5) can sign people in through it with the generic OIDC provider. This page is the setup, and the four things NextAuth does not do for you.

For a new Next.js app, prefer @pontive/pontkit-nextjs (pontiveAuth() with a client secret): it does the same OIDC code flow on the server, and also refreshes rotating tokens once per session, switches organizations, ends the Pontive session on sign-out and handles invitations — everything below you would otherwise write yourself. This recipe is for apps that already use NextAuth, or use it for several providers.

NextAuth signs people in on Pontive's hosted pages: the embedded sign-in widgets are not available to it, and it needs no proxy.

1. Register the app in Pontive

In the dashboard, create an app for the instance:

SettingValue
Type / modeWeb, OAuth
Client typeConfidential — then generate a client secret (shown once)
Redirect URIshttps://app.acme.com/api/auth/callback/pontive
Post-logout redirect URIshttps://app.acme.com/
Sign-in URL (initiate_login_uri)https://app.acme.com/login (step 4)
Security → refresh token DeliveryResponse body

The last one matters: a confidential app gets its refresh token as a browser cookie unless it asks for the response body, and NextAuth calls the token endpoint from your server, where a cookie is no use.

2. Configure the provider

# .env
AUTH_SECRET=…                                   # npx auth secret
AUTH_URL=https://app.acme.com
PONTIVE_ISSUER=https://<your-auth-domain>       # the app's issuer, no trailing slash
PONTIVE_CLIENT_ID=app_…
PONTIVE_CLIENT_SECRET=…
// auth.ts
import NextAuth from "next-auth";
import type { JWT } from "next-auth/jwt";

const issuer = process.env.PONTIVE_ISSUER!;

export const { handlers, auth, signIn, signOut } = NextAuth({
  providers: [
    {
      id: "pontive",
      name: "Pontive",
      type: "oidc",
      issuer, // endpoints come from /.well-known/openid-configuration; PKCE and state are on
      clientId: process.env.PONTIVE_CLIENT_ID,
      clientSecret: process.env.PONTIVE_CLIENT_SECRET,
      authorization: { params: { scope: "openid email profile" } },
    },
  ],
  callbacks: {
    async jwt({ token, account, trigger, session }) {
      // Sign-in: keep what the token endpoint returned.
      if (account) {
        return {
          ...token,
          accessToken: account.access_token,
          expiresAt: account.expires_at,
          refreshToken: account.refresh_token,
          idToken: account.id_token,
        };
      }

      // An organization switch asked for with update({ organizationId }).
      if (trigger === "update" && session?.organizationId) {
        return refresh(token, session.organizationId);
      }

      // Still good for 30 s or more: nothing to do.
      if (Date.now() < (token.expiresAt as number) * 1000 - 30_000) return token;

      return refresh(token);
    },

    async session({ session, token }) {
      session.accessToken = token.accessToken as string;
      session.idToken = token.idToken as string;
      session.error = token.error as string | undefined;
      return session;
    },
  },
});

export const { GET, POST } = handlers;
// app/api/auth/[...nextauth]/route.ts
export { GET, POST } from "@/auth";

Pontive's access token carries the session's organization as org_id, with roles and permissions. Decode it (it is a JWT) where you need them, or call /oauth2/userinfo with it.

3. Refresh rotating tokens

NextAuth does not refresh for you. Pontive rotates refresh tokens: each refresh returns a new one and retires the old, and presenting a retired one more than 30 seconds later revokes the whole chain — the user is signed out.

// auth.ts, continued
let tokenEndpoint: string | undefined;

async function refresh(token: JWT, organizationId?: string): Promise<JWT> {
  tokenEndpoint ??= (await (await fetch(`${issuer}/.well-known/openid-configuration`)).json())
    .token_endpoint as string;

  const body = new URLSearchParams({
    grant_type: "refresh_token",
    refresh_token: token.refreshToken as string,
  });
  // Pontive moves the session to this organization as it refreshes.
  if (organizationId) body.set("organization_id", organizationId);

  const response = await fetch(tokenEndpoint, {
    method: "POST",
    headers: {
      "content-type": "application/x-www-form-urlencoded",
      authorization:
        "Basic " +
        Buffer.from(`${process.env.PONTIVE_CLIENT_ID}:${process.env.PONTIVE_CLIENT_SECRET}`).toString("base64"),
    },
    body,
  });

  const tokens = await response.json();

  // A refused switch is not a lapsed session: Pontive spent nothing, so keep
  // the tokens as they were and say why.
  if (!response.ok && organizationId) return { ...token, switchError: tokens.error_description ?? tokens.error };
  if (!response.ok) return { ...token, error: "RefreshTokenError" };

  return {
    ...token,
    accessToken: tokens.access_token,
    expiresAt: Math.floor(Date.now() / 1000) + tokens.expires_in,
    // Rotation: always the new one. Never keep the token just spent.
    refreshToken: tokens.refresh_token ?? token.refreshToken,
    idToken: tokens.id_token ?? token.idToken,
  };
}

Two rules keep rotation from signing users out:

  • Refresh where NextAuth can write cookies. NextAuth stores the session — and so the new refresh token — in a cookie, and can only rewrite it in middleware, route handlers and server actions. A refresh during a Server Component render is used once and then lost, and the next request spends the retired token. Run auth as middleware so every request refreshes there first:

    // middleware.ts
    export { auth as middleware } from "@/auth";
    
    export const config = { matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"] };
  • Concurrent refreshes are fine within 30 seconds. Two requests that refresh the same token at once both succeed: Pontive accepts a just-retired token for 30 seconds. Past that, a replay is treated as theft.

When session.error is "RefreshTokenError", the session is over: send the user to sign in again.

4. Invitations: the sign-in URL

An accepted invitation sends the invitee to the app's Sign-in URL with organization_id (the organization they joined) and login_hint (their address). That URL has to start a sign-in on a plain GET, and NextAuth's own routes start one only with a POST. So add a route that does:

// app/login/route.ts
import { signIn } from "@/auth";

export async function GET(request: Request) {
  const url = new URL(request.url);
  const params: Record<string, string> = {};

  for (const name of ["organization_id", "login_hint"]) {
    const value = url.searchParams.get(name);
    if (value) params[name] = value;
  }

  // Redirects to Pontive with the organization and the address passed on.
  await signIn("pontive", { redirectTo: "/" }, params);
}

Register it as the app's Sign-in URL (step 1). The invitee arrives signed in, in the organization they were invited to — Pontive signed them in moments earlier, so they are not asked again.

5. Sign-out that ends the Pontive session

signOut() clears NextAuth's cookie, but the Pontive session lives on, so the next sign-in goes straight through. To end both, send the browser to Pontive's end-session endpoint afterwards:

// app/logout/route.ts
import { auth, signOut } from "@/auth";

export async function GET() {
  const session = await auth();
  await signOut({ redirect: false });

  const url = new URL(`${process.env.PONTIVE_ISSUER}/oauth2/logout`);
  if (session?.idToken) url.searchParams.set("id_token_hint", session.idToken);
  url.searchParams.set("post_logout_redirect_uri", `${process.env.AUTH_URL}/`);

  return Response.redirect(url);
}

post_logout_redirect_uri must be one of the app's registered post-logout redirect URIs, or Pontive stops on its own "signed out" page.

Switching organization

With the jwt callback above, switching is a session update:

"use client";
import { useSession } from "next-auth/react";

export function SwitchTo({ organizationId }: { organizationId: string }) {
  const { update } = useSession();
  return <button onClick={() => update({ organizationId })}>Switch</button>;
}

The refresh moves the Pontive session to that organization. A switch Pontive refuses — the user is not a member — spends nothing: the session stays where it was, and token.switchError says why (surface it from the session callback if the UI needs it).

What not to do

  • Do not request offline_access unless the app is allowed offline refresh tokens and you mean it: such a token outlives the Pontive session, so signing out of Pontive no longer signs the user out of your app.
  • Do not expose the access token to the browser unless the browser calls APIs with it. session.accessToken above is readable through /api/auth/session; keep it server-side if only your server uses it.
  • Do not keep the old refresh token after a refresh — it is retired, and presenting it later revokes the chain.