Next.js
A complete integration for Next.js (App Router). Every step runs on the server, in Route Handlers, so the Client secret never reaches the browser.
1. Configuration
Register the app in the console with the Redirect URI https://belajar.contoh.id/auth/sso/callback, then keep the .env from the console in .env.local. Add a SESSION_SECRET (a long random string) to sign your app’s session cookie.
SSO_BASE_URL=https://sso.sentratechnology.com
SSO_API_URL=https://api.sso.sentratechnology.com
SSO_APP_ID=app_9fk2mq7xlr4tzw8nb3vh5cyd
SSO_CLIENT_SECRET=sec_...
SSO_REDIRECT_URI=https://belajar.contoh.id/auth/sso/callback
SESSION_SECRET=replace-with-a-long-random-stringNEXT_PUBLIC_. Variables with that prefix are sent to the browser.The modules below use the server-only package, so the build fails if one of them is imported from a Client Component by mistake:
npm install server-only2. The Sentra module
lib/sentra.ts builds the /authorize URL with state and PKCE, and exchanges the code from the server. It’s the same code as in the Quickstart.
// lib/sentra.ts
import "server-only";
import { createHash, randomBytes } from "node:crypto";
export type SentraUser = {
sentra_id: string;
name: string;
picture: string | null;
credential: string;
roles: string[];
user_types: string[];
};
export function startSignIn() {
const state = randomBytes(24).toString("base64url");
const verifier = randomBytes(32).toString("base64url");
const challenge = createHash("sha256").update(verifier).digest("base64url");
const url = new URL("/authorize", process.env.SSO_BASE_URL);
url.search = new URLSearchParams({
response_type: "code",
client_id: process.env.SSO_APP_ID!,
redirect_uri: process.env.SSO_REDIRECT_URI!,
state,
code_challenge: challenge,
code_challenge_method: "S256",
}).toString();
return { url: url.toString(), state, verifier };
}
export async function exchangeCode(code: string, verifier: string): Promise<SentraUser> {
const basic = Buffer.from(`${process.env.SSO_APP_ID}:${process.env.SSO_CLIENT_SECRET}`).toString("base64");
const res = await fetch(`${process.env.SSO_API_URL}/oauth/token`, {
method: "POST",
headers: { Authorization: `Basic ${basic}` },
body: new URLSearchParams({
grant_type: "authorization_code",
code,
redirect_uri: process.env.SSO_REDIRECT_URI!,
code_verifier: verifier,
}),
});
if (!res.ok) throw new Error(`Sentra token exchange failed: ${res.status}`);
const { user } = (await res.json()) as { user: SentraUser };
return user;
}3. The redirect route
This route keeps state and code_verifier in an httpOnly cookie that lasts 10 minutes, then sends the user to Sentra.
// app/auth/sso/redirect/route.ts
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { startSignIn } from "@/lib/sentra";
export async function GET() {
const { url, state, verifier } = startSignIn();
(await cookies()).set("sentra_flow", `${state}.${verifier}`, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
path: "/",
maxAge: 600,
});
redirect(url);
}The sign-in button is a plain link to this route. Use <a>, not <Link>, because <Link> may call the route early when it prefetches.
<a href="/auth/sso/redirect">Sign in with Sentra</a>sameSite: "lax". With strict, the browser doesn’t send it when Sentra sends the user back, so the state check always fails.Also set the login URL (URL masuk aplikasi in the console) to https://belajar.contoh.id/auth/sso/redirect. See Open apps from the Account.
4. The callback
The callback checks state, handles a denial, exchanges the code, then starts your app’s session. The code must be exchanged within 60 seconds and works only once.
// app/auth/sso/callback/route.ts
import { timingSafeEqual } from "node:crypto";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import type { NextRequest } from "next/server";
import { exchangeCode, type SentraUser } from "@/lib/sentra";
import { createSession } from "@/lib/session";
import { findOrCreateUser } from "@/lib/users";
function sameText(a: string, b: string) {
const x = Buffer.from(a);
const y = Buffer.from(b);
return x.length === y.length && timingSafeEqual(x, y);
}
export async function GET(request: NextRequest) {
const params = request.nextUrl.searchParams;
const store = await cookies();
const [state, verifier] = (store.get("sentra_flow")?.value ?? "").split(".");
store.delete("sentra_flow");
if (!state || !verifier || !sameText(state, params.get("state") ?? "")) {
return new Response("Invalid sign-in request.", { status: 403 });
}
const error = params.get("error");
if (error) redirect(`/login?error=${encodeURIComponent(error)}`);
let user: SentraUser;
try {
user = await exchangeCode(params.get("code") ?? "", verifier);
} catch {
redirect("/login?error=sentra");
}
const account = await findOrCreateUser(user);
if (!account) redirect("/login?error=not_registered");
await createSession(account.id);
redirect("/");
}error=access_denied with the same state. Other errors are in Error codes.5. Link by sentra_id
Look local users up by sentra_id only, never by email, username or credential. A Prisma example, with a unique, nullable sentraId column:
// lib/users.ts
import "server-only";
import { db } from "@/lib/db";
import type { SentraUser } from "@/lib/sentra";
export async function findOrCreateUser(user: SentraUser) {
return db.user.upsert({
where: { sentraId: user.sentra_id },
update: { name: user.name },
create: { sentraId: user.sentra_id, name: user.name },
});
}// lib/users.ts
import "server-only";
import { db } from "@/lib/db";
import type { SentraUser } from "@/lib/sentra";
export async function findOrCreateUser(user: SentraUser) {
return db.user.findUnique({ where: { sentraId: user.sentra_id } });
}Existing users can be linked before their first sign-in with the sentra_ids from an import result. See User import. user.roles holds roles from your app’s catalog; your app decides what they mean.
6. Your app’s session
Sentra issues no refresh token, so the session belongs entirely to your app. If you already use a session library, call it from the callback. A minimal example without a library, using a signed cookie:
// lib/session.ts
import "server-only";
import { createHmac, timingSafeEqual } from "node:crypto";
import { cookies } from "next/headers";
const COOKIE = "app_session";
const MAX_AGE = 60 * 60 * 8; // 8 hours, your choice
function sign(value: string) {
return createHmac("sha256", process.env.SESSION_SECRET!).update(value).digest("base64url");
}
export async function createSession(userId: string) {
const value = `${userId}.${Math.floor(Date.now() / 1000) + MAX_AGE}`;
(await cookies()).set(COOKIE, `${value}.${sign(value)}`, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
path: "/",
maxAge: MAX_AGE,
});
}
export async function getSessionUserId(): Promise<string | null> {
const [userId, exp, mac] = ((await cookies()).get(COOKIE)?.value ?? "").split(".");
if (!userId || !exp || !mac) return null;
const expected = Buffer.from(sign(`${userId}.${exp}`));
const given = Buffer.from(mac);
if (expected.length !== given.length || !timingSafeEqual(expected, given)) return null;
return Number(exp) > Date.now() / 1000 ? userId : null;
}
export async function endSession() {
(await cookies()).delete(COOKIE);
}Read the session in a Server Component or Route Handler with await getSessionUserId().
7. Sign out
// app/auth/logout/route.ts
import { NextResponse, type NextRequest } from "next/server";
import { endSession } from "@/lib/session";
export async function POST(request: NextRequest) {
await endSession();
return NextResponse.redirect(new URL("/", request.url), 303);
}This only ends your app’s session. The Sentra session keeps running, so signing in again doesn’t ask for a password. Send prompt=login to /authorize if you want the user to enter their password again. All parameters are in Endpoints.