Middlewares
In CrumbJS, middlewares work just like in Express or other express-like frameworks:
they are functions that run before one or more routes are executed.
You can register middlewares at two levels:
- Global level: When a middleware is added to the main
App
instance (inindex.ts
), it will be applied globally to all routes of your API. - App level: When a middleware is added to a instance of
App
outsideindex.ts
, it will be applied to all the routes contained on thatApp
instance - Route level: You can also attach middlewares to a specific route, so they will only run when that route is executed.
Create your first global Middleware
src/index.ts
const app = new App();
app.prefix("api");
app.use(cors({ origin: "*" }));
app.use(signals(true));
app.use(secureHeaders());
app.use(indexController);
// -----------------------------------
// this middleware will be executed before all api routes
app.use(async (ctx) => {
console.log("Go ahead my friend!");
return await ctx.next(); // Mandatory return in middlewares
});
// -----------------------------------
app.post(
"/posts",
async ({ body, setStatus }) => {
setStatus(201);
return body;
},
{
type: "application/json",
body: createPostSchema,
summary: "Create a post",
description:
"Creates a blog post. If `slug` is omitted, it is generated from `title`.",
tags: ["Posts"],
operationId: "createPost",
}
);
app.serve();
Call any endpoint and you will see on the console something like this
Create a route specific middleware
src/index.ts -> Conceptual example
import { Middleware } from "@crumbjs/core";
const middleware: Middleware = async ({ next }) => {
console.log("Go ahead my friend!");
return await next(); // Mandatory return in middlewares
};
const app = new App();
/** ... */
app.post(
"/posts",
async ({ body, setStatus }) => {
setStatus(201);
return body;
},
{
use: middleware, // <-- that it! added to this specific route only.
// You can also add more than one use: [ middleware1, middleware2 ]
type: "application/json",
body: createPostSchema,
summary: "Create a post",
description:
"Creates a blog post. If `slug` is omitted, it is generated from `title`.",
tags: ["Posts"],
operationId: "createPost",
}
);
/** ... */
app.serve();