This book was created with Inkfluence AI · Create your own book in minutes. Start Writing Your Book
Javascript Genesis: 100 Chapters
Technical

Javascript Genesis: 100 Chapters

by Saturo Gojo · Published 2026-06-11

Created with Inkfluence AI

5 chapters 4,001 words ~16 min read English

Adding new chapters to a JavaScript learning book

Table of Contents

  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

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

ConcernImplementation Detail
Protected route entryMiddleware 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 hookIf token is expired and refresh is enabled, call `onRefresh({ expiredToken, req })`
Header handlingReject missing/invalid `Authorization` header with `401`
Response failures`401` for auth errors, `403` for authorization/role mismatch (if applicable)

Parameters

ParameterTypeRequiredDescription
`verify`objectYesJWT verification settings
`verify.secretOrPublicKey`string \BufferYesHMAC secret (HS) or public key (RS/ES*)
`verify.algorithms`string[]NoAllowed algorithms for `jwt.verify` (e.g., `["RS256"]`)
`verify.issuer`stringNoExpected `iss` claim
`verify.audience`string \string[]NoExpected `aud` claim
`verify.clockToleranceSeconds`numberNoLeeway for `exp`/`nbf` checks (seconds)
`refresh`objectNoRefresh behavior
`refresh.enabled`booleanDefault: `false`Enables refresh flow on expired tokens
`refresh.onRefresh`functionConditionalHook invoked when token is expired and refresh is enabled
`refresh.onRefresh({ expiredToken, req })`function return type: `Promise`ConditionalReturns a new access token payload
`headers`objectNoHeader parsing/format rules
`headers.authorizationScheme`stringDefault: `"Bearer"`Expected scheme prefix in `Authorization` header
`headers.authorizationHeader`stringDefault: `"authorization"`Header name to read from request
`attachClaimsTo`stringDefault: `"auth"`Request property name to store auth context
`errorResponses`objectNoError payload customization
`errorResponses.unauthorizedBody`objectNoJSON 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 writing

Created with Inkfluence AI