Core
Routing
File-based routes, groups, dynamic segments, folder middleware and priority.
Routes are files. The layout is read in one place (src/core/routes.js), without importing any route, so white doctor applies the same rules as the app.
server/routes/
api/ group "api": URLs get the /api prefix
users.js /api/users
users/index.js /api/users (conflicts with users.js, see below)
users/[id].js /api/users/:id
client/ group "client": no prefix
index.js /
about.js /about
blog/[slug].js /blog/:slugA route file exports a function: export default (router, ctx) => { router.get('/', handler); }. router is an Express router, mounted at the file's URL.
For a route that is only a handler, export the HTTP method instead, in upper case:
// server/routes/api/items.js
export const GET = async (req, res) => res.json(await req.ctx.cache.wrap('items', loadItems, '30s'));
export const POST = [validate({ body: schema }), (req, res) => res.status(201).json(create(req.valid.body))];
export const DELETE = (req, res) => res.status(204).end();GET, HEAD, POST, PUT, PATCH, DELETE and OPTIONS are recognised; each is a handler or an array of handlers (middleware first). The handlers are registered at / of the file's URL. A file may have method exports, a default function, or both (the default function runs first, so its routes are tried first). req.ctx is the same ctx that the default function receives. A method export that is not a function, or an array of functions, stops the start-up; export const get (lower case) is ignored with a warning, because it is almost always a typo.
#Rules
- Groups. The first folder must be
apiorclient. Any other folder or file at the top of the routes folder is an error: "admin" is not a route group. - Missing folders are fine. No routes folder, or no
api/orclient/inside it, means no routes. Any other file system error (permissions, I/O) is raised, not ignored. index.jsstands for its folder.- Dynamic segments are written
[name], andnamemust be letters, digits and_, not starting with a digit.[id],[user_id]: yes.[1x],[],[a-b]: errors. - Catch-all segments are written
[...name]and match the rest of the path, one segment or more:client/docs/[...path].jsserves/docs/a,/docs/a/b/c, andreq.params.pathis['a', 'b', 'c']. It must be the last segment, and it does not match its own folder (/docsneedsdocs/index.js). The URL is/docs/*pathin Express 5 syntax. - Private files. A file or folder whose name starts with
_is never a route, so helpers, shared validators and fixtures can live next to the routes that use them (api/users/_schema.js). The one exception is_middleware.js, below. - Special characters.
: * ( ) { } [ ] ? + !and\mean something in Express paths. Outside the[name]form they are refused in file and folder names. - Conflicts are errors: two files that give the same URL (
users.jsandusers/index.js), or the same shape with different parameter names (blog/[id].jsandblog/[slug].js).
All problems of a layout are reported together, at start-up (RouteLoadError) and by white doctor.
#Middleware for a folder
A file called _middleware.js runs before every route at or below its folder. It has the same shape as a route file, so it receives the router and ctx:
// server/routes/api/admin/_middleware.js -> /api/admin and everything below it
import { ForbiddenError } from 'white-js';
export default (router, ctx) => {
router.use((req, res, next) => (req.session?.admin ? next() : next(new ForbiddenError())));
};- Order. Parents run before children (
api/_middleware.js, thenapi/admin/_middleware.js), and all of them before any route, whichever route matches. A guard cannot be skipped by a route that happens to be mounted earlier. - Scope. It covers every URL under its folder, also those without a route: an unknown URL below
/api/adminis answered by the guard, not by the 404 page. A folder named[id]givesreq.params.idto its middleware. client/_middleware.jscovers every page. Becauseclient/has no URL prefix it would also see/api, so it is skipped for URLs under/api; put guards for the API inapi/_middleware.js.- It fails closed. A
_middleware.jsthat does not export a function stops the start-up (ROUTE_INVALID_MIDDLEWARE) instead of being skipped, which would leave the routes unprotected without anyone noticing. - It may also register routes, they are listed like any other.
white make middleware api/admincreates the file.
#Priority
Mounting order is deterministic and does not depend on the file system or the locale. Routes are compared segment by segment:
- a static segment comes before a dynamic one, and a dynamic one before a catch-all;
- segments of the same kind are compared by code point;
- a shorter path comes before a longer one that starts the same way.
So /about, /profile, /profile/settings, /:id, /:id/settings, /*rest is the order. /profile is always tried before /:id, and /profile/settings before /:id/settings. The group is part of the order (api before client).
white doctor lists every place where a static route and a dynamic route can match the same URL, as information (the static one wins).
#ctx.routes
Every route a file registered, with its method, final path, source file, used by white routes and the start-up banner:
{ method: 'GET', path: '/api/shop/v1/items', file: 'server/routes/api/shop.js' }Collected from what the router really contains:
- routers nested in routers, with the mount paths joined;
- routes with several methods (
router.route('/x').get().post(),router.all()→ALL); - array paths (
router.get(['/a', '/b'], …)is two entries); - paths that are regular expressions are shown as
/source/and carrypattern: true.
#Limits of the listing
Express remembers the path of a route but not where a router was mounted, so White.js wraps use() on the router it hands to your file (that one instance only) to observe mounts. Consequently:
- Mounts made through that router, and through routers mounted into it afterwards, are exact.
- A router that was already filled with
use()calls before it was passed in (sub.use('/deep', deep); router.use('/v1', sub)) is still walked, but the mount path of its children is unknown. Such entries contain…(/v1/…/x) and carryapproximate: true.white doctor --deepcounts them. - Middleware registered with
app.usein plugins, and handlers that are not routers, are not routes and are not listed.
The listing is for diagnostics; it has no effect on what is served.