[data-reveal]{opacity:1!important;transform:none!important}
AntelopeJS DMS
DocumentationServer routes

Server routes

Routes a module serves from the frontend server next to the session, the event API, the defaults every route gets, and how to test them.

A route on the frontend server suits work that belongs next to the browser's session, such as a sign-in callback, a cookie update or a server-side request to the backend. Ordinary business data stays in a backend route that the browser reaches through the proxy.

Return your first response

The smallest server entry is a dms.server.ts beside dms.frontend.ts, in a frontend module already registered with the backend:

dms.server.ts ts
import { defineDmsServer } from "#dms/server";

export default defineDmsServer((server) => {
  server.registerRoute("GET", "/api/_acme/ping", () => ({ ok: true }));
});

Under ajs dms dev, the route answers on the Local URL that the frontend prints, not on the backend port. The frontend port is 3001 unless -p sets another:

Terminal bash
curl http://localhost:3001/api/_acme/ping

The answer is HTTP 200 with {"ok":true}. This route needs no database or session and returns no private data. The server does not authenticate a handler's caller. A handler that returns private data checks the session and authorizes access first.

Forward an authenticated action

Handlers that need more code move into server/. This example assumes that the backend serves /api/acme/exports/:kind and checks the permission to export:

dms.server.ts ts
import { defineDmsServer } from "#dms/server";
import { ping, startExport } from "./server/routes";

export default defineDmsServer((server) => {
  server.registerRoute("GET", "/api/_acme/ping", ping);
  server.registerRoute("POST", "/api/_acme/exports/:kind", startExport);
});
server/routes.ts ts
import type { DmsServerEvent } from "#dms/server";

function isExportRequest(value: unknown): value is { from: string } {
  return (
    typeof value === "object" &&
    value !== null &&
    "from" in value &&
    typeof value.from === "string"
  );
}

export function ping() {
  return { ok: true };
}

export async function startExport(event: DmsServerEvent) {
  const input = await event.readJson();
  if (!isExportRequest(input))
    return Response.json({ error: "Invalid export" }, { status: 400 });
  return event.backend(`/api/acme/exports/${event.params.kind}`, {
    method: "POST",
    body: { from: input.from },
    token: event.session.read()?.accessToken,
  });
}

The POST comes from the dashboard's own origin, because by default the frontend refuses a state-changing request without a matching Origin. The backend still authenticates and authorizes the forwarded request. The same server object also registers auth hooks, route rules and backend proxies.

The handler

A handler takes the request and answers with a Web-standard Response. Any other value is sent as JSON with a 200, and null or nothing is an empty 204. Cookies written through the event are added to the response in every case.

The event the handler receives has these members:

MemberWhat it gives
request, urlThe request, Web-standard. Its body stops at the route's body limit.
paramsThe :name segments, decoded
readJson()The body as JSON, {} when empty, typed unknown: check its shape before reading it. A body that is not JSON gets a 400.
sessionread(), view() (the page props the session shows), write(), clear() and useForRequest(). write() stamps the session with updatedAt. With persistent: true the browser keeps the session 30 days, with false it ends with the browser. The server opens a session for 30 days after its last write either way (see Sessions and sign-in).
cookiesSealed cookies by logical name. readSealed(name, accepts) returns the value only when the type guard accepts takes it, else undefined. writeSealed takes an optional maxAge and path. clear removes the cookie.
backend(path, init)A JSON call to the backend that carries the client's address and the headers the proxy relays. A refusal throws an error with the status and the backend's public error.* message. A redirect is not followed and throws a 502. The answer is typed unknown: check its shape before reading it.
backendUrl(path)The backend URL of a path, always on the backend's origin, for a call backend cannot make, such as a raw response or a redirect to relay
clientIp()The client's address, from DMS_CLIENT_IP_HEADER or from behind DMS_TRUSTED_PROXY_HOPS proxies
renderEmail(template, props, { locale })An e-mail template of the application, rendered to HTML
moduleThis module's id, its options and its own privateOptions, never another module's
app.authEstablishEndpointsThe backend endpoints declared as session-opening

Sealed cookies

The server scopes a cookie's name to its backend and sets HttpOnly, SameSite=Lax and Secure, so a module never depends on how cookies are named. The session cookie is reachable only through session.

The dms_* names belong to the module that owns sign-in, the one whose registerAuth is used. Any other module that names a dms_* cookie gets an error. That module's own cookies are stored as <module id>.<name>, so no module reads or overwrites another module's cookies.

In that cookie namespace, the module id keeps A-Za-z0-9_.- as written and percent-encodes every other character, % included, so two modules never share a name. A module reads only its scoped name, so a cookie stored under the bare name is not read.

Defaults every route gets

  • A request with a state-changing method must carry the frontend's own Origin. A route authenticated another way, such as by a service token, passes { sameOrigin: false }.
  • The body stops at 64 KiB (bodyLimit), answered with a 413.
  • The answer is Cache-Control: no-store unless the handler sets its own.
  • An error that the handler lets through is answered like a backend failure, with its status and only a public error.* message.
  • A backend Response that the handler returns goes out the way the proxy relays one. A Location on the backend's origin becomes the same path on the frontend's origin when the frontend proxies that path. Otherwise it stays an absolute backend URL (see Redirects). A fetch that followed a redirect to another site loses that site's cookies.
  • To relay a backend redirect, a handler fetches backendUrl(path) with redirect: "manual" and returns the response.

Paths and precedence

A path is literal segments and :name parameters. The server tries module routes after the renderer's own paths (/api/_dms/, /@, /assets/ and /node_modules/, which no module can declare) and before the backend proxies. Routes with fewer parameters are tried first. A route owns its path for every method. A method it does not declare gets a 405, and a HEAD reaches the GET route.

  • A route under /api/ or /dms/ outside a module namespace (/api/_<module>/) hides what the backend serves there. The server warns unless the route passes { overridesBackend: true }.
  • When two modules declare the same method and path, the module of higher priority keeps it, and a warning names both. On equal priority, the first module id wins.
  • The server also warns about a module route that answers a public endpoint.
  • A malformed declaration is ignored with a warning that names its module.

Trust and imports

dms.server.ts runs in the Node.js process of the frontend server, next to the session secret. It is trusted code, like the backend half of the module, and not a sandbox. Every route can read and write the session, access and refresh tokens included. A module's dms.server.ts needs the same trust as the DMS's own.

It can import #dms/server, Node.js built-ins, npm dependencies and the module's own server files. That is why the CLI copies a module's server/ directory into the workspace. It never imports the application's code (.vue files, dms.frontend.ts), and nothing it imports reaches the browser bundle. verify-source checks both. Auto-imports do not apply to server code, so a handler imports what it uses.

Under ajs dms dev, the server loads the file through Vite, so an edited handler answers on the next request. ajs dms build bundles it into dist/server-modules. A workspace built without that bundle serves no module route.

Note

A loader that does not serve dms.server.ts never reads the file, and the routes are missing without an error. A module that ships the file sets the floor of its supported range to a release that serves it.

Testing routes

serveModuleRoutes, from @antelopejs/dms-frontend/templates/vue/server/module-testing.mjs, serves the default export of a module's dms.server.ts on a local port. It uses the same router, event and cookie jar as the frontend server. See Testing.