---
title: Routing
project: Total.js V5
version: 0.0.20
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/routing/
updated: 2026-11-18T16:57:14.575Z
---

# Routing

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

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](../../guides/routing/) explains them with examples; this page is the exact reference.

## API

### ROUTE(url, [action], [size])

Type: `method`

Declares a route.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | The method, the path and the flags, for example `+POST /api/orders/ @json <1MB`. |
| `action` | `Function|String` | no |  | 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` | no | `CONF.$httpmaxsize` | The maximum body size in bytes. It can be the second argument when there is no action. |

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

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

function index($) {
	$.view('index');
}
```

Example: A view without code
```js
exports.install = function() {
	ROUTE('GET /contact/', 'contact');
	ROUTE('GET /about/');
};
```

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

Type: `type`

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

Example: An account page
```js
exports.install = function() {
	ROUTE('+GET /account/', function($) {
		$.json($.user);
	});
};
```

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

Type: `type`

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

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

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

Type: `type`

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.

Example: Two parameters
```js
exports.install = function() {
	ROUTE('GET /blog/{year}/{slug}/', function($) {
		$.json({ year: $.params.year, slug: $.params.slug });
	});
};
```

### ROUTE('GET /path/*', action)

Type: `type`

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.

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

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

Type: `type`

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.

Example: Endpoints
```js
exports.install = function() {
	ROUTE('API ? tasks_list --> Tasks/list');
	ROUTE('+API ? tasks_read/{id} --> Tasks/read');
	ROUTE('+API ? tasks_save <5MB --> Tasks/save');
};
```

Example: A function instead of actions
```js
exports.install = function() {
	ROUTE('API ? ping', function($) {
		$.success();
	});
};
```

Example: Client
```js
AJAX('POST /api/', { schema: 'tasks_read/42', data: null }, function(err, response) {
	console.log(response);
});
```

### ROUTE('METHOD /path/ --> Action1 [Action2 (response)]')

Type: `type`

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.

Example: One action
```js
exports.install = function() {
	ROUTE('GET /api/users/ --> Users/list');
};
```

Example: Insert and read back
```js
exports.install = function() {
	ROUTE('+POST /api/users/ --> Users/insert Users/read (response)');
};
```

### ROUTE('METHOD /path/ <10MB', action)

Type: `type`

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

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

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

Type: `type`

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.

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

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

Type: `type`

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 `_`.

Example: Two middleware
```js
MIDDLEWARE('cors_api', function($, next) {
	$.response.headers['x-api'] = '1';
	next();
});

exports.install = function() {
	ROUTE('GET /api/stats/ #cors_api #nocache', stats);
};
```

### ROUTE('METHOD /path/ @json', action)

Type: `type`

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.

Example: Usage
```js
exports.install = function() {
	ROUTE('POST /api/orders/ @json', orders);
};
```

### ROUTE('METHOD /path/ @xml', action)

Type: `type`

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.

Example: Usage
```js
exports.install = function() {
	ROUTE('POST /feed/ @xml', feed);
};
```

### ROUTE('METHOD /path/ @upload', action)

Type: `type`

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.

Example: Usage
```js
exports.install = function() {
	ROUTE('POST /upload/ @upload <20MB', function($) {
		$.json($.files.map(f => f.filename));
	});
};
```

### ROUTE('METHOD /path/ @xhr', action)

Type: `type`

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.

Example: Usage
```js
exports.install = function() {
	ROUTE('GET /partials/menu/ @xhr', 'partials/menu');
};
```

### ROUTE('METHOD /path/ @mobile', action)

Type: `type`

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.

Example: Usage
```js
exports.install = function() {
	ROUTE('GET /', 'index');
	ROUTE('GET /m/ @mobile', 'mobile');
};
```

### ROUTE('METHOD /path/ @robot', action)

Type: `type`

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.

Example: Usage
```js
exports.install = function() {
	ROUTE('GET /prerender/ @robot', 'static');
};
```

### ROUTE('METHOD /path/ @referrer', action)

Type: `type`

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.

Example: Usage
```js
exports.install = function() {
	ROUTE('GET /download/ @referrer', download);
};
```

### ROUTE('METHOD /path/ @debug', action)

Type: `type`

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.

Example: Usage
```js
exports.install = function() {
	ROUTE('GET /dev/routes/ @debug', function($) {
		$.json(F.routes.routes.map(r => r.method + ' ' + r.url2));
	});
};
```

### ROUTE('METHOD /path/ @release', action)

Type: `type`

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.

Example: Usage
```js
exports.install = function() {
	ROUTE('GET /status/ @release', status);
};
```

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

Type: `type`

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

Example: Generated robots.txt
```js
exports.install = function() {
	ROUTE('FILE /robots.txt', function($) {
		$.plain('User-agent: *\nDisallow: /admin/');
	});
};
```

