---
title: Middleware
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/middleware/
updated: 2026-11-18T16:57:14.575Z
---

# Middleware

> NEWMIDDLEWARE(), the middleware handler, the #name route flag and the middleware option of actions.

## API

### NEWMIDDLEWARE(name, fn, [assign])

Type: `method`

Registers a named middleware, or removes it.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Name of the middleware, used as `#name` in routes. Letters, digits and `_`. |
| `fn` | `Function` | no |  | `function($, next)`. Without it, the middleware is removed. |
| `assign` | `String|Array` | no |  | `routes`, `dynamic` or `websockets`, separated by commas. |

Returns: `undefined`

The function runs as `fn($, next)` for every route that lists the name. For HTTP and socket routes `$` is the controller; for actions it is the action's `$`. Call `next()` to continue, or answer the request to stop it.

`assign` adds the middleware to routes that already exist: `'routes'` or `'dynamic'` for HTTP routes, `'websockets'` for socket routes, several values separated by commas or as an array. Routes registered later do not get it.

Called with only `name`, it removes the middleware from the registry and from every route.

Example: API key check
```js
NEWMIDDLEWARE('apikey', function($, next) {
	if ($.headers['x-api-key'] === CONF.apikey)
		next();
	else
		$.invalid(401);
});

ROUTE('GET /api/orders/ #apikey', function($) {
	$.json([]);
});
```

Example: Remove a middleware
```js
NEWMIDDLEWARE('apikey');
```

### MIDDLEWARE(name, fn, [assign])

Type: `method`

The same function as `NEWMIDDLEWARE()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Name of the middleware. |
| `fn` | `Function` | no |  | `function($, next)`. Without it, the middleware is removed. |
| `assign` | `String|Array` | no |  | `routes`, `dynamic` or `websockets`. |

Returns: `undefined`

`MIDDLEWARE` and `NEWMIDDLEWARE` are two names for one function; the arguments and the behaviour are the same.

Example: Register
```js
MIDDLEWARE('timing', function($, next) {
	$.started = Date.now();
	next();
});
```

### function($, next)

Type: `delegate`

The function of a middleware.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `$` | `Controller|Options` | yes |  | The controller of the request, or the action's `$`. |
| `next` | `Function` | yes |  | Continues with the next middleware or the action. |

It receives the controller (or, inside an action, the action's `$`) and the `next` callback. Calling `next()` runs the next middleware of the route, and after the last one the action. Not calling `next()` stops the chain; then the middleware must answer the request itself, for example with `$.invalid(401)`, `$.redirect(url)` or `$.json(data)`.

For HTTP routes, the body, the query, the URL parameters and `$.user` are already set when the middleware runs.

Example: Redirect anonymous users
```js
NEWMIDDLEWARE('login', function($, next) {
	if ($.user)
		next();
	else
		$.redirect('/login/');
});
```

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

Type: `property`

Lists a middleware in a route declaration.

Each `#name` in the route string adds that middleware to the route; they run in the written order. The flag works for HTTP routes, `API` routes and `SOCKET` routes. The name may contain letters, digits and `_`. A name that is not registered is skipped; in a `SOCKET` route, the middleware after it are skipped too.

Example: Two middleware
```js
ROUTE('POST /api/upload/ #apikey #ratelimit', upload);
ROUTE('SOCKET /live/ #apikey', live);
```

### NEWACTION({ middleware: 'name1, name2' })

Type: `property`

Middleware that runs before an action.

The `middleware` option of `NEWACTION()` is a list of middleware names separated by commas, spaces or `|`. They run with the action's `$` every time the action is called, before the `action` function. A name that is not registered is reported with `Total.error()` and skipped.

Example: Action with middleware
```js
NEWACTION({
	name: 'Orders/list',
	middleware: 'tenant',
	action: function($) {
		$.callback([]);
	}
});
```

### middleware/*.js

Type: `type`

Folder with files that register middleware.

`.js` files in `middleware/` and in `plugins/<name>/middleware/` are loaded at start; their `install()` function runs. Use it to keep middleware apart from controllers.

Example: middleware/auth.js
```js
exports.install = function() {
	NEWMIDDLEWARE('admin', function($, next) {
		if ($.user && $.user.sa)
			next();
		else
			$.invalid(401);
	});
};
```
