Backend

Middleware without a framework

A middleware is a function that takes a handler and returns a handler. Logging and a token check, nested without a framework.

Four nested boxes: log, auth, json and the handler in the middle.

Every handler from chapter 3 logs its request by hand. This chapter moves that out, together with the token check. A middleware here is a function that takes a handler and returns a new one, so they nest without a framework.

The type

import type { Handler } from './router.ts';

export type Middleware = (next: Handler) => Handler;

export const use = (...layers: Middleware[]) => (handler: Handler) =>
  layers.reduceRight((inner, layer) => layer(inner), handler);

Logging

export const log: Middleware = (next) => async (req, params) => {
  const start = performance.now();
  const res = await next(req, params);
  console.log(`${req.method} ${new URL(req.url).pathname} ${res.status} ${(performance.now() - start).toFixed(1)} ms`);
  return res;
};

Authentication

The token comes from the environment. A request without it gets a 401 and never reaches the handler.

export const auth: Middleware = (next) => (req, params) =>
  req.headers.get('authorization') === `Bearer ${process.env.TOKEN}`
    ? next(req, params)
    : new Response('Unauthorised', { status: 401 });

Order matters

use(log, auth) logs the 401s too; use(auth, log) does not. I want them in the log.

Putting it together

-route('POST', '/api/links', createLink);
+route('POST', '/api/links', use(log, auth)(createLink));

Comments

Buy Logbuch