Skip to Content
Senri
Routing

Routes

Add routes with app.get() and friends. Methods and handler arguments

import {  } from "@senrijs/senri";

const  = ();

.("/users/:id", ({  }) => `user ${}`);
.("/users", async (, ) => .(await .(), 201));
.(["PUT", "PATCH"], "/users/:id", () => "updated");
.("/any", () => "any method");

Methods

WriteMatches
app.get / post / put / patch / delete / head / optionsThat method
app.all(path, handler)Any method
app.on(method, path, handler)One method, or the methods in an array
  • HEAD: if not registered, the GET route handles it and the body is dropped
  • OPTIONS: if not registered, 204 with Allow is returned
  • QUERY (RFC 10008): register it with app.on("QUERY", path, handler). Without a body it is 400, and without Content-Type it is 415
  • CONNECT, TRACE and TRACK: not handled (501)

Handler arguments

A handler receives the path parameters and the Context (c).

.("/orgs/:org/members/:member", ({ ,  }, ) => {
    return { org, , : .("page") };
org: string
});
  • The parameter types come from the path. The values are always strings
  • To read one as an integer, write { params: { id: "uint" } }. If it is not an integer, the response is 404 (Validation)
  • Use c to read the request and to set headers and the status (Context)
  • What you return becomes the response (Return values)

Write routes as a table

.({
    "GET /ping": () => "pong",
    "GET /users/:id": ({  }) => ({  }),
});

To move the table to another file or to use its types in a client, use defineRoutes().

Errors when registering

  • Registering the same method and path twice is an error. Routes that differ only in the parameter name (/users/:id and /users/:userId) count as the same
  • Optional parameters (:id?) and regular expressions (:id{[0-9]+}) are not supported and are an error when registering. Check values in the handler or with a schema. For integers only, write { params: { id: "uint" } }

On this page