Next.js
Add sign-in to a Next.js App Router application with route handlers, PKCE and your own session.
This guide adds sign-in to a Next.js App Router app. Everything runs on the server: the client
secret and the tokens never reach the browser. There is no SDK; it uses fetch and
jose to verify the ID token.
You need a confidential application with the redirect URI
http://localhost:3000/api/auth/callback. See
Set up an application.
npm install joseONEFOLD_CLIENT_ID=your-client-id
ONEFOLD_CLIENT_SECRET=your-client-secret
ONEFOLD_REDIRECT_URI=http://localhost:3000/api/auth/callbackNever prefix these with NEXT_PUBLIC_: that would ship them to the browser.
Shared helpers
import { createHash, randomBytes } from "node:crypto";
import { createRemoteJWKSet, jwtVerify } from "jose";
export const ISSUER = "https://onefold.eitozx.com";
const JWKS = createRemoteJWKSet(new URL(`${ISSUER}/.well-known/jwks.json`));
export function randomValue(): string {
return randomBytes(32).toString("base64url");
}
export function challengeFor(verifier: string): string {
return createHash("sha256").update(verifier).digest("base64url");
}
export async function tokenRequest(params: Record<string, string>) {
const response = await fetch(`${ISSUER}/o/token/`, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
...params,
client_id: process.env.ONEFOLD_CLIENT_ID!,
client_secret: process.env.ONEFOLD_CLIENT_SECRET!,
}),
});
if (!response.ok) {
throw new Error(`Token request failed: ${response.status}`);
}
return response.json();
}
export async function verifyIdToken(idToken: string, nonce: string) {
const { payload } = await jwtVerify(idToken, JWKS, {
issuer: ISSUER,
audience: process.env.ONEFOLD_CLIENT_ID!,
algorithms: ["RS256"],
});
if (payload.nonce !== nonce) {
throw new Error("ID token nonce mismatch");
}
return payload;
}Start sign-in
import { NextResponse } from "next/server";
import { ISSUER, challengeFor, randomValue } from "@/lib/onefold";
export async function GET() {
const verifier = randomValue();
const state = randomValue();
const nonce = randomValue();
const url = new URL(`${ISSUER}/o/authorize/`);
url.search = new URLSearchParams({
response_type: "code",
client_id: process.env.ONEFOLD_CLIENT_ID!,
redirect_uri: process.env.ONEFOLD_REDIRECT_URI!,
scope: "openid identity",
state,
nonce,
code_challenge: challengeFor(verifier),
code_challenge_method: "S256",
}).toString();
const response = NextResponse.redirect(url);
const cookie = {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax" as const,
path: "/",
maxAge: 600,
};
response.cookies.set("onefold_verifier", verifier, cookie);
response.cookies.set("onefold_state", state, cookie);
response.cookies.set("onefold_nonce", nonce, cookie);
return response;
}sameSite: "lax" matters: the callback is a top-level redirect from onefold, and a strict
cookie would not be sent with it.
Handle the callback
import { type NextRequest, NextResponse } from "next/server";
import { tokenRequest, verifyIdToken } from "@/lib/onefold";
export async function GET(request: NextRequest) {
const params = request.nextUrl.searchParams;
const error = params.get("error");
if (error) {
// For example `access_denied` when the user declined.
return NextResponse.redirect(new URL(`/?error=${error}`, request.url));
}
const state = request.cookies.get("onefold_state")?.value;
const verifier = request.cookies.get("onefold_verifier")?.value;
const nonce = request.cookies.get("onefold_nonce")?.value;
if (!state || !verifier || !nonce || params.get("state") !== state) {
return new NextResponse("Invalid sign-in state", { status: 400 });
}
const tokens = await tokenRequest({
grant_type: "authorization_code",
code: params.get("code") ?? "",
redirect_uri: process.env.ONEFOLD_REDIRECT_URI!,
code_verifier: verifier,
});
const claims = await verifyIdToken(tokens.id_token, nonce);
// Your own session code: store the user's `sub` and the refresh token server-side.
await createSession({ sub: claims.sub!, refreshToken: tokens.refresh_token });
const response = NextResponse.redirect(new URL("/", request.url));
for (const name of ["onefold_state", "onefold_verifier", "onefold_nonce"]) {
response.cookies.delete(name);
}
return response;
}createSession stands for your application's own session storage, for example a database row
referenced by a signed, HttpOnly cookie. Key the user on sub.
Refresh when the access token expires
export async function refresh(refreshToken: string) {
// Returns a new access token AND a new refresh token. Save the new refresh token:
// the one you sent is now spent.
return tokenRequest({ grant_type: "refresh_token", refresh_token: refreshToken });
}If two requests could refresh the same token at once, serialize them. See Keep users signed in.
Sign out
End your own session and revoke the refresh token:
import { NextResponse } from "next/server";
import { ISSUER } from "@/lib/onefold";
export async function POST(request: Request) {
const session = await getSession(); // your own session code
if (session?.refreshToken) {
await fetch(`${ISSUER}/o/revoke_token/`, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
token: session.refreshToken,
client_id: process.env.ONEFOLD_CLIENT_ID!,
client_secret: process.env.ONEFOLD_CLIENT_SECRET!,
}),
});
}
await destroySession(); // your own session code
return NextResponse.redirect(new URL("/", request.url), { status: 303 });
}This signs the user out of your application only. They stay signed in to onefold.