---
title: Middleware
project: Total.js V5
version: 0.0.20
section: guides
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/middleware/
updated: 2026-11-16T15:32:42.496Z
---

# Middleware

> Run named functions before routes, WebSockets and actions with NEWMIDDLEWARE().

## Creating a middleware

Register a middleware with `NEWMIDDLEWARE(name, fn)` (`MIDDLEWARE()` is the same function). The function receives the controller `$` and a `next` callback. Call `next()` to continue; answer the request instead to stop it there.

```js
// middleware/apikey.js
exports.install = function() {
	NEWMIDDLEWARE('apikey', function($, next) {
		if ($.headers['x-api-key'] === CONF.apikey)
			next();
		else
			$.invalid(401);
	});
};
```

Files in the `middleware/` folder (and in `plugins/<name>/middleware/`) are loaded at start like controllers: their `install()` function runs. You can also register a middleware from any other file.

The name is what routes use to refer to it. Use only letters, digits and `_` in the name, because the route flag accepts only these characters.

## Using a middleware in a route

Add the name with `#` to the route declaration. Several middleware run in the order you write them, and the action runs after the last one calls `next()`.

```js
exports.install = function() {
	ROUTE('GET /api/orders/ #apikey', orders);
	ROUTE('POST /api/orders/ #apikey #ratelimit', create);
	ROUTE('SOCKET /live/ #apikey', live);
};

function orders($) {
	$.json([]);
}
```

For HTTP routes, middleware runs after the body is parsed and after your `AUTH()` delegate has run, so `$.body`, `$.query`, `$.params` and `$.user` are ready. A name that is not registered is skipped; in a `SOCKET` route, the middleware after it are skipped too. The `#name` flag also works for `API` routes and for `SOCKET` routes (see [WebSockets](../../guides/websockets/)); for a socket, middleware runs before the connection is accepted.

A middleware can also prepare data for the action:

```js
NEWMIDDLEWARE('company', function($, next) {
	$.company = $.headers['x-company'] || 'default';
	next();
});
```

## Assigning a middleware to existing routes

The third argument of `NEWMIDDLEWARE()` adds the middleware to routes that already exist: `'routes'` (or `'dynamic'`) for all HTTP routes, `'websockets'` for all socket routes. Several values are separated by commas. Only routes registered before the call get it, so call it when all routes exist, for example in the `ready` event.

```js
ON('ready', function() {
	NEWMIDDLEWARE('audit', function($, next) {
		console.log($.method, $.url);
		next();
	}, 'routes');
});
```

`NEWMIDDLEWARE(name)` without a function removes the middleware: it is deleted from the registry and from every route that uses it.

## Middleware in actions

An action created with `NEWACTION()` has its own `middleware` option: a list of names separated by commas, spaces or `|`. Here the function receives the action's `$` (the options object of the action) and runs every time the action is called, from a route or from code. A missing name is reported as an error and skipped.

```js
NEWMIDDLEWARE('tenant', function($, next) {
	if ($.user && $.user.tenantid)
		next();
	else
		$.invalid(401);
});

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

See [Actions](../../guides/actions/) for the other options.
