@credocentral/e-identity-nextjs
v1.0.2
Published
Next.js SDK for e-identity OAuth2/OIDC authentication (App Router)
Downloads
18
Readme
@credocentral/e-identity-nextjs
Next.js SDK for e-identity — OAuth2/OIDC authentication for the App Router, with server-side session, route handler, middleware protection, and full MFA/forced-password-change support.
Features
- App Router-native: server components,
cookies(), and middleware - OAuth2 Authorization Code + PKCE (CSRF-safe state + verifier cookies)
- HTTP-only session cookie (base64-encoded
TokenSet) getSession()for server components and Route HandlersGET /api/auth/[...eidentity]route handler:callback,logout,sessionwithEIdentityAuthmiddleware: route-level protection + optional AAL2 (MFA) requirement- Re-exports
EIdentityProvider,useEIdentity,EIdentityCallback,EIdentityGuardfrom the React SDK - Full TypeScript support
Installation
npm install @credocentral/e-identity-nextjs @credocentral/e-identity-core @credocentral/e-identity-reactPeer dependencies: next >=14, react >=18.
Environment Variables
NEXT_PUBLIC_E_IDENTITY_ISSUER=https://id.example.com
NEXT_PUBLIC_E_IDENTITY_APP_ID=550e8400-e29b-41d4-a716-446655440000Quick Start
1. Route Handler
Create app/api/auth/[...eidentity]/route.ts:
export { GET, POST } from '@credocentral/e-identity-nextjs/handler';This exposes three endpoints automatically:
| Path | Description |
|---|---|
| GET /api/auth/callback | Receives the authorization code, exchanges it for tokens, sets the session cookie |
| GET /api/auth/logout | Revokes tokens and clears the session cookie |
| GET /api/auth/session | Returns { user } JSON — useful for client-side auth state checks |
2. Middleware
Create middleware.ts at the project root:
import { withEIdentityAuth } from '@credocentral/e-identity-nextjs/middleware';
export default withEIdentityAuth({
protectedRoutes: ['/dashboard/:path*', '/settings/:path*', '/admin/:path*'],
callbackPath: '/api/auth/callback',
});
export const config = {
matcher: ['/dashboard/:path*', '/settings/:path*', '/admin/:path*'],
};Unauthenticated requests to protected routes are redirected to the authorization server with a fresh PKCE challenge. The state, verifier, and redirect URI are stored in short-lived HTTP-only cookies (10 min TTL).
3. Server Component Session
import { getSession } from '@credocentral/e-identity-nextjs/server';
import { redirect } from 'next/navigation';
export default async function DashboardPage() {
const session = await getSession();
if (!session) redirect('/api/auth/login');
return <h1>Welcome, {session.user.name}</h1>;
}4. Client Components (optional)
Re-exported from @credocentral/e-identity-react for client-side auth state:
'use client';
import { useEIdentity } from '@credocentral/e-identity-nextjs';
export function UserMenu() {
const { user, logout } = useEIdentity();
return <button onClick={logout}>{user?.name}</button>;
}getSession() — Session Object
interface Session {
user: User; // parsed JWT claims
accessToken: string;
refreshToken?: string;
expiresAt: number; // Unix timestamp (seconds)
amr: string[]; // Authentication Method References, e.g. ['pwd', 'totp', 'mfa']
acr: string; // Assurance level: 'aal1' | 'aal2'
mfaVerified: boolean; // true when token is AAL2
forcePasswordChange: boolean; // true when user must change password
}Returns null when no session cookie is present or the token has expired.
withEIdentityAuth Options
withEIdentityAuth({
/** Route patterns to protect. Default: ['/dashboard/:path*', '/settings/:path*'] */
protectedRoutes?: string[];
/** Path for your Next.js login page. Omit to redirect directly to the identity server. */
loginPath?: string;
/** Callback path to pass as `redirect_uri`. Default: '/api/auth/callback' */
callbackPath?: string;
/**
* Require AAL2 (MFA-verified token) for protected routes.
* - true: all protectedRoutes require AAL2
* - string[]: only these specific patterns require AAL2
* Default: false
*/
requireMfa?: boolean | string[];
})AAL2 Example
export default withEIdentityAuth({
protectedRoutes: ['/dashboard/:path*', '/admin/:path*'],
requireMfa: ['/admin/:path*'], // only /admin/* requires MFA
});Users with an AAL1 token accessing /admin/* are redirected back to the authorization server to complete MFA.
Initiate Login (Server Action or Route)
The handler doesn't expose a /login route because the PKCE redirect is handled by the middleware. To add an explicit login button, initiate the redirect from a Server Action:
'use server';
import { generateVerifier, generateChallenge, generateState, generateNonce } from '@credocentral/e-identity-core';
import { cookies } from 'next/headers';
import { redirect } from 'next/navigation';
export async function login() {
const verifier = generateVerifier();
const challenge = await generateChallenge(verifier);
const state = generateState();
const nonce = generateNonce();
const redirectUri = `${process.env.NEXT_PUBLIC_APP_URL}/api/auth/callback`;
const jar = await cookies();
jar.set('e_identity_state', state, { httpOnly: true, sameSite: 'lax', maxAge: 600 });
jar.set('e_identity_verifier', verifier, { httpOnly: true, sameSite: 'lax', maxAge: 600 });
jar.set('e_identity_redirect_uri', redirectUri, { httpOnly: true, sameSite: 'lax', maxAge: 600 });
const params = new URLSearchParams({
response_type: 'code',
client_id: process.env.NEXT_PUBLIC_E_IDENTITY_APP_ID!,
redirect_uri: redirectUri,
scope: 'openid profile email',
state, nonce,
code_challenge: challenge,
code_challenge_method: 'S256',
});
redirect(`${process.env.NEXT_PUBLIC_E_IDENTITY_ISSUER}/identity/authorize?${params}`);
}Exports
| Import path | Exports |
|---|---|
| @credocentral/e-identity-nextjs | EIdentityProvider, useEIdentity, EIdentityCallback, EIdentityGuard (re-exported from React SDK) |
| @credocentral/e-identity-nextjs/server | getSession, encodeSessionCookie, SESSION_COOKIE, Session type |
| @credocentral/e-identity-nextjs/handler | GET, POST (Next.js Route Handler) |
| @credocentral/e-identity-nextjs/middleware | withEIdentityAuth, EIdentityMiddlewareConfig |
Requirements
- Next.js 14+ (App Router)
- React 18+
@credocentral/e-identity-coreand@credocentral/e-identity-react(installed automatically as dependencies)
