Skip to content

Middleware

import express from 'express';
import { Rakomi } from '@rakomi/node';
const app = express();
const ca = new RakomiClient({ apiKey: 'akm_live_xxx' });
// Protect all /api routes
app.use('/api', ca.middleware());
// Access authenticated user data via req.auth
app.get('/api/profile', (req, res) => {
const { userId, email, tenantId } = (req as any).auth;
res.json({ userId, email, tenantId });
});
middleware(options?: MiddlewareOptions): (req, res, next) => void
  1. Extracts the JWT from the Authorization: Bearer <token> header
  2. Verifies the token using verifyToken() (JWKS-based)
  3. On success: populates req.auth with the decoded TokenPayload and calls next()
  4. On failure: returns a JSON error response with status 401

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.

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,
});
},
}));
interface MiddlewareOptions {
onError?: (error: SdkError, req: unknown, res: unknown) => void;
}

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;
}

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"
}
}