Spanish Total.js
English
Documentation For AI agents
Contents

Routing

Declare routes with ROUTE(): methods, dynamic paths, authorization, actions, API endpoints, flags, file routes, CORS and proxies.

.md GitHub
On this page

Routes connect URLs to code. You declare them with the global ROUTE() in the install function of a file in /controllers/ (or of a plugin or a module). Each route is a single string: the HTTP method, the path and optional flags, followed by the action.

exports.install = function() {
    ROUTE('GET /', index);
    ROUTE('GET /products/{id}/', detail);
    ROUTE('POST /contact/', contact);
};

function index($) {
    $.plain('Hello world');
}

function detail($) {
    $.json({ id: $.params.id });
}

function contact($) {
    // $.body contains the parsed JSON or form data
    $.success();
}

The action receives the controller $. Its properties and methods ($.params, $.body, $.query, $.json(), $.view()...) are described in Controller.

Methods and paths

The first word is the method: GET, POST, PUT, PATCH, DELETE or any other method name. The path is compared in lower case and the trailing slash does not matter. When CONF.$root is set (for example /admin/), it is prepended to every path.

The action can be:

  • a function, called with the controller;
  • a string, the name of a view that is rendered;
  • missing, then a view named after the first segment of the path is rendered (index for /).
exports.install = function() {
    ROUTE('GET /', 'index');      // views/index.html
    ROUTE('GET /about/');         // views/about.html
    ROUTE('GET /pricing/', 'cms/pricing');
};

Dynamic parameters and wildcards

A segment in curly braces is a parameter. Its value is in $.params as a string, with the case of the request URL. A route with parameters matches only URLs with the same number of segments.

exports.install = function() {
    ROUTE('GET /users/{id}/orders/{order}/', function($) {
        $.json({ user: $.params.id, order: $.params.order });
    });
    ROUTE('GET /docs/*', function($) {
        // /docs/, /docs/a/, /docs/a/b/c/ ...
        $.plain($.url);
    });
};

A * at the end makes a wildcard route: it matches the path and everything below it. Fixed routes are checked first, then routes with parameters, then wildcards.

Authorization: + and -

Prefix the method with + for routes that need a signed-in user, or with - for routes only for visitors who are not signed in. The AUTH() delegate decides who is signed in; when the user does not fit any route of the URL, the answer is 401. Without AUTH() the prefixes are not checked and every route serves everybody. A route without a prefix serves everybody.

exports.install = function() {
    ROUTE('+GET /account/', 'account');
    ROUTE('-GET /account/', 'login');
    ROUTE('+POST /account/password/', password);
};

You can declare the same URL twice, once with + and once with -, as above.

Actions with -->

Instead of a function, a route can call actions declared with NEWACTION(). Write their names after -->. The request body is the payload and the result is sent back as the response (an error is sent with $.invalid()).

exports.install = function() {
    ROUTE('GET /api/products/ --> Products/list');
    ROUTE('+POST /api/products/ --> Products/insert');
    ROUTE('+PUT /api/products/{id}/ --> Products/update');
    ROUTE('+POST /api/orders/ --> Orders/insert Orders/read (response)');
};

With several actions, (response) marks the action whose result is the response.

API routes with ?

API routes put many operations behind one URL. A ? in the path is replaced with CONF.$api (default /api/). The client sends POST with a JSON body { "schema": "name/param?query", "data": {...} }; the framework finds the endpoint name, fills $.params from the path parts, $.query from the part after ?, and uses data as the body.

exports.install = function() {
    ROUTE('API ? products_list --> Products/list');
    ROUTE('API ? products_read/{id} --> Products/read');
    ROUTE('+API ? products_save --> Products/save');
    ROUTE('+API ? products_remove/{id} --> Products/remove');
};
// client
AJAX('POST /api/', { schema: 'products_read/123', data: null }, console.log);

+API and -API set the authorization of each endpoint separately. A missing parameter is answered with an error for params.<name>, and an unknown endpoint or a body without schema with 400.

Flags

