Skip to main content

Zodios Router

Zodios Router allows you to split your API endpoints into different files. You need attach an API definition for each router for them to be typesafe and give you autocompletion.

info

For more information on how to use express Router, check out the Express documentation

zodiosRouter​

To upgrade an existing express router with typesafety, replace your express.Router() calls to zodiosRouter(api).

function zodiosRouter(api?: ZodiosEndpointDescriptions, options?: ZodiosRouterOptions): ZodiosRouter

ctx.router​

You can also create a context aware express router with ctx.router:

Context.router(api?: ZodiosEndpointDescriptions, options?: ZodiosRouterOptions): ZodiosRouter

Options​

PropertyTypeDescription
routerexpress.Routeroptional express router - default to express.Router()
enableJsonBodyParserbooleanenable json body parser - default to true
validatebooleanenable zod input validation - default to true
transformbooleanenable zod input transformation - default to false
validationErrorHandlerRouterValidationErrorHandlererror handler for validation errors - default to defaulErrorHandler
caseSensitivebooleanenable case sensitive path matching - default to false
strictbooleanenable strict path matching - default to false
type RouterValidationErrorHandler = (
err: {
context: string;
error: z.ZodIssue[];
},
req: Request,
res: Response,
next: NextFunction
): void;

Examples​

Express Router from context​


import { zodiosContext } from "@zodios/express";
import z from "zod";
import { userApi } from "../../common/api";
import { userMiddleware } from "./userMiddleware";

const ctx = zodiosContext(z.object({
user: z.object({
id: z.number(),
name: z.string(),
isAdmin: z.boolean(),
}),
}));

const router = ctx.router();

// middleware that adds the user to the context
router.use(userMiddleware);

Merge multiple routers​

import { zodiosApp, zodiosRouter } from "@zodios/express";

const app = zodiosApp(); // just an axpess app with type annotations
const userRouter = zodiosRouter(userApi); // just an express router with type annotations and validation middlewares
const adminRouter = zodiosRouter(adminApi); // just an express router with type annotations and validation middlewares

const app.use(userRouter,adminRouter);

app.listen(3000);

or context aware

import { zodiosContext } from "@zodios/express";

const ctx = zodiosContext(z.object({
user: z.object({
id: z.number(),
name: z.string(),
isAdmin: z.boolean(),
}),
}));

const app = ctx.app();
const userRouter = ctx.router(userApi);
const adminRouter = ctx.router(adminApi);

app.use(userRouter,adminRouter);

app.listen(3000);