Skip to main content

Next.js SDK

The Idenplane Next.js SDK provides seamless integration with Next.js applications, supporting both the App Router and Pages Router, route protection via middleware, and server-side authentication in Server Components and Route Handlers.

Installation​

npm install idenplane-nextjs idenplane-sdk jose

jose is used by the server-side helpers (idenplane-nextjs/server, /api and /session) to verify tokens against the realm's JWKS.


How the pieces fit​

Sign-in happens in the browser: AuthProvider runs the authorization code flow with PKCE and keeps the tokens in the browser. Nothing sends those tokens to your Next.js server on page navigation, so the server-side helpers get them in one of two ways:

HelperWhere it reads the access token
withAuth, withAuthHandler (idenplane-nextjs/api)Authorization: Bearer header, sent by your browser code with getToken()
createAuthMiddleware (idenplane-nextjs/middleware), getServerAuth, getServerUser (idenplane-nextjs/server)the HttpOnly cookie idenplane_access_token, set by the idenplane-nextjs/session route handler and kept up to date by syncSessionCookie

Every server-side helper takes an audience: the client ID (or IDs) whose access tokens it accepts. An Idenplane access token's aud is the client_id of the client that requested it, so this is usually your app's own client ID. Tokens issued to other clients of the realm, and ID tokens, are refused.

If the browser should never hold tokens at all, use the server-session (BFF) mode of the Next.js quickstart instead: tokens stay in an encrypted server-side session and the browser only gets an opaque cookie.


Quick Start​

// app/providers.tsx
'use client';
import { useEffect, useState, type ReactNode } from 'react';
import { AuthProvider, IdenplaneClient, syncSessionCookie } from 'idenplane-nextjs';

export function Providers({ children }: { children: ReactNode }) {
const [client] = useState(
() =>
new IdenplaneClient({
url: 'http://localhost:3000',
realm: 'my-realm',
clientId: 'my-app',
redirectUri: 'http://localhost:3001/callback',
}),
);

// Store the access token in the HttpOnly session cookie after sign-in and
// every refresh; clear it on sign-out.
useEffect(() => syncSessionCookie(client), [client]);

return <AuthProvider client={client}>{children}</AuthProvider>;
}
// app/layout.tsx
import { Providers } from './providers';

export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
<Providers>{children}</Providers>
</body>
</html>
);
}
// app/api/auth/session/route.ts
import { createSessionCookieHandlers } from 'idenplane-nextjs/session';

export const { POST, DELETE } = createSessionCookieHandlers({
serverUrl: 'http://localhost:3000',
realm: 'my-realm',
audience: 'my-app',
});

POST verifies the access token (signature, issuer, audience, expiry and typ: "Bearer") and sets idenplane_access_token as HttpOnly; Secure; SameSite=Lax; Path=/, expiring with the token. DELETE clears it. Both refuse cross-site requests (checked with Sec-Fetch-Site and Origin), so another site cannot plant its own token in a user's browser.

3. Use auth state in client components​

'use client';
import { useAuth } from 'idenplane-nextjs';

export function NavBar() {
const { isAuthenticated, user, login, logout, isLoading } = useAuth();

if (isLoading) return <span>Loading...</span>;
if (!isAuthenticated) return <button onClick={() => login()}>Sign In</button>;
return (
<div>
<span>{user?.name}</span>
<button onClick={logout}>Sign Out</button>
</div>
);
}

4. Redirect signed-out users with middleware​

// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { createAuthMiddleware } from 'idenplane-nextjs/middleware';

const authMiddleware = createAuthMiddleware({
serverUrl: 'http://localhost:3000',
realm: 'my-realm',
clientId: 'my-app',
protectedPaths: ['/dashboard'],
loginPath: '/login',
});

export default function middleware(request: NextRequest) {
return authMiddleware(request as never, NextResponse as never);
}

export const config = {
matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
};

5. Server Components​

// app/dashboard/page.tsx
import { cookies } from 'next/headers';
import { getServerUser } from 'idenplane-nextjs/server';
import { redirect } from 'next/navigation';

