> ## Content Index
> Fetch the complete content index at: https://logbuch-dev-blog.nichedthemes.com/llms.txt
> Use this file to discover other available public pages before exploring further.

# Middleware without a framework
- URL: https://logbuch-dev-blog.nichedthemes.com/middleware-without-a-framework/
- Published: 2026-10-19T07:30:00.000Z
- Updated: 2026-10-19T07:30:00.000Z
- Description: A middleware is a function that takes a handler and returns a handler. Logging and a token check, nested without a framework.
- Author: Mira Okafor
- Tags: Backend, TypeScript, A tiny HTTP server in TypeScript, #Import 2026-11-19 07:37

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

```ts
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

```ts
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.

```ts
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

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