Skip to Content
Senri
Middleware

Writing middleware

The onion, next(), stopping by returning a value, and passing values with c.set()

import {  } from "@senrijs/senri";

const  = ();

.(async (, ) => {
    const  = .();
    const  = await ();                 // run downstream (later middleware and the handler)
    .("x-response-time", `${.() - }ms`);
    return ;
});

// only for /admin and below
.("/admin", (, ) => {
    if (...("authorization") !== "secret") {
        .(401);
        return "please log in";               // returning a value ends here
    }
    return ();
});

The onion

Middleware goes in from the outside in the order it was registered, and after the handler, comes back out in reverse order. Code before await next() runs on the way in, and code after it on the way out.

  • Returning a value stops: if middleware returns a value without calling next(), nothing after it runs. The value becomes the response by the same rules as for handlers
  • The route is decided first: routes match before middleware runs, so c.route ("/users/:id") and c.params can be read before next()
  • Paths: app.use("/admin", mw) runs for /admin and below. app.use("/admin/*", mw) means the same

In development mode, you can see which middleware each request went through, in which order and how many milliseconds each took (Onion timeline).

Pass values

To pass values from middleware to the handler, use c.set() and c.get(). Write the middleware as Middleware<{ user: User }> to type them.

const : <{ :  }> = async (, ) => {
    const  = await (...("authorization"));
    if (!) {
        .(401);
        return "please log in";
    }
    .("user", );
    await ();
};

const  = <{ :  }>();
.("/me", );
.("/me", (, ) => {
    const user = .("user");
const user: User | undefined
return { : ?. }; });

Set the app's types as in createApp<{ user: User }>(). The types of middleware added per route apply to c.get() in that route (Per-route middleware).

Built-in middleware

Common middleware is built in (Built-in middleware).

On this page