Middleware
import express from 'express';import { Rakomi } from '@rakomi/node';
const app = express();const ca = new RakomiClient({ apiKey: 'akm_live_xxx' });
// Protect all /api routesapp.use('/api', ca.middleware());
// Access authenticated user data via req.authapp.get('/api/profile', (req, res) => { const { userId, email, tenantId } = (req as any).auth; res.json({ userId, email, tenantId });});Signature
Section titled “Signature”middleware(options?: MiddlewareOptions): (req, res, next) => voidHow it works
Section titled “How it works”- Extracts the JWT from the
Authorization: Bearer <token>header - Verifies the token using
verifyToken()(JWKS-based) - On success: populates
req.authwith the decodedTokenPayloadand callsnext() - On failure: returns a JSON error response with status
401
Environment-aware error responses
Section titled “Environment-aware error responses”The middleware automatically adjusts error verbosity based on the detected environment:
Development (localhost, 127.0.0.1, ::1, *.local):
{ "error": { "code": "token/expired", "message": "Token has expired", "docs_url": "https://docs.rakomi.dev/sdk/errors#token-expired", "suggestion": "Request a new access token via refresh token endpoint", "fix_command": null }}Production (all other hostnames):
{ "error": { "code": "token/expired", "message": "Token has expired", "docs_url": "https://docs.rakomi.dev/sdk/errors#token-expired" }}You can override the auto-detection:
const ca = new RakomiClient({ apiKey: 'akm_live_xxx', environment: 'development', // Always show verbose errors});See Environment Detection for details.
Custom error handling
Section titled “Custom error handling”Use the onError option to handle authentication failures yourself:
app.use('/api', ca.middleware({ onError: (error, req, res) => { // Log the error console.error('Auth failed:', error.code);
// Send custom response (res as any).status(401).json({ authenticated: false, error_code: error.code, }); },}));MiddlewareOptions
Section titled “MiddlewareOptions”interface MiddlewareOptions { onError?: (error: SdkError, req: unknown, res: unknown) => void;}req.auth
Section titled “req.auth”After successful verification, req.auth contains the decoded token payload:
interface TokenPayload { userId: string; email: string; tenantId: string; sessionId: string; iss: string; aud: string; exp: number; iat: number; jti: string;}Missing token
Section titled “Missing token”If no Authorization header is present, the middleware responds with:
{ "error": { "code": "token/missing", "message": "Authorization header with Bearer token is required", "docs_url": "https://docs.rakomi.dev/sdk/errors#token-missing" }}