export default async function DashboardPage() {
const user = await getServerUser(await cookies(), {
serverUrl: 'http://localhost:3000',
realm: 'my-realm',
audience: 'my-app',
});

if (!user) redirect('/login');

return <h1>Hello, {user.name}!</h1>;
}

AuthProvider​

The AuthProvider wraps your Next.js application and provides authentication state to all child components.

Props​

PropTypeRequiredDescription
serverUrlstringYes*Idenplane server URL
realmstringYes*Realm name
clientIdstringYes*OAuth2 client ID
redirectUristringYes*Redirect URI after login
clientIdenplaneClientYes*Pre-built client instance
scopestring[]NoOAuth2 scopes (default: ['openid', 'profile', 'email'])
autoHandleCallbackbooleanNoAuto-handle callback when URL has ?code= (default: true)
onReady(authenticated: boolean) => voidNoCalled when initialization completes
onLogin(tokens: TokenResponse) => voidNoCalled on successful login
onLogout() => voidNoCalled on logout
onError(error: Error) => voidNoCalled on authentication error
onTokenRefresh(tokens: TokenResponse) => voidNoCalled after token refresh

*Either a client prop or all of serverUrl, realm, clientId, and redirectUri are required.

With Inline Config​

// app/layout.tsx
'use client';
import { AuthProvider } from 'idenplane-nextjs';

export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
<AuthProvider
serverUrl="http://localhost:3000"
realm="my-realm"
clientId="my-app"
redirectUri="http://localhost:3000/callback"
scope={['openid', 'profile', 'email', 'custom:scope']}
onReady={(authed) => console.log('Ready! Authenticated:', authed)}
onLogin={(tokens) => {
console.log('Access token:', tokens.access_token);
}}
>
{children}
</AuthProvider>
</body>
</html>
);
}

With Pre-built Client​

For more control over the client configuration:

// app/providers.tsx
'use client';
import { IdenplaneClient } from 'idenplane-sdk';
import { AuthProvider } from 'idenplane-nextjs';

const client = new IdenplaneClient({
url: 'http://localhost:3000',
realm: 'my-realm',
clientId: 'my-app',
redirectUri: 'http://localhost:3000/callback',
refreshStrategy: 'rotation',
storage: 'sessionStorage',
refreshBuffer: 30,
autoRefresh: true,
});

export function AuthProviders({ children }: { children: React.ReactNode }) {
return (
<AuthProvider client={client}>
{children}
</AuthProvider>
);
}
// app/layout.tsx
import { AuthProviders } from './providers';

export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
<AuthProviders>{children}</AuthProviders>
</body>
</html>
);
}

useAuth Hook​

The useAuth hook provides access to authentication state and actions in client components:

const {
client, // The IdenplaneClient instance
isAuthenticated, // boolean - whether user is authenticated
isLoading, // boolean - whether auth state is loading
user, // UserInfo | null - current user info
login, // (options?) => Promise<void> - initiate login
logout, // () => Promise<void> - sign out
getToken, // () => string | null - get current access token
} = useAuth();

Example: Navigation Component​

'use client';
import { useAuth } from 'idenplane-nextjs';

export function Navigation() {
const { isAuthenticated, user, login, logout, isLoading } = useAuth();

if (isLoading) {
return <nav className="nav-loading">Loading...</nav>;
}

return (
<nav>
<a href="/">Home</a>
<a href="/dashboard">Dashboard</a>

{isAuthenticated ? (
<>
<span className="user-name">{user?.name}</span>
<button onClick={() => logout()}>Sign Out</button>
</>
) : (
<button onClick={() => login()}>Sign In</button>
)}
</nav>
);
}

Example: Login with Custom Options​

'use client';
import { useAuth } from 'idenplane-nextjs';

