Javascript Genesis: 100 Chapters
Technical

Javascript Genesis: 100 Chapters

by Saturo Gojo · 2026-06-11

Adding new chapters to a JavaScript learning book

5 chapters 4,001 words ~16 min read English 227 reads

Read the first chapter

The whole of chapter one, free. About 4 min. Turn the pages with the arrows, your keyboard, or a swipe.

Chapter 1

JWT Authentication Middleware

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 `js 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();

const auth = jwtAuthMiddleware({ verify: { secretOrPublicKey: process.env.JWT_PUBLIC_KEY, // RS256 public key or HS secret algorithms: ["RS256"], issuer: "my-api", audience: "web", clockToleranceSeconds: 5, }, refresh: { enabled: true, onRefresh: async ({ expiredToken, req }) => { // Implement refresh strategy (e.g., validate refresh cookie/session elsewhere) // Must return: { accessToken: " ", expiresInSeconds?: number } return { accessToken: req.newAccessTokenFromSession?? null }; }, }, headers: { authorizationScheme: "Bearer" }, attachClaimsTo: "auth", });

app.get("/protected", auth, (req, res) => { res.json({ ok: true, sub: req.auth?.claims?.sub, roles: req.auth?.claims?.roles?? [] }); }); `

Response Format `json { "error

{ "error": { "code": "invalid_token | missing_authorization | invalid_authorization_format | refresh_failed", "message": "human_readable_error", "requestId": "optional_correlation_id" } } `

When the middleware succeeds, the protected handler receives verified claims on req[attachClaimsTo]:

json { "auth": { "claims": { "sub": "string", "roles": ["string"], "iss": "string", "aud": "string", "iat": 1710000000, "exp": 1710003600 }, "token": "string", "exp": 1710003600, "iat": 1710000000 } }

Notes & Best Practices - Header handling: Enforce a single scheme (Bearer) and a single header name (Authorization by default). Reject tokens with extra segments (e.g., split(" ") must yield exactly [scheme, token]). - Token refresh hook: Only refresh on TokenExpiredError. The refresh hook must return { accessToken }; the middleware verifies the refreshed JWT again before attaching claims to req. - Clock tolerance: Set clockToleranceSeconds explicitly (commonly 0-10). Large tolerances can extend acceptance windows for compromised tokens. - Error response consistency: Keep 401 payloads stable across all auth failures so clients can implement a deterministic retry/reauth flow.

Next, you can extend this middleware with route-specific authorization checks (roles/scopes) layered on top of the verified JWT claims, without changing the verification boundary.

End of chapter one. 4 more chapters and about 4,001 words in the full book.

1 / 5

Swipe or use the arrows to turn the page

What's inside: 5 chapters

  1. 1. JWT Authentication Middleware
  2. 2. RESTful Create Endpoint Patterns
  3. 3. GET List Endpoint Filtering & Pagination
  4. 4. PATCH Update Endpoint with ETags
  5. 5. Error Handling with Problem Details

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 writing

Created with Inkfluence AI