---
title: Middleware
project: Total.js V4
version: 0.0.99
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v4/0-0-99/reference/middleware/
updated: 2026-11-18T16:57:34.578Z
---

# Middleware

> MIDDLEWARE(), USE(), MiddlewareOptions and the $ object of a middleware.

## API

### MIDDLEWARE(name, fn, [types], [first])

Type: `method`

Registers, replaces or removes a named middleware.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name used in route flags (`#name`) and in `USE()`. |
| `fn` | `Function($)` | yes |  | The middleware, or `null` to remove it. |
| `types` | `String|String[]` | yes |  | Assigns the middleware globally to these request types. |
| `first` | `Boolean` | yes |  | With `types`, puts the middleware before the others. |

`fn` receives one argument, `$` (`MiddlewareOptions`). It must call `$.next()`, call `$.cancel()`, or respond with `$.res`; otherwise the request waits until its timeout. A middleware that is not registered but assigned to a route is skipped and logged as `Middleware not found`.

With `types`, the middleware is also assigned globally by calling `USE(name, '', types, first)`. Use a type name or an array: `web`, `file`, `websocket`, `all`.

`fn = null` removes the middleware and removes its name from all routes and global lists. `NEWMIDDLEWARE()` is the same function. Middleware registered by a plugin or another owner is removed when that owner is unloaded.

Example: Check an API key
```js
MIDDLEWARE('apikey', function($) {
	if ($.headers['x-api-key'] === CONF.apikey)
		$.next();
	else
		$.res.throw401();
});

exports.install = function() {
	ROUTE('GET /api/products/', products, ['#apikey']);
};
```

Example: Register and assign to all static files
```js
MIDDLEWARE('cors', function($) {
	$.res.setHeader('Access-Control-Allow-Origin', '*');
	$.next();
}, ['file']);
```

Example: Remove
```js
MIDDLEWARE('apikey', null);
```

### USE(name, [url], [types], [first])

Type: `method`

Assigns middleware to all requests, to one type of request, or to routes under a URL.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String|String[]|Function` | yes |  | Middleware name(s), or a function. |
| `url` | `String|String[]` | yes |  | A URL prefix. An array here is taken as `types`. |
| `types` | `String|String[]` | yes |  | Request types: `web`, `file`, `websocket`, `all`. |
| `first` | `Boolean` | yes |  | Puts the middleware before the middleware already assigned. |

`USE()` runs after the application is loaded, so it sees the routes from all controllers.

- Without `url` and `types`, or with the type `all` or `*`, the middleware runs for every request, static files included, before the routing. `$.controller` is not set there.
- With `types` only, it runs for every request of those types. `web` (also `route`, `routes`, `dynamic`, `http`, `https`, `api`, `schema`, `schemas`) means dynamic routes; `file` (also `files`, `static`) means static files and file routes; `websocket` (also `socket`, `sockets`, `websockets`, `ws`, `wss`) means WebSocket routes.
- With `url` and `types`, it is added to each existing route of those types whose URL starts with `url`. A `url` of `*` means no URL.

`name` can be a string with several names separated by commas or spaces (a leading `#` or `&` is ignored), an array of names, or a function, which is registered as a middleware with a generated name. A name that is already in a list is not added twice.

Example: Every request
```js
USE('poweredby');
```

Example: Only dynamic routes under /api/
```js
USE('apikey', '/api/', ['web']);
```

Example: An anonymous middleware for WebSocket routes
```js
USE(function($) {
	console.log('WebSocket', $.url);
	$.next();
}, ['websocket']);
```

### $

Type: `class`

The argument of every middleware function.

A new instance is created for each chain of middleware of a request. Besides the methods below, it has these read-only shortcuts:

| Property | Value |
| --- | --- |
| `$.req`, `$.res` | The request and the response (for WebSocket routes, `$.res` is the WebSocket client) |
| `$.user`, `$.session`, `$.sessionid` | The user and session set by authorization |
| `$.headers`, `$.ip`, `$.ua`, `$.language` | Request data |
| `$.url`, `$.path`, `$.split` | The URL and its parts |
| `$.query`, `$.body`, `$.files` | Query string, parsed body and uploaded files |
| `$.params`, `$.id` | Route parameters and the controller ID (only when `$.controller` exists) |
| `$.controller` | The controller, in middleware of dynamic routes |
| `$.options` | The options object of the route |
| `$.middleware` | The list of names in the current chain |

Example: Read request data
```js
MIDDLEWARE('logger', function($) {
	console.log($.ip, $.url, $.ua);
	$.next();
});
```

### $.next([err])

Type: `method`

Continues with the next middleware, or with the action when this was the last one.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `err` | `Boolean|Error|ErrorBuilder` | yes |  | `false` to stop, or an error to respond with 500. |

- No argument: continue.
- `false`: stop the chain; the action is not run.
- An `Error` or an `ErrorBuilder`: respond with an error 500 and stop.

If the response was already sent, the chain stops by itself.

Example: Stop with an error
```js
MIDDLEWARE('maintenance', function($) {
	if (CONF.maintenance)
		$.next(new Error('Maintenance'));
	else
		$.next();
});
```

### $.cancel()

Type: `method`

Stops the chain of middleware without running the action.

Returns: `MiddlewareOptions`

The same as `$.next(false)`. Use it after you have sent a response yourself. Returns `$`.

Example: Answer and stop
```js
MIDDLEWARE('ping', function($) {
	if ($.url === '/ping/') {
		$.res.send(200, 'pong', 'text/plain');
		$.cancel();
	} else
		$.next();
});
```

### $.callback()

Type: `method`

Continues the chain; the same as `$.next()` without an argument.

Returns: `MiddlewareOptions`

Returns `$`.

Example: Continue
```js
MIDDLEWARE('log', function($) {
	console.log($.url);
	$.callback();
});
```

### $.options

Type: `property`

The options object from the flags of the route.

Returns: `Object`

An object in the flags array of `ROUTE()` or a file route becomes `$.options` in all middleware of that route. For global middleware it is an empty object.

Example: One middleware, different settings
```js
MIDDLEWARE('role', function($) {
	if ($.user && $.user.roles.includes($.options.role))
		$.next();
	else
		$.res.throw403();
});

exports.install = function() {
	ROUTE('GET /admin/', admin, ['#role', { role: 'admin' }]);
	ROUTE('GET /editor/', editor, ['#role', { role: 'editor' }]);
};
```

### $.controller

Type: `property`

The controller of the request, in middleware of dynamic routes.

Returns: `Controller`

It is set for middleware of a route and for middleware assigned with `USE(name, ...['web'])`. In global middleware of all requests, static files and file routes it is `undefined`. `$.params` and `$.id` read from it.

Example: Use the controller
```js
MIDDLEWARE('product', function($) {
	if ($.params.id)
		$.next();
	else
		$.controller.throw404();
});
```

### PATH.middleware([filename])

Type: `method`

Returns the absolute path to a file in the middleware directory.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | yes |  | A file name. |

Returns: `String` An absolute path.

The directory is set by `directory_middleware`.

Example: Path
```js
PATH.middleware('auth.js');
```

### directory_middleware

Type: `config`

The directory with middleware files. Default `/middleware/`.

Returns: `String` '/middleware/'

Each `.js` file is loaded at startup and its `exports.install()` is called. Register the middleware there with `MIDDLEWARE()`.

Example: A middleware file
```js
// /middleware/auth.js
exports.install = function() {
	MIDDLEWARE('auth', function($) {
		if ($.user)
			$.next();
		else
			$.res.throw401();
	});
};
```