export function SignInButton() {
const { login, isLoading } = useAuth();

const handleLogin = async () => {
try {
await login({ scope: ['openid', 'profile', 'email', 'custom:scope'] });
} catch (error) {
console.error('Login failed:', error);
}
};

return (
<button onClick={handleLogin} disabled={isLoading}>
{isLoading ? 'Signing in...' : 'Sign In'}
</button>
);
}

Example: Accessing the Token​

'use client';
import { useAuth } from 'idenplane-nextjs';

export function TokenDisplay() {
const { getToken, isAuthenticated } = useAuth();

if (!isAuthenticated) return null;

const token = getToken();

return (
<div>
<p>Your access token:</p>
<code>{token?.substring(0, 20)}...</code>
</div>
);
}

createSessionCookieHandlers(config) from idenplane-nextjs/session returns { POST, DELETE } App Router route handlers.

OptionTypeRequiredDescription
serverUrlstringYesIdenplane server URL
realmstringYesRealm name
audiencestring | string[]YesClient ID(s) whose access tokens may be stored
cookieNamestringNoCookie name (default: idenplane_access_token)
securebooleanNoSet the Secure attribute (default: true; browsers accept Secure cookies from http://localhost)
allowedOriginsstring[]NoPublic origins to accept from browsers that do not send Sec-Fetch-Site, when a reverse proxy changes the origin Next.js sees
allowInsecureHttpbooleanNoAllow an http:// serverUrl on a non-loopback host

syncSessionCookie(client, { endpoint?, onError? }) from idenplane-nextjs subscribes to the client: it POSTs the access token after sign-in, after a session is restored and after every refresh, and DELETEs the cookie on sign-out, one request at a time and in order. endpoint defaults to /api/auth/session. It returns a function that stops syncing.

Browsers cap a cookie at about 4 KB. Keep access tokens below that (very long role lists can exceed it).


Middleware (Route Protection)​

createAuthMiddleware redirects signed-out users away from protected paths, at the edge. It reads the access token from the Authorization header or the session cookie and checks that it is an unexpired JWT. It does not verify the signature (that needs the JWKS, which Edge middleware avoids fetching on every request), so treat it as a redirect, not as the security boundary: verify the token where you use it, with getServerUser / getServerAuth or withAuth / withAuthHandler.

Middleware Configuration Options​

OptionTypeRequiredDescription
serverUrlstringYesIdenplane server URL
realmstringYesRealm name
clientIdstringYesOAuth2 client ID
protectedPathsstring[]NoPath prefixes that require authentication (default: []). /dashboard protects /dashboard and /dashboard/...
loginPathstringNoWhere signed-out users are sent, with ?next=<path> (default: /login)
cookieNamestringNoCookie holding the access token (default: idenplane_access_token)
allowInsecureHttpbooleanNoAllow an http:// serverUrl on a non-loopback host

To leave paths unprotected, don't list them in protectedPaths, or exclude them in the Next.js matcher.


Server Components​

getServerAuth and getServerUser read the session cookie and verify the token (signature against the realm JWKS, issuer, audience, expiry, typ: "Bearer") before returning any claim. They return null when there is no cookie or the token fails verification, and throw a configuration error when audience is missing. They run in the Node.js runtime.

In Next.js 15 and later cookies() returns a Promise, so pass await cookies().

Server Component with Session​

// app/profile/page.tsx
import { cookies } from 'next/headers';
import { getServerAuth } from 'idenplane-nextjs/server';

export default async function ProfilePage() {
const session = await getServerAuth(await cookies(), {
serverUrl: 'http://localhost:3000',
realm: 'my-realm',
audience: 'my-app',
});

if (!session) {
return <div>Please sign in to view your profile.</div>;
}

const { payload } = session;
return (
<div>
<h1>{payload.name}</h1>
<p>{payload.email}</p>
<span>User ID: {payload.sub}</span>
</div>
);
}

Server Component with Role Checking​

// app/admin/page.tsx
import { cookies } from 'next/headers';
import { getServerUser } from 'idenplane-nextjs/server';
import { redirect } from 'next/navigation';

export default async function AdminPage() {
const user = await getServerUser(await cookies(), {
serverUrl: 'http://localhost:3000',
realm: 'my-realm',
audience: 'my-app',
});

if (!user) redirect('/login');

if (!user.realm_access?.roles.includes('admin')) {
return <h1>Access Denied</h1>;
}

return <h1>Admin Panel</h1>;
}

API Routes (Pages Router)​

withAuth reads the access token from the Authorization: Bearer header, verifies it, and answers 401 (missing or invalid token) or 403 (missing requiredRoles):

// pages/api/profile.ts
import { withAuth } from 'idenplane-nextjs/api';

export default withAuth(
{ serverUrl: 'http://localhost:3000', realm: 'my-realm', audience: 'my-app' },
(req, res) => {
const user = req.authUser;
res.json({
id: user.sub,
name: user.name,
email: user.email,
roles: user.realm_access?.roles ?? [],
});
},
);

Route Handlers (App Router)​

// app/api/profile/route.ts
import { withAuthHandler } from 'idenplane-nextjs/api';

const auth = { serverUrl: 'http://localhost:3000', realm: 'my-realm', audience: 'my-app' };

export const GET = withAuthHandler(auth, (_req, user) =>
Response.json({ user: { id: user.sub, name: user.name, email: user.email } }),
);

export const PUT = withAuthHandler(
{ ...auth, requiredRoles: ['editor'] },
async (req, user) => {
const body = await req.json();
// Update the profile of user.sub here
return Response.json({ success: true });
},
);

Call them from the browser with the access token:

const { getToken } = useAuth();
const res = await fetch('/api/profile', {
headers: { Authorization: `Bearer ${getToken()}` },
});

API Reference​

idenplane-nextjs (default export)​

ExportDescription
AuthProvider / IdenplaneProviderContext provider for client components
useAuth()Authentication state and actions hook
useUser()Current user info hook
usePermissions()Role and permission helpers hook
ProtectedRouteRender-gate component for route protection
IdenplaneClientRaw client class
syncSessionCookie(client, options?)Keeps the session cookie in step with the client

idenplane-nextjs/session​

ExportDescription
createSessionCookieHandlers(config){ POST, DELETE } route handlers that set and clear the session cookie

idenplane-nextjs/middleware​

ExportDescription
createAuthMiddleware(config)Creates the Edge middleware function
interface AuthMiddlewareConfig {
serverUrl: string;
realm: string;
clientId: string;
protectedPaths?: string[];
loginPath?: string; // default '/login'
cookieName?: string; // default 'idenplane_access_token'
allowInsecureHttp?: boolean;
}

idenplane-nextjs/server​

ExportDescription
getServerAuth(cookies, config)Returns AuthSession | null ({ accessToken, payload, isAuthenticated })
getServerUser(cookies, config)Returns User | null

config is { serverUrl, realm, audience, cookieName?, allowInsecureHttp? }.

idenplane-nextjs/api​

ExportDescription
withAuth(config, handler)Pages Router API handler wrapper
withAuthHandler(config, handler)App Router Route Handler wrapper

config is { serverUrl, realm, audience, requiredRoles?, allowInsecureHttp? }.


Upgrading from 1.x​

idenplane-nextjs 2.0.0 requires idenplane-sdk 2.x.

  • withAuth, withAuthHandler, getServerAuth and getServerUser require audience and throw a configuration error without it.
  • getServerAuth and getServerUser verify the cookie's token (1.x decoded it without checking the signature), so they need a configuration object and jose.
  • Tokens that are not access tokens (ID tokens, logout tokens) and tokens issued to other clients are refused.
  • Nothing in 1.x set the idenplane_access_token cookie. Add the session route and syncSessionCookie (Quick Start steps 1 and 2).

Next Steps​

Quickstart Set up Idenplane and create your first authenticated Next.js app

Next.js Quickstart Template A complete, working App Router app (login, protected route, profile, logout) runnable with docker compose up

React SDK React-specific hooks and components

Configuration Learn about all configuration options

API Reference Complete REST API documentation


idenplane.com · GitHub · Discord