Spanish Total.js
English
Documentation For AI agents
Contents

Routing

ROUTE() syntax, flags, the route object, CORS(), PROXY() and the routing configuration.

.md GitHub
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.
ParameterTypeDescription
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.

A page and a JSON endpoint
exports.install = function() {
	ROUTE('GET /', index);
	ROUTE('GET /api/time/', function($) {
		$.json({ now: new Date() });
	});
};

function index($) {
	$.view('index');
}
A view without code
exports.install = function() {
	ROUTE('GET /contact/', 'contact');
	ROUTE('GET /about/');
};
type

ROUTE('+METHOD /path/', action)

The route is only for signed-in users.

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.

An account page
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.

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.

Login or account
exports.install = function() {
	ROUTE('+GET /', 'dashboard');
	ROUTE('-GET /', 'login');
};
type

ROUTE('GET /path/{name}/', action)

A dynamic segment of the path.

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.

Two parameters
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.

A wildcard route has a lower priority than fixed and dynamic routes, so it catches only the URLs that no other route takes.

A catch-all for a section
exports.install = function() {
	ROUTE('GET /app/*', 'app');
};
type

ROUTE('[+|-]API ? endpoint[/{param}] --> Action', [action])

Declares one endpoint of the API route.

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.

Endpoints
exports.install = function() {
	ROUTE('API ? tasks_list --> Tasks/list');
	ROUTE('+API ? tasks_read/{id} --> Tasks/read');
	ROUTE('+API ? tasks_save <5MB --> Tasks/save');
};
A function instead of actions
exports.install = function() {
	ROUTE('API ? ping', function($) {
		$.success();
	});
};
Client
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.

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.

One action
exports.install = function() {
	ROUTE('GET /api/users/ --> Users/list');
};
Insert and read back
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.

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).

Uploads up to 50 MB
exports.install = function() {
	ROUTE('POST /upload/ @upload <50MB', upload);
};
type

ROUTE('METHOD /path/ <30s', action)

Sets the timeout of the request.

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.

A long export
exports.install = function() {
	ROUTE('GET /export/ <10m', exportdata);
};
type

ROUTE('METHOD /path/ #name', action)

Runs a middleware before the 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 _.

Two middleware
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).

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.

Usage
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).

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.

Usage
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.

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.

Usage
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.

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.

Usage
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.

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.

Usage
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.

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.

Usage
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.

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.

Usage
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.

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.

Usage
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.

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.

Usage
exports.install = function() {
	ROUTE('GET /status/ @release', status);
};
type

ROUTE('FILE /path/pattern', action)

Handles requests for static files with your code.

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.

Generated robots.txt
exports.install = function() {
	ROUTE('FILE /robots.txt', function($) {
		$.plain('User-agent: *\nDisallow: /admin/');
	});
};
Files from a private folder
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.

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.

Chat
exports.install = function() {
	ROUTE('+SOCKET /chat/{room}/ <1MB', chat);
};
type

ROUTE('#code', action)

Replaces the default error page for a status code.

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.

Custom 404
exports.install = function() {
	ROUTE('#404', function($) {
		$.response.status = 404;
		$.view('404');
	});
};
class

Route

The object that ROUTE() returns.

It 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.

Inspect a 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 -.

Returns String

API routes have POST. FILE and SOCKET routes keep their method name.

property

route.url

The path split into lower-case segments.

Returns 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.

Returns 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.

Returns Object

For example @json @xhr gives { json: 1, xhr: 1 }.

property

route.middleware

The names of the middleware that run before the action.

Returns 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.

Returns 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.

Returns 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.

Returns Number

0 means the request uses CONF.$httptimeout.

property

route.priority

The order in which routes with the same method and path are checked.

Returns 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.

Returns String

route, file or websocket.

method

route.remove()

Removes the route.

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.

A temporary route
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.
ParameterTypeDescription
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).

Allow two apps
CORS('https://app.example.com,https://admin.example.com');
Add one and allow subdomains
CORS('+https://partner.com');
CORS('+*example.org');
Any origin
CORS();
method

PROXY(path, [target])

Forwards requests under a path to another server.
ParameterTypeDescription
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.

Forward to a service
PROXY('/search/', 'http://127.0.0.1:9200').copy('replace');
Unix socket
PROXY('/legacy/', '/var/run/legacy.sock');
Own handler
PROXY('/ping/', function($) {
	$.plain('pong');
});
method

proxy.copy(type)

Sets how the request path is copied to the target.
ParameterTypeDescription
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.

Keep sub-paths
// 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.
ParameterTypeDescription
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...).

Add a token
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.
ParameterTypeDescription
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.

Remove a header
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.
ParameterTypeDescription
callback Function function($) returning a boolean.

Returns Proxy The proxy.

callback($) returns true to forward the request. Otherwise the request goes to the routes.

Only GET
PROXY('/files/', 'http://127.0.0.1:8001').check($ => $.method === 'GET');
method

proxy.timeout(ms)

Sets the timeout of the forwarded request.
ParameterTypeDescription
ms Number The timeout in milliseconds.

Returns Proxy The proxy.

In milliseconds. Without it (or with 0) the proxy uses CONF.$proxytimeout seconds.

30 seconds
PROXY('/reports/', 'http://127.0.0.1:8002').timeout(30000);
method

proxy.remove()

Removes the proxy.

Returns undefined

Requests under its path go to the routes again. PROXY(path) without a target does the same.

Remove
var proxy = PROXY('/old/', 'http://127.0.0.1:8003');
proxy.remove();
config

$api : /api/

The path that ? stands for in API routes.

Returns String

Default /api/. When $root is set, it is added in front.

/config
$api : /rpc/
config

$root : /app/

A path prefix for all routes.

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.

/config
$root : /admin/
config

$cors : https://app.example.com

The origins allowed for cross-origin requests.

Returns 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).

/config
$cors : https://app.example.com, *example.org
config

$httpmaxsize : 256

The default maximum body size of HTTP routes, in kB.

Returns Number

Default 256. A route overrides it with a size flag.

/config
$httpmaxsize : 1024
config

$httptimeout : 5

The default timeout of HTTP requests, in seconds.

Returns Number

Default 5. A route overrides it with a timeout flag.

/config
$httptimeout : 15
config

$proxytimeout : 5

The default timeout of PROXY() requests, in seconds.

Returns Number

Default 5. proxy.timeout() overrides it for one proxy.

/config
$proxytimeout : 30
Made in Europe