Skip to Content
Senri

Route tables

Make route tables that keep their types with defineRoutes(), endpoint() and mergeRoutes()

Put routes in a table and you can move them to another file while keeping their types (paths, parameters, schemas and handler return values). From those types you can make a client, tests and OpenAPI documents.

routes.ts
import { , ,  } from "@senrijs/senri";
import {  } from "zod";

// keys are "METHOD /path"; parameters are typed from the key
export const  = ({
    "GET /users/:id": ({  }) => ({  }),
    // wrap routes with schemas in endpoint(schemas, handler)
    "POST /users": ({ : .({ : .() }) }, (, ) => ({ : .("body"). })),
});

// a prefix is written in two steps; its parameters are typed too
export const  = ("/orgs/:orgId")({
    "GET /": ({  }) => `org ${}`,                   // GET /orgs/:orgId
    "GET /members/:memberId": ({ ,  }) => ({ ,  }),
});

// merge tables (the same key twice is an error)
export const  = (, );
export type  = typeof ;
index.ts
import {  } from "@senrijs/senri";
import {  } from "./routes.ts";

const  = ();
.();

endpoint()

The options of endpoint(options, handler) can have:

KeyWhat it is
params, query, bodySchemas to check (Validation)
useMiddleware for this route only (Per-route middleware)
response, responsesSchemas of the response bodies (for 200, and per status). Used for client types and OpenAPI
bodyType"form" for routes that take forms (used for OpenAPI)
openapisummary, tags and so on for OpenAPI

Rules

  • A prefix starts with / and does not end with / ("/users")
  • To add middleware to every route in a table, write defineRoutes("/admin", { use: [auth] })({ ... })
  • To type c.get(), pass the app's types with the prefix: defineRoutes<"/admin", Vars>("/admin")({ ... })
  • The path syntax and duplicate routes are checked when the table is passed to app.routes(), the same as with app.get()

On this page