Example: Files from a private folder
```js
exports.install = function() {
	ROUTE('FILE /files/*.pdf|docx', function($) {
		$.file(PATH.databases($.split[1]), true);
	});
};
```

### ROUTE('SOCKET /path/ [flags]', action)

Type: `type`

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](../../guides/websockets/).

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

### ROUTE('#code', action)

Type: `type`

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.

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

### Route

Type: `class`

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

Example: Inspect a route
```js
var route = ROUTE('+POST /api/orders/ @json <2MB', create);
console.log(route.method, route.auth, route.size, route.flags);
```

### route.method

Type: `property`

The HTTP method in upper case, without `+` or `-`.

Returns: `String`

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

### route.url

Type: `property`

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

### route.params

Type: `property`

The dynamic parameters of the path.

Returns: `Array`

Each item has `name` and `index`, the position of the segment in the path.

### route.flags

Type: `property`

The `@` flags of the route as an object.

Returns: `Object`

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

### route.middleware

Type: `property`

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.

### route.auth

Type: `property`

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.

### route.size

Type: `property`

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

### route.timeout

Type: `property`

The timeout in seconds, or `0`.

Returns: `Number`

`0` means the request uses `CONF.$httptimeout`.

### route.priority

Type: `property`

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.

### route.type

Type: `property`

The kind of route.

Returns: `String`

`route`, `file` or `websocket`.

### route.remove()

Type: `method`

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.

Example: A temporary route
```js
var route = ROUTE('GET /maintenance/', function($) {
	$.plain('Back soon');
});

setTimeout(function() {
	route.remove();
}, 60000);
```

### CORS([origins])

Type: `method`

Sets the origins allowed for cross-origin requests.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `origins` | `String` | no | `'*'` | The allowed origins, `*`, or `+origins` to add. |

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

Example: Allow two apps
```js
CORS('https://app.example.com,https://admin.example.com');
```

Example: Add one and allow subdomains
```js
CORS('+https://partner.com');
CORS('+*example.org');
```

Example: Any origin
```js
CORS();
```

### PROXY(path, [target])

Type: `method`

Forwards requests under a path to another server.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes |  | The beginning of the request path, for example `/cdn/`. |
| `target` | `String|Function` | no |  | 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.

Example: Forward to a service
```js
PROXY('/search/', 'http://127.0.0.1:9200').copy('replace');
```

Example: Unix socket
```js
PROXY('/legacy/', '/var/run/legacy.sock');
```

Example: Own handler
```js
PROXY('/ping/', function($) {
	$.plain('pong');
});
```

### proxy.copy(type)

Type: `method`

Sets how the request path is copied to the target.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `type` | `String` | yes |  | `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.

Example: Keep sub-paths
```js
// GET /cl/something/?q=1 --> https://example.com/something/?q=1
PROXY('/cl/', 'https://example.com').copy('extend');
```

### proxy.before(callback)

Type: `method`

Changes the outgoing request.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | yes |  | `function(uri, $)`. |

Returns: `Proxy` The proxy.

`callback(uri, $)` runs before the request is sent. `uri` holds the Node.js request options (`path`, `headers`, `method`...).

Example: Add a token
```js
PROXY('/api2/', 'https://internal.example.com').before(function(uri, $) {
	uri.headers['x-token'] = CONF.internal_token;
});
```

### proxy.after(callback)

Type: `method`

Reads the response of the target.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | yes |  | `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`.

Example: Remove a header
```js
PROXY('/cdn/', 'https://cdn.example.com').after(function(response) {
	delete response.headers['set-cookie'];
});
```

### proxy.check(callback)

Type: `method`

Decides for each request whether the proxy is used.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | yes |  | `function($)` returning a boolean. |

Returns: `Proxy` The proxy.

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

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

### proxy.timeout(ms)

Type: `method`

Sets the timeout of the forwarded request.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `ms` | `Number` | yes |  | The timeout in milliseconds. |

Returns: `Proxy` The proxy.

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

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

### proxy.remove()

Type: `method`

Removes the proxy.

Returns: `undefined`

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

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

### $api : /api/

Type: `config`

The path that `?` stands for in API routes.

Returns: `String`

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

Example: /config
```js
$api : /rpc/
```

### $root : /app/

Type: `config`

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.

Example: /config
```js
$root : /admin/
```

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

Type: `config`

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

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

### $httpmaxsize : 256

Type: `config`

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

Returns: `Number`

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

Example: /config
```js
$httpmaxsize : 1024
```

### $httptimeout : 5

Type: `config`

The default timeout of HTTP requests, in seconds.

Returns: `Number`

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

Example: /config
```js
$httptimeout : 15
```

### $proxytimeout : 5

Type: `config`

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

Returns: `Number`

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

Example: /config
```js
$proxytimeout : 30
```
