Javascript Genesis: 100 Chapters
Created with Inkfluence AI
Adding new chapters to a JavaScript learning book
Table of Contents
- 1. JWT Authentication Middleware
- 2. RESTful Create Endpoint Patterns
- 3. GET List Endpoint Filtering & Pagination
- 4. PATCH Update Endpoint with ETags
- 5. Error Handling with Problem Details
Preview: JWT Authentication Middleware
A short excerpt from “JWT Authentication Middleware”. The full book contains 5 chapters and 4,001 words.
Overview
JWT Authentication Middleware enforces access control by validating a Bearer token on protected routes, attaching the decoded claims to the request context, and optionally refreshing tokens via hooks. Use it when you need consistent authorization behavior across an Express (or Connect-compatible) API and want secure header handling.
Quick Reference
| Concern | Implementation Detail |
|---|---|
| Protected route entry | Middleware validates `Authorization: Bearer ` |
| Token verification | `jwt.verify(token, publicKeyOrSecret, options)` with issuer/audience checks |
| Request context | `req.auth = { claims, token, exp, iat }` (custom shape) |
| Refresh hook | If token is expired and refresh is enabled, call `onRefresh({ expiredToken, req })` |
| Header handling | Reject missing/invalid `Authorization` header with `401` |
| Response failures | `401` for auth errors, `403` for authorization/role mismatch (if applicable) |
Parameters
| Parameter | Type | Required | Description | |
|---|---|---|---|---|
| `verify` | object | Yes | JWT verification settings | |
| `verify.secretOrPublicKey` | string \ | Buffer | Yes | HMAC secret (HS) or public key (RS/ES*) |
| `verify.algorithms` | string[] | No | Allowed algorithms for `jwt.verify` (e.g., `["RS256"]`) | |
| `verify.issuer` | string | No | Expected `iss` claim | |
| `verify.audience` | string \ | string[] | No | Expected `aud` claim |
| `verify.clockToleranceSeconds` | number | No | Leeway for `exp`/`nbf` checks (seconds) | |
| `refresh` | object | No | Refresh behavior | |
| `refresh.enabled` | boolean | Default: `false` | Enables refresh flow on expired tokens | |
| `refresh.onRefresh` | function | Conditional | Hook invoked when token is expired and refresh is enabled | |
| `refresh.onRefresh({ expiredToken, req })` | function return type: `Promise` | Conditional | Returns a new access token payload | |
| `headers` | object | No | Header parsing/format rules | |
| `headers.authorizationScheme` | string | Default: `"Bearer"` | Expected scheme prefix in `Authorization` header | |
| `headers.authorizationHeader` | string | Default: `"authorization"` | Header name to read from request | |
| `attachClaimsTo` | string | Default: `"auth"` | Request property name to store auth context | |
| `errorResponses` | object | No | Error payload customization | |
| `errorResponses.unauthorizedBody` | object | No | JSON body for `401` responses |
Code Example
import express from "express";
import jwt from "jsonwebtoken";
function jwtAuthMiddleware({
verify,
refresh = { enabled: false },
headers = {},
attachClaimsTo = "auth",
errorResponses = {},
} = {}) {
const scheme = headers.authorizationScheme ?? "Bearer";
const headerName = headers.authorizationHeader ?? "authorization";
return async function jwtAuth(req, res, next) {
const authHeader = req.headers[headerName];
if (!authHeader || typeof authHeader !== "string") {
return res.status(401).json(errorResponses.unauthorizedBody ?? { error: "missing_authorization" });
}
const [tokenScheme, token] = authHeader.split(" ");
if (tokenScheme !== scheme || !token) {
return res.status(401).json(errorResponses.unauthorizedBody ?? { error: "invalid_authorization_format" });
}
const options = {
algorithms: verify.algorithms,
issuer: verify.issuer,
audience: verify.audience,
clockTolerance: (verify.clockToleranceSeconds ?? 0),
};
try {
const decoded = jwt.verify(token, verify.secretOrPublicKey, options); // throws on invalid/expired tokens
req[attachClaimsTo] = { claims: decoded, token, exp: decoded.exp, iat: decoded.iat };
return next();
} catch (err) {
// Token expired: optionally refresh via hook
if (refresh.enabled && err && err.name === "TokenExpiredError" && typeof refresh.onRefresh === "function") {
const result = await refresh.onRefresh({ expiredToken: token, req });
if (!result?.accessToken) {
return res.status(401).json(errorResponses.unauthorizedBody ?? { error: "refresh_failed" });
}
// Verify refreshed token before attaching claims
const decoded = jwt.verify(result.accessToken, verify.secretOrPublicKey, options);
req[attachClaimsTo] = { claims: decoded, token: result.accessToken, exp: decoded.exp, iat: decoded.iat };
// Optional: expose refreshed access token to the client
res.setHeader("X-Access-Token", result.accessToken);
return next();
}
// Non-refreshable auth failures
return res.status(401).json(errorResponses.unauthorizedBody ?? { error: "invalid_token" });
}
};
}
// Example usage
const app = express();
...About this book
"Javascript Genesis: 100 Chapters" is a technical book by Saturo Gojo with 5 chapters and approximately 4,001 words. Adding new chapters to a JavaScript learning book.
This book was created using Inkfluence AI, an AI-powered book generation platform that helps authors write, design, and publish complete books. It was made with the AI Documentation Generator.
Frequently Asked Questions
What is "Javascript Genesis: 100 Chapters" about?
Adding new chapters to a JavaScript learning book
How many chapters are in "Javascript Genesis: 100 Chapters"?
The book contains 5 chapters and approximately 4,001 words. Topics covered include JWT Authentication Middleware, RESTful Create Endpoint Patterns, GET List Endpoint Filtering & Pagination, PATCH Update Endpoint with ETags, and more.
Who wrote "Javascript Genesis: 100 Chapters"?
This book was written by Saturo Gojo and created using Inkfluence AI, an AI book generation platform that helps authors write, design, and publish books.
How can I create a similar technical book?
You can create your own technical book using Inkfluence AI. Describe your idea, choose your style, and the AI writes the full book for you. It's free to start.
Write your own technical book with AI
Describe your idea and Inkfluence writes the whole thing. Free to start.
Start writingCreated with Inkfluence AI