---
title: HTTP server
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/http-server/
updated: 2026-11-16T15:41:15.818Z
---

# HTTP server

> Functions for starting the server, CORS, proxies, redirects and error handling.

Functions and settings of the HTTP server that are not routes: `HTTP()`, `CORS()`, `PROXY()`, `REDIRECT()`, error pages and error helpers. The guide [HTTP server: CORS, proxy and errors](../../guides/http-server/) explains them with examples; this page is the exact reference. The sitemap has its own page: [Sitemap](../sitemap/).

## API

### HTTP(mode, [options], [middleware])

Type: `method`

Starts the HTTP server and loads the application.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `mode` | `String` | yes |  | `'debug'` or `'release'`. |
| `options` | `Object` | no |  | Start options, see [HTTP options](#http-options). |
| `middleware` | `Function` | no |  | `function(listen)`; the server listens only when you call `listen()`. Same as `options.middleware`. |

Returns: `undefined`

Loads the configuration, the sitemap and all files of the application, then listens. `mode` is `'debug'` or `'release'`. Command-line arguments are read too: a number sets the port when `options.port` is empty, and any other argument that is not a URL and does not start with `--` becomes `unixsocket`. The start script normally calls this function for you.

Example: Start on a port
```js
require('total4');

HTTP('release', { port: 8000 });
```

Example: Start later
```js
require('total4');

HTTP('release', { port: 8000 }, function(listen) {
	// prepare something, then:
	listen();
});
```

### HTTPS(mode, options, [middleware])

Type: `method`

Starts the application with an HTTPS server.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `mode` | `String` | yes |  | `'debug'` or `'release'`. |
| `options` | `Object` | yes |  | Start options with `https: { key, cert }`. |
| `middleware` | `Function` | no |  | `function(listen)`, as in `HTTP()`. |

Returns: `undefined`

Works as `HTTP()` but creates a Node.js `https` server. `options.https` is passed to `https.createServer()`: a `key` or `cert` string that contains a dot is read as a file, other strings are decoded from base64. Other TLS options of Node.js can be added to the same object.

Example: Certificates from files
```js
require('total4');

HTTPS('release', {
	port: 443,
	https: {
		key: 'keys/server.key',
		cert: 'keys/server.crt'
	}
});
```

### { port, ip, unixsocket, unixsocket777, config, https, middleware, id }

Type: `type`

The options object of `HTTP()` and `HTTPS()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `port` | `Number` | no | `CONF.default_port or 8000` | The port. |
| `ip` | `String` | no | `CONF.default_ip or '0.0.0.0'` | The IP address. |
| `unixsocket` | `String` | no |  | A Unix socket path to listen on instead of a port. |
| `unixsocket777` | `Boolean` | no | `false` | Sets the permissions of the socket file to `0777`. |
| `config` | `Object` | no |  | Values copied into `CONF` before the configuration is used. |
| `https` | `Object` | no |  | `{ key, cert }` and other TLS options for `HTTPS()`. |
| `middleware` | `Function` | no |  | `function(listen)` that starts listening. |
| `id` | `String` | no |  | The identifier of the instance, kept in `F.id`. |

The same object is passed to the start script `require('total4/release')(options)` or `require('total4/debug')(options)`, which hands it to `HTTP()`. The defaults of port and IP come from the config keys `default_port`, `default_ip` and `default_unixsocket` (see [Configuration](../../guides/configuration/)). `ip: 'auto'` listens on `0.0.0.0`.

Example: In the start script
```js
// index.js
const options = {};
options.port = 8000;
options.ip = '127.0.0.1';
options.config = { name: 'Shop' };
require('total4/release')(options);
```

### F.server

Type: `property`

The Node.js HTTP or HTTPS server of the application.

Returns: `http.Server`

Created when the server starts. You can use it to read the address or to attach listeners of Node.js.

Example: Listen to connections
```js
ON('ready', function() {
	F.server.on('connection', function(socket) {
		socket.setTimeout(60000);
	});
});
```

### F.port

Type: `property`

The port the server listens on.

Returns: `Number`

Set when the server starts, from `options.port`, the command line, `default_port` or `8000`.

Example: Print the address
```js
ON('ready', function() {
	console.log('Listening on ' + F.ip + ':' + F.port);
});
```

### F.ip

Type: `property`

The IP address the server listens on.

Returns: `String`

Set when the server starts, from `options.ip`, `default_ip` or `0.0.0.0`.

Example: Read it
```js
ON('ready', function() {
	console.log(F.ip);
});
```

### allow_performance : true

Type: `config`

Tunes sockets of the HTTP server for many connections.

Returns: `Boolean`

With `true`, each incoming socket gets `setNoDelay(true)` and keep-alive, and the global HTTP agent of Node.js can open up to 9999 sockets. Default: `false`.

Example: In the config file
```text
allow_performance : true
```

### CORS([url], [flags], [credentials])

Type: `method`

Allows cross-origin requests to a path.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | no |  | The path, for example `/api/*`, or a list of origins. |
| `flags` | `Array` | no |  | Origins, methods, max age and `credentials`. |
| `credentials` | `Boolean` | no | `false` | Sends `Access-Control-Allow-Credentials: true`. `flags` can be `true` for the same effect. |

Returns: `Object` The rule, with `remove()` to delete it.

Registers a CORS rule. The framework answers preflight `OPTIONS` requests with `200` and adds the `Access-Control-*` headers to the other requests. A `url` that ends with `*` or contains `{` covers all paths below it. In `flags`, origins are `'https://host'`, `'http://host'` or `'//host'`; HTTP methods are `'get'`, `'post'`, `'put'`, `'patch'`, `'delete'`, `'head'`, `'options'` (default: all); a number is the max age in seconds; `true` or `'credentials'` allows credentials. Without origins, the config key `default_cors` is used, and without it every origin is allowed. A request from another origin gets an empty `404`. Calling `CORS()` again with the same URL extends the existing rule.

Without arguments, every path and every origin is allowed. A first argument that starts with `http://` or `https://` is a comma-separated list of origins allowed on every path.

Example: API for one origin
```js
exports.install = function() {
	CORS('/api/*', ['https://app.example.com', 'get', 'post', 'credentials']);
};
```

Example: Everything
```js
CORS();
```

Example: Origins for the whole app
```js
CORS('https://app.example.com, https://admin.example.com');
```

Example: Remove later
```js
var rule = CORS('/public/*');
// ...
rule.remove();
```

### default_cors_maxage : 120

Type: `config`

How long browsers can cache a CORS preflight answer.

Returns: `Number`

The value of `Access-Control-Max-Age` in seconds for `CORS()` rules without their own number flag. Default: `120`.

Example: In the config file
```text
default_cors_maxage : 600
```

### PROXY(url, target, [copypath], [before], [after], [check], [timeout])

Type: `method`

Forwards requests under a path to another server.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | The path prefix, ending with `/`. |
| `target` | `String` | yes |  | The target address or Unix socket path. `null` removes the proxy. |
| `copypath` | `Boolean|String` | no |  | `true`, `false`, `'replace'` or `'extend'`. |
| `before` | `Function` | no |  | `function(uri, req, res)` called before the request is sent; change `uri.headers` or `uri.path` here. |
| `after` | `Function` | no |  | `function(response)` called with the response of the target before it is sent to the client. |
| `check` | `Function` | no |  | `function(req, res)`; return `false` to skip the proxy for this request. |
| `timeout` | `Number` | no | `10000` | Timeout in milliseconds. |

Returns: `Object` The proxy, with `remove()` to delete it.

Every request whose path starts with `url` (lower case, ending with `/`) is sent to `target` and the answer is streamed back. The target is an `http://` or `https://` address or a Unix socket path. Proxies are checked before redirects, middleware and routes, and WebSocket connections are forwarded too. The request gets the headers `X-Forwarded-For`, `X-Forwarded-Url` and `X-Forwarded-Host`. When the target fails, the client gets the error page `503`.

`copypath`: not set appends the whole request path to the path of the target; `'replace'` and `'extend'` remove the `url` prefix; `true` removes it only when the target has a path; `false` always uses only the path of the target. When `copypath` is a function, it is `before`, and the next argument is `after`. When `check` is a number, it is `timeout`. `PROXY(url, null)` removes the proxy.

Example: Forward an API
```js
exports.install = function() {
	PROXY('/api/', 'http://127.0.0.1:8001', 'replace');
};
```

Example: Add a header
```js
PROXY('/files/', 'https://files.example.com', function(uri, req, res) {
	uri.headers['x-token'] = CONF.filestoken;
});
```

Example: Unix socket
```js
PROXY('/service/', '/tmp/service.socket', 'replace');
```

### REDIRECT(from, to, [path], [permanent])

Type: `method`

Redirects a host or a URL to another address.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `from` | `String` | yes |  | A full address (`protocol://host`) or a path. |
| `to` | `String` | yes |  | The new address or path. |
| `path` | `Boolean` | no | `false` | For hosts: keep the path and query. For paths: make the redirect permanent. |
| `permanent` | `Boolean` | no | `false` | For hosts: answer `301`. |

Returns: `undefined`

With a full address in `from` (`http://example.com`), every request to that protocol and host is redirected before routing; `path` keeps the path and query, `permanent` answers `301` instead of `302`.

With a path in `from`, a `GET` route is created that redirects to `to` and keeps the query string. In this form the third argument makes the redirect permanent, and an array in the third or fourth position is passed as route flags. A path to a static file (`/docs.pdf`) creates a file route instead.

Example: Move to HTTPS and www
```js
REDIRECT('http://example.com', 'https://www.example.com', true, true);
```

Example: An old page
```js
exports.install = function() {
	REDIRECT('/old-shop/', '/shop/', true);
};
```

### res.redirect(url, [permanent])

Type: `method`

Answers a request with a redirect.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | The target address. |
| `permanent` | `Boolean` | no | `false` | Sends `301 Moved Permanently`. |

Returns: `Response` The response.

Sends `302`, or `301` when `permanent` is `true`, with the `Location` header. Useful in middleware and file handlers, where there is no controller.

Example: In a middleware
```js
MIDDLEWARE('signin', function($) {
	if ($.user)
		$.next();
	else
		$.res.redirect('/signin/');
});
```

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

Type: `method`

Declares the page for an error status.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `code` | `String` | yes |  | The status, for example `#404`. |
| `action` | `Function` | yes |  | The action that answers. |

Returns: `undefined`

A status route runs when the request ends with that status: `#400`, `#401`, `#403`, `#404`, `#408`, `#409`, `#431`, `#500`, `#501` or `#503`. The controller has the problem or error in `this.exception`; set `this.status` yourself. Without a status route, the framework answers with its built-in HTML error page, or with JSON errors when `default_errorbuilder_errors` is on or the request is XHR (`default_errorbuilder_forxhr`). A timeout answers `503`, a body over the size limit `431`.

Example: Custom 404 and 500
```js
exports.install = function() {
	ROUTE('#404', notfound);
	ROUTE('#500', servererror);
};

function notfound() {
	this.status = 404;
	this.view('404');
}

function servererror() {
	this.status = 500;
	this.plain('Something went wrong');
}
```

### default_errorbuilder_forxhr : true

Type: `config`

Answers XHR requests with JSON errors instead of the HTML error page.

Returns: `Boolean`

When a request with `X-Requested-With: XMLHttpRequest` ends with an error status and there is no status route, the answer is an `ErrorBuilder` JSON array. Default: `true`.

Example: In the config file
```text
default_errorbuilder_forxhr : false
```

### res.throw400([problem])

Type: `method`

Answers with the error status 400 Bad Request.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `problem` | `String` | no |  | A description passed to `this.exception` of the status route. |

Returns: `Response` The response.

Runs the status route `#400` or the built-in error page. For a `HEAD` request only the status is sent. It also emits the event `error400`. Use it in middleware and file handlers; in actions use `controller.throw400()`.

Example: In a middleware
```js
MIDDLEWARE('apikey', function($) {
	if ($.headers['x-api-key'] === CONF.apikey)
		$.next();
	else
		$.res.throw400('Invalid API key');
});
```

### res.throw401([problem])

Type: `method`

Answers with the error status 401 Unauthorized.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `problem` | `String` | no |  | A description passed to `this.exception` of the status route. |

Returns: `Response` The response.

Runs the status route `#401` or the built-in error page. For a `HEAD` request only the status is sent. It also emits the event `error401`. Use it in middleware and file handlers; in actions use `controller.throw401()`.

Example: In a middleware
```js
MIDDLEWARE('admin', function($) {
	if ($.user && $.user.sa)
		$.next();
	else
		$.res.throw401();
});
```

### res.throw403([problem])

Type: `method`

Answers with the error status 403 Forbidden.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `problem` | `String` | no |  | A description passed to `this.exception` of the status route. |

Returns: `Response` The response.

Runs the status route `#403` or the built-in error page. For a `HEAD` request only the status is sent. It also emits the event `error403`. Use it in middleware and file handlers; in actions use `controller.throw403()`.

Example: In a middleware
```js
MIDDLEWARE('admin', function($) {
	if ($.user && $.user.sa)
		$.next();
	else
		$.res.throw403();
});
```

### res.throw404([problem])

Type: `method`

Answers with the error status 404 Not Found.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `problem` | `String` | no |  | A description passed to `this.exception` of the status route. |

Returns: `Response` The response.

Runs the status route `#404` or the built-in error page. For a `HEAD` request only the status is sent. It also emits the event `error404`. Use it in middleware and file handlers; in actions use `controller.throw404()`.

Example: In a middleware
```js
MIDDLEWARE('apikey', function($) {
	if ($.headers['x-api-key'] === CONF.apikey)
		$.next();
	else
		$.res.throw404('Invalid API key');
});
```

### res.throw500([error])

Type: `method`

Answers with the error status 500 Internal Server Error.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `error` | `Error` | no |  | The error; it is logged with `F.error()`. |

Returns: `Response` The response.

Runs the status route `#500` or the built-in error page. For a `HEAD` request only the status is sent. It also emits the event `error500`. Use it in middleware and file handlers; in actions use `controller.throw500()`.

Example: On an error
```js
FILE('/report.pdf', function(req, res) {
	makereport(function(err, filename) {
		if (err)
			res.throw500(err);
		else
			res.file(filename);
	});
});
```

### res.throw503([error])

Type: `method`

Answers with the error status 503 Service Unavailable.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `error` | `Error` | no |  | The error; it is logged with `F.error()`. |

Returns: `Response` The response.

Runs the status route `#503` or the built-in error page. For a `HEAD` request only the status is sent. It also emits the event `error503`. Use it in middleware and file handlers; in actions use `controller.throw503()`.

Example: On an error
```js
FILE('/report.pdf', function(req, res) {
	makereport(function(err, filename) {
		if (err)
			res.throw503(err);
		else
			res.file(filename);
	});
});
```

### F.error(err, [name], [uri])

Type: `method`

Logs an error.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `err` | `Error|String` | yes |  | The error. Nothing happens when it is empty. |
| `name` | `String` | no |  | Where it happened, printed with the error. |
| `uri` | `String|Object` | no |  | The URL of the request. |

Returns: `undefined`

Calls `DEF.onError`. The default handler prints the error to the console, keeps it in `F.errors` and emits the event `error`. Without arguments it returns a callback `function(err)` that logs errors.

Example: Log an error
```js
Fs.readFile(filename, function(err, data) {
	if (err) {
		F.error(err, 'readconfig');
		return;
	}
	// ...
});
```

### ERROR([name])

Type: `method`

Returns a callback that logs its error.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | no |  | A label printed with the error. |

Returns: `Function` `function(err)`.

The callback `function(err)` calls `F.error(err, name)` when `err` is not empty. Use it where you need a callback but do not care about the result.

Example: Ignore the result, log the error
```js
F.Fs.unlink(PATH.temp('export.csv'), ERROR('unlink export'));
```

### DEF.onError = function(err, name, uri)

Type: `delegate`

The function that handles every error logged by the framework.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `err` | `Error|String` | yes |  | The error. |
| `name` | `String` | yes |  | The place where it happened. |
| `uri` | `Object|String` | yes |  | The URL of the request, when there is one. |

`F.error()`, errors in actions and `throw500()` all end here. The default prints `ERROR ======= date: name ---> error (url)` and the stack, keeps the last five errors in `F.errors` and emits `ON('error')`. Replace it to send errors elsewhere; you can call the original one from yours.

Example: Send errors to a service
```js
var onerror = DEF.onError;

DEF.onError = function(err, name, uri) {
	onerror(err, name, uri);
	RESTBuilder.POST('https://logs.example.com/', { error: err + '', name: name }).callback(NOOP);
};
```

### F.errors

Type: `property`

The last five logged errors.

Returns: `Array`

Each item is `{ error, name, url, date }`. Filled by the default `DEF.onError`.

Example: Show them
```js
exports.install = function() {
	ROUTE('GET /api/errors/', function() {
		this.json(F.errors);
	});
};
```

### SUCCESS([success], [value])

Type: `method`

Returns the `{ success, value, error }` answer object.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `success` | `Boolean|Error|ErrorBuilder|Function` | no | `true` | The result, an error, or a callback to wrap. |
| `value` | `Object` | no |  | A value for the `value` property. |

Returns: `Object` `{ success, value, error }`.

`SUCCESS()` gives `{ success: true }`. `SUCCESS(true, value)` adds `value` (a schema instance is cleaned first). An `Error` or an `ErrorBuilder` with errors gives `success: false` and the text of the error in `error`. With a function, it returns a callback `(err, value)` that calls your function with `SUCCESS(err, value)` as the second argument. The function returns one shared object, so read or send it at once and do not keep it.

Example: In an action
```js
function save() {
	var self = this;
	NOSQL('orders').insert(self.body).callback(function(err) {
		self.json(SUCCESS(err ? false : true));
	});
}
```

Example: With a value
```js
this.json(SUCCESS(true, { id: UID() }));
```

### FINISHED(stream, callback)

Type: `method`

Calls a function when a request, a response or a stream ends.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `stream` | `Stream|Request|Response` | yes |  | What to watch. |
| `callback` | `Function` | yes |  | Called once at the end. |

Returns: `undefined`

For a request or a response, the callback runs when its socket closes or fails, also when the client goes away. For other streams it runs when they end. Several callbacks can wait on one stream.

Example: Clean up after a response
```js
function report() {
	var self = this;
	var filename = PATH.temp(UID() + '.pdf');
	makepdf(filename, function() {
		FINISHED(self.res, () => F.Fs.unlink(filename, NOOP));
		self.res.file(filename, 'report.pdf');
	});
}
```

### DESTROY(stream)

Type: `method`

Destroys a stream and closes its file descriptor.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `stream` | `Stream` | yes |  | The stream. |

Returns: `Stream` The same stream.

A file read stream is destroyed and closed even if it is still opening. Other Node.js streams are destroyed with `destroy()`.

Example: Stop reading
```js
var stream = F.Fs.createReadStream(filename);
FINISHED(this.res, () => DESTROY(stream));
stream.pipe(this.res);
```

### EMPTYCONTROLLER

Type: `property`

A controller without a request.

Returns: `Controller`

The framework uses it for `VIEW()` and `MAIL()`, where there is no HTTP request. Its `req` has an empty URL, query, body and files. You can use it to call controller helpers outside a request; do not answer with it.

Example: A sitemap URL outside a request
```js
var url = EMPTYCONTROLLER.sitemap_url('detail', 'book');
```
