---
title: Routing
project: jComponent V19
version: 19.194
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/jcomponent-v19/19-194/reference/routing/
updated: 2026-11-18T17:06:23.115Z
---

# Routing

> The client-side routing API: ROUTE(), REDIRECT(), MIDDLEWARE(), the NAV object, and the route options and events.

These functions map URLs to functions in a single-page application, and `NAV` holds the current state of the navigation. For an introduction with complete examples, read [Routing](../../guides/routing/).

## API

### ROUTE(url, callback, [middleware], [init])

Type: `method`

Registers a function for a URL.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | The URL of the route. It can contain dynamic segments such as `{id}` and environment variables such as `[name]`. The value of `DEF.root` is added in front of it. |
| `callback` | `Function` | yes |  | The function to run. It receives the values of the dynamic segments. |
| `middleware` | `String or Array` | no |  | A comma-separated string or an array of [middleware names](#middleware-name), [roles](#role), [code lists](#code-list) and an [options object](#options-object). The options object is accepted only in an array. |
| `init` | `Function` | no |  | A function that runs once, on the first visit, ahead of the middleware. It receives `next`, which must be called to continue. |

Returns: `Object` The `NAV` object, so calls can be chained.

The route for the current URL runs when the application starts. Inside the callback, `this` is `NAV`, and the values of the [dynamic segments](#dynamic-segment) are the arguments.

The URL is compared in lowercase, so write fixed segments in lowercase. A missing trailing slash is added to the address. A static route wins over a dynamic one with the same number of segments, and registering the same URL again replaces the route.

The arguments can also be passed in these orders:

- `ROUTE(url, middleware, callback, [init])`, with `middleware` as an array
- `ROUTE(url, callback, init, [middleware])`

When the current URL is in the 404 state, a route registered for it runs immediately.

Example: Static and dynamic routes
```js
ROUTE('/products/new/', function() {
	console.log('form');
});

ROUTE('/products/{id}/', function(id) {
	console.log('detail', id, this.url);
});

REDIRECT('/products/new/');
REDIRECT('/products/AB-15');

// Output:
// form
// detail AB-15 /products/AB-15/
```

Example: Prepare a route once
```js
ROUTE('/reports/', function() {
	console.log('reports');
}, function(next) {
	console.log('prepare once');
	next();
});

REDIRECT('/reports/');
REDIRECT('/');
REDIRECT('/reports/');

// Output:
// prepare once
// reports
// reports
```

### REDIRECT([url])

Type: `method`

Navigates to a URL without reloading the page.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | no |  | The target URL with an optional query string. It can contain environment variables such as `[name]`, and the value of `DEF.root` is added in front of it. The default value is the current URL. |

Without a URL, the current route runs again. `REDIRECT('./')` does the same, `REDIRECT('../')` goes one segment up, and `REDIRECT('../../')` goes two segments up. A query string can follow the dots, for example `REDIRECT('../?page=2')`.

A word starting with `@` at the end of the URL is a [custom flag](#custom-flag).

Example: Navigate
```js
ROUTE('/users/{id}/', function(id) {
	console.log('user', id, NAV.query.tab);
});

REDIRECT('/users/15/?tab=orders');

// Output:
// user 15 orders
```

Example: Go one level up
```js
ROUTE('/users/', function() {
	console.log('list');
});

ROUTE('/users/{id}/', function(id) {
	console.log('user', id);
});

REDIRECT('/users/15/');
REDIRECT('../');
console.log(NAV.url);

// Output:
// user 15
// list
// /users/
```

### MIDDLEWARE(name, callback)

Type: `method`

Registers a named middleware, or runs a list of middleware.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String or Array` | yes |  | The name of the middleware, or an array of names to run. |
| `callback` | `Function` | yes |  | The middleware. With an array of names, the function to call at the end. |

Returns: `Object` The `NAV` object, so calls can be chained.

A middleware runs ahead of the route callback and decides if the route continues. Inside the callback, `this` is `NAV`. The callback receives:

| Argument | Type | Description |
| --- | --- | --- |
| `next` | Function | `next()` continues. `next(false)` and `next(new Error())` stop the route. |
| `options` | Object | The [options object](#options-object) of the route. |
| `roles` | Array | The [roles](#role) of the route. |
| `route` | Object | The [route object](#route-object). |

The chain stops as well when the URL changes while a middleware is working.

With an array of names, `MIDDLEWARE(names, callback)` runs those middleware one after another and then calls `callback`. Each middleware receives only `next`, and unknown names are skipped.

Example: Protect a route
```js
var user = null;

MIDDLEWARE('auth', function(next, options, roles, route) {
	console.log('auth', route.id);
	next(user ? undefined : false);
});

ROUTE('/admin/', function() {
	console.log('admin page');
}, 'auth');

REDIRECT('/admin/');

setTimeout(function() {
	user = { name: 'Ann' };
	REDIRECT('/admin/');
}, 100);

// Output:
// auth /admin/
// auth /admin/
// admin page
```

Example: Run a list of middleware
```js
MIDDLEWARE('first', function(next) {
	console.log('first');
	next();
});

MIDDLEWARE('second', function(next) {
	console.log('second');
	next();
});

MIDDLEWARE(['first', 'second'], function() {
	console.log('done');
});

// Output:
// first
// second
// done
```

### ROUTE('/items/{name}/', callback)

Type: `config`

A dynamic segment of a route URL.

A segment in curly brackets matches any value of that segment. The values are passed to the callback in order and are available in `NAV.params`. They keep their original case. The address must have the same number of segments as the route.

Example: Read two segments
```js
ROUTE('/items/{id}/{tab}/', function(id, tab) {
	console.log(id, tab, JSON.stringify(NAV.params));
});

REDIRECT('/items/AB-1/Photos/');

// Output:
// AB-1 Photos ["AB-1","Photos"]
```

### ROUTE(url, callback, 'name')

Type: `config`

Runs a registered middleware for the route.

A plain name in the `middleware` argument of `ROUTE()` selects a middleware registered with [MIDDLEWARE()](#middleware). The middleware run in the listed order, and a name that is not registered is skipped.

Example: Two middleware
```js
MIDDLEWARE('first', function(next) {
	console.log('first');
	next();
});

MIDDLEWARE('second', function(next) {
	console.log('second');
	next();
});

ROUTE('/orders/', function() {
	console.log('orders');
}, 'first,second');

REDIRECT('/orders/');

// Output:
// first
// second
// orders
```

### ROUTE(url, callback, ['name', '@role'])

Type: `config`

Adds a role that middleware receive in the roles array.

An item starting with `@` is passed to every middleware of the route in the `roles` array, without the `@`. Roles have no effect of their own: the middleware decides what they mean.

Example: Read the roles
```js
MIDDLEWARE('auth', function(next, options, roles) {
	console.log(roles.join());
	next();
});

ROUTE('/admin/', function() {
	console.log('admin page');
}, ['auth', '@admin', '@editor']);

REDIRECT('/admin/');

// Output:
// admin,editor
// admin page
```

### ROUTE(url, callback, '#name')

Type: `config`

Loads a code list ahead of the route callback.

An item starting with `#` loads the code list with that name through `CL()`, in its position in the middleware chain. See [Global functions](../globals/).

Example: Load a code list
```js
CLINIT('countries', function(next) {
	console.log('loading countries');
	next([{ id: 'sk', name: 'Slovakia' }]);
});

ROUTE('/orders/', function() {
	console.log('orders', DEF.cl.countries.length);
}, '#countries');

REDIRECT('/orders/');

// Output:
// loading countries
// orders 1
```

### ROUTE(url, callback, ['name', { key: value }])

Type: `config`

Passes options to the middleware of the route.

An object in the middleware array is passed to every middleware of the route as `options`. It is also available in `options` of the [route object](#route-object).

Example: Read the options
```js
MIDDLEWARE('layout', function(next, options) {
	console.log(options.title);
	next();
});

ROUTE('/admin/', function() {
	console.log('admin page');
}, ['layout', { title: 'Administration' }]);

REDIRECT('/admin/');

// Output:
// Administration
// admin page
```

### REDIRECT('/url/ @name')

Type: `config`

Emits a flag event when navigating.

A word starting with `@` is removed from the URL, and the event `@flag name` is emitted ahead of the navigation. The handler receives `null`, the original URL and the type `redirect`. See [Events](../events/).

Example: React to a flag
```js
ON('@flag audit', function(path, value, type) {
	console.log(value, '|', type);
});

ROUTE('/orders/', function() {
	console.log(NAV.url);
});

REDIRECT('/orders/ @audit');

// Output:
// /orders/ @audit | redirect
// /orders/
```

### NAV.routes[index]

Type: `type`

Describes one registered route.

Middleware receive this object as the `route` argument, and `NAV.routes` contains one for each route.

| Property | Type | Description |
| --- | --- | --- |
| `id` | String | The URL of the route. |
| `url` | Array | The segments of the URL. |
| `fn` | Function | The route callback. |
| `priority` | Number | The position in the matching order. A higher number is tried first. |
| `params` | Array | The indexes of the dynamic segments. |
| `middleware` | Array | The middleware names and code lists, or `null`. |
| `init` | Function | The `init` function. It is `null` after it has run. |
| `count` | Number | How many times the route has matched. |
| `pending` | Boolean | `true` while the middleware or `init` are working. |
| `options` | Object | The [options object](#options-object). |
| `roles` | Array | The [roles](#role). |

Example: Inspect a route
```js
ROUTE('/items/{id}/', function() {}, ['auth', '@admin', { title: 'Items' }]);
MIDDLEWARE('auth', function(next) {
	next();
});

var route = NAV.routes[0];
console.log(route.id, JSON.stringify(route.url), JSON.stringify(route.params));
console.log(JSON.stringify(route.middleware), JSON.stringify(route.roles), route.options.title);

// Output:
// /items/{id}/ ["items","{id}"] [1]
// ["auth"] ["admin"] Items
```

### NAV.autosave()

Type: `method`

Saves the history to the browser storage at each navigation.

After this call, the history is stored the same way as with [NAV.save()](#nav-save) every time it changes. [NAV.load()](#nav-load) reads it back.

Example: Keep the history
```js
NAV.autosave();

REDIRECT('/a/');
REDIRECT('/b/');
REDIRECT('/c/');

NAV.history.length = 0;
NAV.load();
console.log(JSON.stringify(NAV.history));

// Output:
// ["/a/","/b/"]
```

### NAV.back()

Type: `method`

Goes to the previous URL.

Returns: `Object` The `NAV` object, so calls can be chained.

With an empty history, it goes to `/`.

Example: Go back
```js
REDIRECT('/a/');
REDIRECT('/b/');

NAV.back();
console.log(NAV.url, NAV.next());

// Output:
// /a/ /b/
```

### NAV.clientside(selector)

Type: `method`

Turns matching elements into client-side links.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `selector` | `String` | yes |  | A jQuery selector of the links. |

Returns: `Object` The `NAV` object, so calls can be chained.

A click on a matching element navigates with `REDIRECT()`. The URL is read from `href`, `data-href` or `data-url`. The values `#` and `javascript:void(0)` are ignored. Elements added later work too.

Example: Links
```html
<a class="link" href="/about/">About</a>
<span class="link" data-href="/contact/">Contact</span>

<script>
NAV.clientside('.link');

ROUTE('/about/', function() {
	console.log('about');
});

ROUTE('/contact/', function() {
	console.log('contact');
});
</script>

<!-- Output:
about
contact
-->
```

### NAV.custom([expire])

Type: `method`

Keeps the navigation inside the application.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `expire` | `String or Boolean` | no | `'1 month'` | How long the URL is kept, for example `1 day`. `true` means one month, and `false` stores nothing. |

Routes and `REDIRECT()` work as usual, and the address bar stays as it is. This suits an application embedded in another page. Call it at the start of the application.

The current URL is stored in the browser and opened again on the next visit.

Example: Navigate inside the application
```js
NAV.custom('1 day');

ROUTE('/inbox/', function() {
	console.log('inbox', NAV.url);
});

REDIRECT('/inbox/');

// Output:
// inbox /inbox/
```

### NAV.forward()

Type: `method`

Goes to the next URL after going back.

Returns: `Object` The `NAV` object, so calls can be chained.

When there is no next URL, it goes to `/`.

Example: Go forward
```js
REDIRECT('/a/');
REDIRECT('/b/');

NAV.back();
NAV.forward();
console.log(NAV.url);

// Output:
// /b/
```

### NAV.load()

Type: `method`

Restores the history from the browser storage.

It reads what [NAV.save()](#nav-save) or [NAV.autosave()](#nav-autosave) stored. The next navigation does not add the current URL to the restored history.

Example: Restore the history
```js
REDIRECT('/a/');
REDIRECT('/b/');
NAV.save();

NAV.history.length = 0;
NAV.load();
console.log(JSON.stringify(NAV.history));

// Output:
// ["/a/"]
```

### NAV.location(url, [skiphistory])

Type: `method`

Runs the route of a URL without changing the address bar.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | The URL to process. |
| `skiphistory` | `Boolean` | no | `false` | `true` does not add the current URL to the history. |

`NAV` is updated, the events are emitted and the route runs, like in `REDIRECT()`. The address in the browser is not changed.

Example: Process URLs
```js
ROUTE('/a/', function() {
	console.log('a');
});

NAV.location('/a/');
NAV.location('/b/');
NAV.location('/c/', true);

console.log(NAV.url, JSON.stringify(NAV.history));

// Output:
// a
// /c/ ["/a/"]
```

### NAV.next()

Type: `method`

Returns the URL that NAV.forward() opens.

Returns: `String` The next URL, or `undefined` when there is none.

Example: Read the next URL
```js
REDIRECT('/a/');
REDIRECT('/b/');

NAV.back();
console.log(NAV.next());

// Output:
// /b/
```

### NAV.path(url, [delimiter])

Type: `method`

Adds the trailing delimiter to a URL.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | The URL. |
| `delimiter` | `String` | no | `'/'` | The character to add. |

Returns: `String` The URL with the delimiter.

A query string is kept after the delimiter. A URL starting with `#` is returned unchanged.

Example: Normalize URLs
```js
console.log(NAV.path('/products'));
console.log(NAV.path('/products?page=2'));
console.log(NAV.path('#inbox'));

// Output:
// /products/
// /products/?page=2
// #inbox
```

### NAV.prev()

Type: `method`

Returns the URL that NAV.back() opens.

Returns: `String` The previous URL, or `undefined` when there is none.

Example: Read the previous URL
```js
REDIRECT('/a/');
REDIRECT('/b/');

console.log(NAV.prev());

// Output:
// /a/
```

### NAV.redirect([url])

Type: `method`

The same function as REDIRECT().

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | no |  | The target URL. The default value is the current URL. |

See [REDIRECT()](#redirect).

Example: Navigate
```js
ROUTE('/a/', function() {
	console.log('a');
});

NAV.redirect('/a/');

// Output:
// a
```

### NAV.refresh()

Type: `method`

Runs the route of the current URL again.

The history does not change.

Example: Run the route again
```js
ROUTE('/a/', function() {
	console.log('a');
});

REDIRECT('/a/');
NAV.refresh();
console.log(JSON.stringify(NAV.history));

// Output:
// a
// a
// []
```

### NAV.reload()

Type: `method`

The same as NAV.refresh().

See [NAV.refresh()](#nav-refresh).

Example: Run the route again
```js
ROUTE('/a/', function() {
	console.log('a');
});

REDIRECT('/a/');
NAV.reload();

// Output:
// a
// a
```

### NAV.remember(name, [value])

Type: `method`

Adds a query parameter to every following REDIRECT().

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the query parameter. |
| `value` | `String` | no |  | The value, or `null` to stop. |

Without a value, the current value of the parameter in `NAV.query` is kept. The value `null` stops adding the parameter.

Example: Keep a parameter
```js
NAV.remember('lang', 'de');
REDIRECT('/list/');
console.log(NAV.href);

NAV.remember('lang', null);
REDIRECT('/list/');
console.log(NAV.href);

// Output:
// /list/?lang=de
// /list/
```

### NAV.remove(url)

Type: `method`

Removes a route.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | The URL used in `ROUTE()`. |

Returns: `Object` The `NAV` object, so calls can be chained.

Example: Remove a route
```js
ROUTE('/a/', function() {
	console.log('a');
});

NAV.remove('/a/');
REDIRECT('/a/');
console.log(NAV.is404);

// Output:
// true
```

### NAV.save()

Type: `method`

Stores the history in the browser storage once.

The previous and next URLs are written to `localStorage` under the key `DEF.localstorage + '.nav'`.

Example: Store the history
```js
REDIRECT('/a/');
REDIRECT('/b/');
NAV.save();

var data = JSON.parse(localStorage.getItem(DEF.localstorage + '.nav'));
console.log(JSON.stringify(data.prev));

// Output:
// ["/a/"]
```

### NAV.status(code, [data])

Type: `method`

Emits an event named after a code.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `code` | `Number or String` | yes |  | The name of the event. |
| `data` | `Object` | no |  | The argument of the event. |

Returns: `Object` The `NAV` object, so calls can be chained.

This gives an application one place to handle errors.

Example: Report an error
```js
ON('500', function(error) {
	console.log('failed:', error);
});

NAV.status(500, 'Database is down');

// Output:
// failed: Database is down
```

### NAV.hashtags

Type: `property`

Drives the routes with the hash part of the URL.

Returns: `Boolean` The default value is `false`.

Set it to `true` at the start of the application. Write the routes with a leading `#`, and navigate with links or `location.hash`.

Example: Routes on the hash
```js
NAV.hashtags = true;

ROUTE('#inbox', function() {
	console.log('inbox', NAV.url);
});

setTimeout(function() {
	location.hash = '#inbox';
}, 100);

// Output:
// inbox #inbox
```

### NAV.href

Type: `property`

The URL passed to the last navigation.

Returns: `String` The URL with its query string.

Example: Read the URL
```js
REDIRECT('/search/?q=lamp');
console.log(NAV.href);

// Output:
// /search/?q=lamp
```

### NAV.history

Type: `property`

The previous URLs.

Returns: `Array` An array of strings.

The items are paths without the query string. The last item is the most recent one.

Example: List the previous URLs
```js
REDIRECT('/a/?page=2');
REDIRECT('/b/');
REDIRECT('/c/');

console.log(JSON.stringify(NAV.history));

// Output:
// ["/a/","/b/"]
```

### NAV.is404

Type: `property`

Tells if no route matches the current URL.

Returns: `Boolean` `true` when no route matches.

Example: Check the state
```js
ROUTE('/a/', function() {});

REDIRECT('/missing/');
console.log(NAV.is404);

REDIRECT('/a/');
console.log(NAV.is404);

// Output:
// true
// false
```

### NAV.isback

Type: `property`

The number of URLs to go back to.

Returns: `Number` The number of previous URLs.

It is a path, so the markup can bind to it.

Example: Count the previous URLs
```js
REDIRECT('/a/');
REDIRECT('/b/');
REDIRECT('/c/');

console.log(NAV.isback);

// Output:
// 2
```

### NAV.isforward

Type: `property`

The number of URLs to go forward to.

Returns: `Number` The number of next URLs.

It is a path, so the markup can bind to it.

Example: Count the next URLs
```js
REDIRECT('/a/');
REDIRECT('/b/');

NAV.back();
console.log(NAV.isforward);

// Output:
// 1
```

### NAV.middlewares

Type: `property`

The registered middleware.

Returns: `Object` The functions, with the middleware names as keys.

Example: List the names
```js
MIDDLEWARE('auth', function(next) {
	next();
});

console.log(Object.keys(NAV.middlewares).join());

// Output:
// auth
```

### NAV.params

Type: `property`

The values of the dynamic segments of the current route.

Returns: `Array` An array of strings.

It is a path, so the markup can bind to it.

Example: Read the values
```js
ROUTE('/items/{id}/{tab}/', function() {
	console.log(JSON.stringify(NAV.params));
});

REDIRECT('/items/15/photos/');

// Output:
// ["15","photos"]
```

### NAV.query

Type: `property`

The parsed query string of the current URL.

Returns: `Object` The parameters. All values are strings.

The names and values are decoded, and a `+` becomes a space. It is a path, so the markup can bind to it.

Example: Read the query string
```js
REDIRECT('/search/?q=desk+lamp&page=2');
console.log(JSON.stringify(NAV.query));

// Output:
// {"q":"desk lamp","page":"2"}
```

### NAV.queryraw

Type: `property`

The query string as text.

Returns: `String` The query string without the leading `?`.

Example: Read the text
```js
REDIRECT('/search/?q=lamp&page=2');
console.log(NAV.queryraw);

// Output:
// q=lamp&page=2
```

### NAV.routes

Type: `property`

The registered routes.

Returns: `Array` An array of route objects.

The array is sorted in the matching order. Each item is a [route object](#route-object).

Example: List the routes
```js
ROUTE('/items/{id}/', function() {});
ROUTE('/items/new/', function() {});

console.log(NAV.routes.map(route => route.id).join());

// Output:
// /items/new/,/items/{id}/
```

### NAV.ua

Type: `property`

Information about the browser.

Returns: `Object` The object of `MAIN.ua`.

It is the same object as `MAIN.ua` and is available when the application has started. See [MAIN](../main/).

Example: Compare with MAIN
```js
ROUTE('/', function() {
	console.log(NAV.ua === MAIN.ua);
});

// Output:
// true
```

### NAV.url

Type: `property`

The current path without the query string.

Returns: `String` The path with a trailing slash.

It is a path, so the markup can bind to it with `<ui-bind path="NAV.url" config="text"></ui-bind>`.

Example: Read the path
```js
REDIRECT('/search?q=lamp');
console.log(NAV.url);

// Output:
// /search/
```

### ON('location', function(url) {})

Type: `event`

Emitted when the URL changes, ahead of the route callback.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | The path without the query string. |

Example: Watch the navigation
```js
ON('location', function(url) {
	console.log('location', url);
});

ROUTE('/a/', function() {
	console.log('route');
});

REDIRECT('/a/?page=2');

// Output:
// location /a/
// route
```

### ON('404', function() {})

Type: `event`

Emitted when no route matches the URL.

Example: Handle an unknown URL
```js
ON('404', function() {
	console.log('not found', NAV.url);
});

REDIRECT('/missing/');

// Output:
// not found /missing/
```

### ON('route', function(url) {})

Type: `event`

Emitted when a route is registered.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | The URL of the route. |

Example: Watch the registration
```js
ON('route', function(url) {
	console.log('registered', url);
});

ROUTE('/a/', function() {});

// Output:
// registered /a/
```
