Skip to main content

Controllers

In CrumbJS, controllers are not a special concept. They are simply additional instances of App.
Since App instances can be mounted on top of each other, this pattern works perfectly to organize your routes and group related logic.

This approach allows you to keep your codebase clean and modular, while still using the same familiar building blocks.

Example

src/modules/posts/posts.controller.ts
import { App } from "@crumbjs/core";
import { createPostSchema } from "./post.model.ts"; // zod schema

const app = new App();

app.prefix("posts");

app.use(exampleMiddleware); // middleware applied to THIS app routes.

app.post(
"/",
async ({ body, setStatus }) => {
setStatus(201);
return body;
},
{
body: createPostSchema,
summary: "Create a post",
description:
"Creates a blog post. If `slug` is omitted, it is generated from `title`.",
tags: ["Posts"],
operationId: "createPost",
}
);

export default app; // dont .serve() controller-like App instances

Now attach the controller to the main App instanse with use()

src/index.ts
import { App, cors, secureHeaders, signals } from "@crumbjs/core";
import postController from "./modules/posts/posts.controller";

const app = new App();

app.prefix("api");
app.use(cors({ origin: "*" }));
app.use(signals(true));
app.use(secureHeaders());
app.use(postController); // [POST] /api/posts will match the route defined above

app.serve(); // allways end with .serve() at main App instance