Flags follow the path. @flag limits when the route matches, #name runs a middleware, <value sets a body size limit or a timeout.

exports.install = function() {
    ROUTE('POST /upload/ @upload <20MB', upload);
    ROUTE('POST /api/import/ @json <2m', importdata);
    ROUTE('GET /dashboard/ @xhr #nocache', dashboard);
};
FlagThe route matches only when
@jsonThe body is JSON
@xmlThe body is XML
@uploadThe body is multipart/form-data
@xhrThe request has X-Requested-With: XMLHttpRequest
@mobileThe client is a mobile device
@robotThe client is a crawler
@referrer (or @referer)The Referer header contains the host of the request
@debugThe application runs in debug mode
@releaseThe application runs in release mode

When two routes have the same method and path, the one with fewer flags is checked first. Size limits and timeouts:

FlagMeaning
<500bBody size limit in bytes
<512kBBody size limit in kilobytes (1 kB = 1024 bytes)
<10MBBody size limit in megabytes
<2GBBody size limit in gigabytes
<30sTimeout in seconds
<5mTimeout in minutes
<1hTimeout in hours

Without a size flag, the limit is CONF.$httpmaxsize (256 kB); a larger body is answered with 431. Without a timeout flag, the request has CONF.$httptimeout (5 seconds) and then ends with 503. The timeout is checked every 5 seconds. The third argument of ROUTE() also sets the limit, in bytes: ROUTE('POST /import/', fn, 1024 * 1024 * 50).

Middleware

#name runs the middleware registered with MIDDLEWARE(name, fn) before the action, in the order written. See Middleware.

MIDDLEWARE('nocache', function($, next) {
    $.response.headers['cache-control'] = 'no-store';
    next();
});

exports.install = function() {
    ROUTE('GET /report/ #nocache', report);
};

File routes

The FILE method handles requests for static files (URLs with an extension) with your own code.

exports.install = function() {
    ROUTE('FILE /robots.txt', robots);          // one file
    ROUTE('FILE /docs/*.md|txt', docs);          // extensions inside /docs/
    ROUTE('FILE /downloads/*', downloads);       // every file inside /downloads/
    ROUTE('FILE *.webp', webp);                  // every .webp file
};

function robots($) {
    $.plain('User-agent: *');
}

function downloads($) {
    $.file(PATH.databases('files' + $.url.substring(10)), true);
}

WebSocket routes

SOCKET (or WEBSOCKET) declares a WebSocket endpoint with the same path syntax, +/- and size flags. See WebSockets.

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

Error routes

A route named # plus a status code replaces the default error page for that code.

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

Removing a route

ROUTE() returns the route object. Call remove() on it to unregister the route while the application runs; the routing table is sorted again at once. It works for every kind of route: an HTTP route, one API endpoint (the shared POST route of the API disappears with its last endpoint), a FILE route and a SOCKET route (its open connections are closed).

var route = ROUTE('GET /promo/', function($) {
    $.plain('Promo is running');
});

var endpoint = ROUTE('API ? promo_read --> Promo/read');

// later
route.remove();
endpoint.remove();

CORS

Requests with an Origin header from another host are checked against CONF.$cors. Set it with CORS() or in /config.

CORS();                                         // any origin
CORS('https://app.example.com,https://admin.example.com');
CORS('+https://partner.example.com');           // add one more
CORS('*example.com');                           // any origin that contains example.com

An allowed request gets Access-Control-Allow-* headers and a preflight OPTIONS request is answered at once. A refused origin gets 400 with Invalid origin (CORS).

Proxies

PROXY(path, target) forwards every request whose path starts with path to another server, before the routes are searched. The target is an http:// or https:// URL, a Unix socket path, or a function that receives the controller.

PROXY('/cdn/', 'https://cdn.example.com').copy('extend').timeout(10000);
PROXY('/legacy/', '/var/run/legacy.sock');

The forwarded request gets X-Forwarded-For, X-Forwarded-URL and X-Forwarded-Host. When the target fails, the client gets 503.

Made in Europe