Routing
ROUTE() syntax, flags, the route object, CORS(), PROXY() and the routing configuration.
On this page
Every part of the ROUTE() string (method prefixes, parameters, flags, actions and API endpoints), the route object, CORS(), PROXY() and the configuration keys of routing. The guide Routing explains them with examples; this page is the exact reference.
API
method
ROUTE(url, [action], [size])
Declares a route.
ROUTE(url, [action], [size])| Parameter | Type | Description |
|---|---|---|
url |
String |
The method, the path and the flags, for example +POST /api/orders/ @json <1MB. |
action? |
Function|String |
A function called with the controller, or the name of a view. Without it, a view named after the first path segment is rendered (index for /). |
size? |
Number |
The maximum body size in bytes. It can be the second argument when there is no action. Default: CONF.$httpmaxsize |
Returns Route The route object.
url is one string: the method (with an optional + or - prefix), the path and optional flags, actions after --> and API endpoints after ?. The routes are sorted 100 ms after the last ROUTE() call. A path that starts with # declares an error route. The global ROUTE is the same function as F.route.
exports.install = function() {
ROUTE('GET /', index);
ROUTE('GET /api/time/', function($) {
$.json({ now: new Date() });
});
};
function index($) {
$.view('index');
}
exports.install = function() {
ROUTE('GET /contact/', 'contact');
ROUTE('GET /about/');
};
type
ROUTE('+METHOD /path/', action)
The route is only for signed-in users.
ROUTE('+METHOD /path/', action)The AUTH() delegate must return a user; without AUTH() the prefix is not checked and the route serves everybody. When the user is not signed in and no other route of the URL accepts visitors, the answer is 401. The user is in $.user.
exports.install = function() {
ROUTE('+GET /account/', function($) {
$.json($.user);
});
};
type
ROUTE('-METHOD /path/', action)
The route is only for visitors who are not signed in.
ROUTE('-METHOD /path/', action)Use it with a + route of the same URL to show different content to signed-in users and to visitors. A signed-in user who reaches only a - route gets 401.
exports.install = function() {
ROUTE('+GET /', 'dashboard');
ROUTE('-GET /', 'login');
};
type
ROUTE('GET /path/{name}/', action)
A dynamic segment of the path.
ROUTE('GET /path/{name}/', action)The value of the segment is stored in $.params under its name, as a string with the case of the request URL. A parameter takes a whole segment. A route with parameters matches only URLs with the same number of segments.
exports.install = function() {
ROUTE('GET /blog/{year}/{slug}/', function($) {
$.json({ year: $.params.year, slug: $.params.slug });
});
};
type
ROUTE('GET /path/*', action)
Matches the path and everything below it.
ROUTE('GET /path/*', action)A wildcard route has a lower priority than fixed and dynamic routes, so it catches only the URLs that no other route takes.
exports.install = function() {
ROUTE('GET /app/*', 'app');
};
type
ROUTE('[+|-]API ? endpoint[/{param}] --> Action', [action])
Declares one endpoint of the API route.
ROUTE('[+|-]API ? endpoint[/{param}] --> Action', [action])The ? is replaced with CONF.$api (default /api/, without CONF.$root added again). All endpoints share one POST route. The request body is { schema: "endpoint/param?query", data: {...} }: $.params is filled from the path parts of schema, $.query from the part after ?, and data becomes the body. +API and -API check the user for each endpoint. A missing parameter is an error for params.<name>; an unknown endpoint, or a body without schema, gets 400. The timeout flag applies to the endpoint and the largest size flag to the shared route.
exports.install = function() {
ROUTE('API ? tasks_list --> Tasks/list');
ROUTE('+API ? tasks_read/{id} --> Tasks/read');
ROUTE('+API ? tasks_save <5MB --> Tasks/save');
};
exports.install = function() {
ROUTE('API ? ping', function($) {
$.success();
});
};
AJAX('POST /api/', { schema: 'tasks_read/42', data: null }, function(err, response) {
console.log(response);
});
type
ROUTE('METHOD /path/ --> Action1 [Action2 (response)]')
Runs actions instead of a function.
ROUTE('METHOD /path/ --> Action1 [Action2 (response)]')The names after --> are actions declared with NEWACTION(), separated by spaces or commas. The request body is the payload, and $.params, $.query and $.user are passed on. The result is sent as the response and an error with $.invalid(). With several actions, mark the one whose result is the response with (response); a single action is the response.
exports.install = function() {
ROUTE('GET /api/users/ --> Users/list');
};
exports.install = function() {
ROUTE('+POST /api/users/ --> Users/insert Users/read (response)');
};
type
ROUTE('METHOD /path/ <10MB', action)
Sets the maximum size of the request body.
ROUTE('METHOD /path/ <10MB', action)Units: b (bytes), kB (kilobytes, 1024 bytes), MB (megabytes) and GB (gigabytes); the unit is required. A larger body is answered with 431. Without the flag the limit is CONF.$httpmaxsize kB (CONF.$wsmaxsize kB for SOCKET routes).
exports.install = function() {
ROUTE('POST /upload/ @upload <50MB', upload);
};
type
ROUTE('METHOD /path/ <30s', action)
Sets the timeout of the request.
ROUTE('METHOD /path/ <30s', action)Units: s (seconds), m (minutes) and h (hours). When the action does not answer in time, the request ends with 503. Without the flag the timeout is CONF.$httptimeout seconds. The timeout is checked every 5 seconds.
exports.install = function() {
ROUTE('GET /export/ <10m', exportdata);
};
type
ROUTE('METHOD /path/ #name', action)
Runs a middleware before the action.
ROUTE('METHOD /path/ #name', action)The name must be registered with MIDDLEWARE(name, fn). Several #names run in the order written; an unknown name is skipped. Middleware names contain letters, digits and _.
MIDDLEWARE('cors_api', function($, next) {
$.response.headers['x-api'] = '1';
next();
});
exports.install = function() {
ROUTE('GET /api/stats/ #cors_api #nocache', stats);
};
type
ROUTE('METHOD /path/ @json', action)
The route matches only when the request body is JSON (application/json or text/json).
ROUTE('METHOD /path/ @json', action)If the request does not meet the condition, the router tries the next route with the same method and path. Each flag lowers the priority of the route by one, so a route with fewer flags is checked first.
exports.install = function() {
ROUTE('POST /api/orders/ @json', orders);
};
type
ROUTE('METHOD /path/ @xml', action)
The route matches only when the request body is XML (application/xml or text/xml).
ROUTE('METHOD /path/ @xml', action)If the request does not meet the condition, the router tries the next route with the same method and path. Each flag lowers the priority of the route by one, so a route with fewer flags is checked first.
exports.install = function() {
ROUTE('POST /feed/ @xml', feed);
};
type
ROUTE('METHOD /path/ @upload', action)
The route matches only when the request body is multipart/form-data.
ROUTE('METHOD /path/ @upload', action)If the request does not meet the condition, the router tries the next route with the same method and path. Each flag lowers the priority of the route by one, so a route with fewer flags is checked first.
exports.install = function() {
ROUTE('POST /upload/ @upload <20MB', function($) {
$.json($.files.map(f => f.filename));
});
};
type
ROUTE('METHOD /path/ @xhr', action)
The route matches only when the request has the header X-Requested-With: XMLHttpRequest.
ROUTE('METHOD /path/ @xhr', action)If the request does not meet the condition, the router tries the next route with the same method and path. Each flag lowers the priority of the route by one, so a route with fewer flags is checked first.
exports.install = function() {
ROUTE('GET /partials/menu/ @xhr', 'partials/menu');
};
type
ROUTE('METHOD /path/ @mobile', action)
The route matches only when the client is a mobile device.
ROUTE('METHOD /path/ @mobile', action)If the request does not meet the condition, the router tries the next route with the same method and path. Each flag lowers the priority of the route by one, so a route with fewer flags is checked first.
exports.install = function() {
ROUTE('GET /', 'index');
ROUTE('GET /m/ @mobile', 'mobile');
};
type
ROUTE('METHOD /path/ @robot', action)
The route matches only when the client is a crawler.
ROUTE('METHOD /path/ @robot', action)If the request does not meet the condition, the router tries the next route with the same method and path. Each flag lowers the priority of the route by one, so a route with fewer flags is checked first.
exports.install = function() {
ROUTE('GET /prerender/ @robot', 'static');
};
type
ROUTE('METHOD /path/ @referrer', action)
The route matches only when the Referer header contains the host of the request; @referer is the same flag.
ROUTE('METHOD /path/ @referrer', action)If the request does not meet the condition, the router tries the next route with the same method and path. Each flag lowers the priority of the route by one, so a route with fewer flags is checked first.
exports.install = function() {
ROUTE('GET /download/ @referrer', download);
};
type
ROUTE('METHOD /path/ @debug', action)
The route matches only when the application runs in debug mode.
ROUTE('METHOD /path/ @debug', action)If the request does not meet the condition, the router tries the next route with the same method and path. Each flag lowers the priority of the route by one, so a route with fewer flags is checked first.
exports.install = function() {
ROUTE('GET /dev/routes/ @debug', function($) {
$.json(F.routes.routes.map(r => r.method + ' ' + r.url2));
});
};
type
ROUTE('METHOD /path/ @release', action)
The route matches only when the application runs in release mode.
ROUTE('METHOD /path/ @release', action)If the request does not meet the condition, the router tries the next route with the same method and path. Each flag lowers the priority of the route by one, so a route with fewer flags is checked first.
exports.install = function() {
ROUTE('GET /status/ @release', status);
};
type
ROUTE('FILE /path/pattern', action)
Handles requests for static files with your code.
ROUTE('FILE /path/pattern', action)File routes are checked for URLs with an extension. Patterns: a fixed file (/robots.txt), extensions in a folder (/docs/*.md|txt), every file in a folder (/downloads/*) and an extension anywhere (*.webp). The action receives the controller; answer with $.file(), $.image(), $.plain() or $.resume() (serves the file from /public/). A request that no route takes is served from /public/ when its extension is in CONF.$httpfiles, or gets 404.
exports.install = function() {
ROUTE('FILE /robots.txt', function($) {
$.plain('User-agent: *\nDisallow: /admin/');
});
};
exports.install = function() {
ROUTE('FILE /files/*.pdf|docx', function($) {
$.file(PATH.databases($.split[1]), true);
});
};
type
ROUTE('SOCKET /path/ [flags]', action)
Declares a WebSocket endpoint.
ROUTE('SOCKET /path/ [flags]', action)WEBSOCKET is the same method. The path, +/-, {params}, #middleware and the size flag work as in HTTP routes; the default message size is CONF.$wsmaxsize kB. See WebSockets.
exports.install = function() {
ROUTE('+SOCKET /chat/{room}/ <1MB', chat);
};
type
ROUTE('#code', action)
Replaces the default error page for a status code.
ROUTE('#code', action)When the framework answers with that code (for example 404, 401, 431 or 503), it calls your action with the controller instead of rendering the built-in error page.
exports.install = function() {
ROUTE('#404', function($) {
$.response.status = 404;
$.view('404');
});
};
class
Route
The object that ROUTE() returns.
RouteIt describes a parsed route. You read its properties or call remove(); do not change them after the routes are sorted. The controller of a request has its route in $.route.
var route = ROUTE('+POST /api/orders/ @json <2MB', create);
console.log(route.method, route.auth, route.size, route.flags);
property
route.method
The HTTP method in upper case, without + or -.
route.methodReturns String
API routes have POST. FILE and SOCKET routes keep their method name.
property
route.url
The path split into lower-case segments.
route.urlReturns Array
Parameter segments keep their {name} form. The path as written (with CONF.$root) is in route.url2.
property
route.params
The dynamic parameters of the path.
route.paramsReturns Array
Each item has name and index, the position of the segment in the path.
property
route.flags
The @ flags of the route as an object.
route.flagsReturns Object
For example @json @xhr gives { json: 1, xhr: 1 }.
property
route.middleware
The names of the middleware that run before the action.
route.middlewareReturns Array
The #name flags in their order. MIDDLEWARE(name, fn, assign) can add names to existing routes.
property
route.auth
The authorization of the route.
route.authReturns Number
0 for everybody, 1 for signed-in users (+), 2 for visitors who are not signed in (-). The shared route of the API has 0; each endpoint keeps its own value.
property
route.size
The maximum body size in bytes.
route.sizeReturns Number
Set by the size flag or the size argument; otherwise CONF.$httpmaxsize * 1024 (CONF.$wsmaxsize * 1024 for SOCKET routes).
property
route.timeout
The timeout in seconds, or 0.
route.timeoutReturns Number
0 means the request uses CONF.$httptimeout.
property
route.priority
The order in which routes with the same method and path are checked.
route.priorityReturns Number
It starts at 100, each @ flag lowers it by one and a wildcard by 50. Higher values are checked first.
property
route.type
The kind of route.
route.typeReturns String
route, file or websocket.
method
route.remove()
Removes the route.
route.remove()Returns undefined
Unregisters the route and sorts the routing table again. It works for HTTP routes, API endpoints (the shared POST route of the API is removed with its last endpoint), FILE routes and SOCKET routes, whose open connections are closed.
var route = ROUTE('GET /maintenance/', function($) {
$.plain('Back soon');
});
setTimeout(function() {
route.remove();
}, 60000);
method
CORS([origins])
Sets the origins allowed for cross-origin requests.
CORS([origins])| Parameter | Type | Description |
|---|---|---|
origins? |
String |
The allowed origins, *, or +origins to add. Default: '*' |
Returns undefined
Without an argument, every origin is allowed (*). Otherwise give full origins separated by commas, ; or |. An item that starts with * allows every origin that contains the rest. A value that starts with + adds origins to the current list. Requests from the same host always pass. An allowed request gets Access-Control-Allow-Origin (the origin), -Credentials: true, -Methods, -Headers and -Expose-Headers (*), and OPTIONS is answered at once. Other origins get 400 with Invalid origin (CORS).
CORS('https://app.example.com,https://admin.example.com');
CORS('+https://partner.com');
CORS('+*example.org');
CORS();
method
PROXY(path, [target])
Forwards requests under a path to another server.
PROXY(path, [target])| Parameter | Type | Description |
|---|---|---|
path |
String |
The beginning of the request path, for example /cdn/. |
target? |
String|Function |
The target URL, a Unix socket path, or function($). |
Returns Proxy The proxy object with chainable methods, or nothing when you remove a proxy.
Proxies are checked before routes, for every method and for WebSocket upgrades. path should end with / and gets CONF.$root. target is an http:///https:// URL, a Unix socket path, or a function that receives the controller and answers itself. The forwarded request keeps the headers (without Host) and gets X-Forwarded-For, X-Forwarded-URL and X-Forwarded-Host. When the target fails, the client gets 503. PROXY(path) without a target removes the proxy for that path.
PROXY('/search/', 'http://127.0.0.1:9200').copy('replace');
PROXY('/legacy/', '/var/run/legacy.sock');
PROXY('/ping/', function($) {
$.plain('pong');
});
method
proxy.copy(type)
Sets how the request path is copied to the target.
proxy.copy(type)| Parameter | Type | Description |
|---|---|---|
type |
String |
none, replace or extend. |
Returns Proxy The proxy.
none (default): the target URL with the query string of the request. replace: the target with the part of the path after the proxy path (when the target URL has its own path, replace works like extend). extend: the target path, plus the rest of the request path, plus the query strings of the request and of the target.
// GET /cl/something/?q=1 --> https://example.com/something/?q=1
PROXY('/cl/', 'https://example.com').copy('extend');
method
proxy.before(callback)
Changes the outgoing request.
proxy.before(callback)| Parameter | Type | Description |
|---|---|---|
callback |
Function |
function(uri, $). |
Returns Proxy The proxy.
callback(uri, $) runs before the request is sent. uri holds the Node.js request options (path, headers, method...).
PROXY('/api2/', 'https://internal.example.com').before(function(uri, $) {
uri.headers['x-token'] = CONF.internal_token;
});
method
proxy.after(callback)
Reads the response of the target.
proxy.after(callback)| Parameter | Type | Description |
|---|---|---|
callback |
Function |
function(response). |
Returns Proxy The proxy.
callback(response) gets the Node.js response before it is sent to the client; you can change response.headers.
PROXY('/cdn/', 'https://cdn.example.com').after(function(response) {
delete response.headers['set-cookie'];
});
method
proxy.check(callback)
Decides for each request whether the proxy is used.
proxy.check(callback)| Parameter | Type | Description |
|---|---|---|
callback |
Function |
function($) returning a boolean. |
Returns Proxy The proxy.
callback($) returns true to forward the request. Otherwise the request goes to the routes.
PROXY('/files/', 'http://127.0.0.1:8001').check($ => $.method === 'GET');
method
proxy.timeout(ms)
Sets the timeout of the forwarded request.
proxy.timeout(ms)| Parameter | Type | Description |
|---|---|---|
ms |
Number |
The timeout in milliseconds. |
Returns Proxy The proxy.
In milliseconds. Without it (or with 0) the proxy uses CONF.$proxytimeout seconds.
PROXY('/reports/', 'http://127.0.0.1:8002').timeout(30000);
method
proxy.remove()
Removes the proxy.
proxy.remove()Returns undefined
Requests under its path go to the routes again. PROXY(path) without a target does the same.
var proxy = PROXY('/old/', 'http://127.0.0.1:8003');
proxy.remove();
config
$api : /api/
The path that ? stands for in API routes.
$api : /api/Returns String
Default /api/. When $root is set, it is added in front.
$api : /rpc/
config
$root : /app/
A path prefix for all routes.
$root : /app/Returns String
Every route, proxy and $api path is prefixed with it, for example when the app runs under /app/ behind a web server. Default empty.
$root : /admin/
config
$cors : https://app.example.com
The origins allowed for cross-origin requests.
$cors : https://app.example.comReturns String
The same value as CORS() takes: *, or origins separated by commas, with *domain items for partial matches. Default empty (cross-origin requests are not checked).
$cors : https://app.example.com, *example.org
config
$httpmaxsize : 256
The default maximum body size of HTTP routes, in kB.
$httpmaxsize : 256Returns Number
Default 256. A route overrides it with a size flag.
$httpmaxsize : 1024
config
$httptimeout : 5
The default timeout of HTTP requests, in seconds.
$httptimeout : 5Returns Number
Default 5. A route overrides it with a timeout flag.
$httptimeout : 15
config
$proxytimeout : 5
The default timeout of PROXY() requests, in seconds.
$proxytimeout : 5Returns Number
Default 5. proxy.timeout() overrides it for one proxy.
$proxytimeout : 30