---
title: Controller
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/controller/
updated: 2026-11-16T15:41:00.817Z
---

# Controller

> Properties and methods of the controller, the object that answers a request.

The controller is `this` inside every action of a route. It holds the request data and the methods that answer the request. The guide [Controllers](../../guides/controllers/) explains how to use it with examples; this page is the exact reference.

## API

### controller.body

Type: `property`

The parsed body of the request.

Returns: `Object`

A JSON or URL-encoded body is parsed into an object. Values of a form are strings. A route with a schema replaces it with the validated model. You can also assign a new object.

Example: Read the body
```js
exports.install = function() {
	ROUTE('POST /api/contact/', contact);
};

function contact() {
	var email = this.body.email;
	this.success();
}
```

### controller.query

Type: `property`

The query string of the URL as an object.

Returns: `Object`

Values are strings: `?page=2` gives `{ page: '2' }`. The object is parsed the first time you read it.

Example: Paging
```js
function list() {
	var page = (this.query.page || '1').parseInt();
	this.json({ page: page });
}
```

### controller.params

Type: `property`

The dynamic parameters of the URL.

Returns: `Object`

Each `{name}` of the route becomes a key. Parameters declared with a type are converted: `{id:number}` with `parseInt()`, `{active:boolean}` with `parseBoolean()` and `{date:date}` with `parseDate()`. The same values arrive as arguments of the action.

Example: Typed parameter
```js
exports.install = function() {
	ROUTE('GET /orders/{id:number}/', order);
};

function order(id) {
	// this.params.id is a number
	this.json({ id: this.params.id });
}
```

### controller.files

Type: `property`

The uploaded files.

Returns: `Array`

Only routes with the `upload` flag receive files. Each file has `name` (the form field), `filename`, `type`, `size`, `extension`, `width` and `height`, and the methods `move(path)`, `copy(path)`, `read()`, `isImage()`, `isVideo()` and `isAudio()`. `move()`, `copy()` and `read()` return a promise without a callback. The temporary files are removed when the request ends, unless you call `controller.autoclear(false)`.

Example: Save an upload
```js
exports.install = function() {
	ROUTE('POST /upload/', upload, ['upload'], 1024 * 5);
};

async function upload() {
	var file = this.files[0];
	await file.move(PATH.public('uploads/' + file.filename));
	this.success();
}
```

### controller.user

Type: `property`

The signed-in user.

Returns: `Object`

The object that your `AUTH()` delegate passed to `$.success(user)`. It is `undefined` when nobody is signed in. You can assign it.

Example: Profile
```js
exports.install = function() {
	ROUTE('+GET /api/profile/', profile);
};

function profile() {
	this.json({ name: this.user.name });
}
```

### controller.headers

Type: `property`

The headers of the request.

Returns: `Object`

Header names are in lower case.

Example: Read a header
```js
function api() {
	var token = this.headers['x-token'];
	this.plain(token ? 'ok' : 'missing');
}
```

### controller.ip

Type: `property`

The IP address of the client.

Returns: `String`

Behind a proxy it is the first address of the `X-Forwarded-For` header; otherwise the address of the connection.

### controller.url

Type: `property`

The path of the request URL in lower case.

Returns: `String`

It has no query string and always ends with `/`.

### controller.mobile

Type: `property`

`true` when the client is a mobile device.

Returns: `Boolean`

It is tested on the `User-Agent` header. You can assign it.

### controller.xhr

Type: `property`

`true` when the request was sent by XMLHttpRequest.

Returns: `Boolean`

It is `true` when the request has the header `X-Requested-With: XMLHttpRequest`.

### controller.language

Type: `property`

The language of the request.

Returns: `String`

It is the value returned by your localization delegate (`DEF.onLocale`). Views and `controller.mail()` translate texts with it.

### controller.status

Type: `property`

The HTTP status code of the answer.

Returns: `Number`

Set it before you answer. `json()`, `jsonstring()`, `plain()`, `content()` and `html()` use it, and `200` when it is not set. `invalid()` uses a status over `399` for the errors.

Example: Created
```js
function create() {
	this.status = 201;
	this.json({ id: UID() });
}
```

### controller.repository

Type: `property`

An object shared by the view and its layout.

Returns: `Object`

Values you store here before `view()` are available in the view and in the layout as `repository`. The page title and meta tags are stored in it too.

Example: Pass a value to the layout
```js
function home() {
	this.repository.menu = 'home';
	this.view('index');
}
```

### controller.exception

Type: `property`

The problem of an error route.

Returns: `Error|String`

In a route for an error status (`ROUTE('#404', ...)`, `ROUTE('#500', ...)`) it contains the problem passed to `throw404()`, `throw500()` and the others.

### controller.req

Type: `property`

The request object of the framework.

Returns: `Request`

It extends the Node.js request. The properties of the controller like `body`, `query` and `ip` read from it.

### controller.json(obj, [headers], [beautify], [replacer])

Type: `method`

Answers with an object serialized as JSON.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `obj` | `Object` | yes |  | The value to serialize. |
| `headers` | `Object` | no |  | Extra response headers. |
| `beautify` | `Boolean` | no | `false` | Formats the JSON with indentation. |
| `replacer` | `Function` | no |  | A replacer for `JSON.stringify()`. |

Returns: `Controller` The controller.

The content type is `application/json` and the status is `controller.status` or `200`. An `ErrorBuilder` is answered as its errors with its own status. `beautify` can be the second argument.

Example: An object
```js
exports.install = function() {
	ROUTE('GET /api/products/', products);
};

function products() {
	this.json([{ id: 1, name: 'Book' }]);
}
```

Example: Formatted
```js
this.json({ name: 'Peter' }, true);
```

### controller.jsonstring(str, [headers])

Type: `method` · Since: `0.0.57`

Answers with a text that is already JSON.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `str` | `String` | yes |  | The JSON text. |
| `headers` | `Object` | no |  | Extra response headers. |

Returns: `Controller` The controller.

Use it when you have the JSON as a string, for example from a cache. The text is sent as it is, with the content type `application/json`.

Example: From a cache
```js
function list() {
	this.jsonstring('[{"id":1}]');
}
```

### controller.plain(body, [headers])

Type: `method`

Answers with plain text.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `body` | `String|Object` | yes |  | The text. |
| `headers` | `Object` | no |  | Extra response headers. |

Returns: `Controller` The controller.

The content type is `text/plain`. An object is serialized as formatted JSON; `null` gives an empty body.

Example: Text
```js
function home() {
	this.plain('Hello world');
}
```

### controller.html(body, [headers])

Type: `method`

Answers with HTML.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `body` | `String` | yes |  | The HTML. |
| `headers` | `Object` | no |  | Extra response headers. |

Returns: `Controller` The controller.

The same as `content(body, 'text/html', headers)`.

Example: HTML
```js
function home() {
	this.html('<h1>Hello</h1>');
}
```

### controller.content(body, type, [headers])

Type: `method`

Answers with a text and your content type.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `body` | `String` | yes |  | The content. |
| `type` | `String` | no | `text/plain` | The content type. |
| `headers` | `Object` | no |  | Extra response headers. |

Returns: `Controller` The controller.

An `ErrorBuilder` as `body` is answered as JSON with its own status.

Example: XML
```js
function feed() {
	this.content('<rss></rss>', 'application/xml');
}
```

### controller.view([name], [model], [headers], [partial])

Type: `method`

Renders a view and answers with it.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | no |  | The name of the view without `.html`. |
| `model` | `Object` | no |  | The model, available in the view as `model`. |
| `headers` | `Object` | no |  | Extra response headers. |
| `partial` | `Boolean` | no | `false` | Returns the HTML as a string and does not answer. It can be the third argument. |

Returns: `Controller|String` The controller, or the HTML when `partial` is `true`.

The view is a file `name.html` in `views/`, rendered inside the layout (`layout` by default, see `controller.layout()`). Routes of a controller other than `default` look for views in `views/<controller name>/`. The first character of the name changes where the file is looked up:

| Prefix | Where |
| --- | --- |
| `~` | The root of `views/` |
| `#plugin/view` | The views of a plugin |
| `=theme/view` | The views of a theme |
| `@` | A package |

Without a name, the view is named after the last part of the URL (`index` for `/`). With `partial` set to `true` the method returns the rendered HTML instead of answering.

Example: A page
```js
exports.install = function() {
	ROUTE('GET /', home);
};

function home() {
	this.view('index', { title: 'Home' });
}
```

Example: HTML as a string
```js
var html = this.view('~mail/order', order, true);
```

### controller.layout(name)

Type: `method`

Chooses the layout for the next view.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the layout view, or an empty string. |

Returns: `Controller` The controller.

The default layout is `layout` (the `default_layout` config). An empty string renders the view without a layout.

Example: Without a layout
```js
function widget() {
	this.layout('');
	this.view('widget');
}
```

### controller.title(value)

Type: `method`

Sets the title of the page.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String` | yes |  | The title. |

Returns: `Controller` The controller.

The layout prints it with `@{title}`. The text is HTML-encoded.

Example: Title
```js
this.title('Products');
this.view('products');
```

### controller.meta(title, [description], [keywords], [image])

Type: `method`

Sets the meta values of the page.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `title` | `String` | yes |  | The title. |
| `description` | `String` | no |  | The description. |
| `keywords` | `String|Array` | no |  | The keywords. |
| `image` | `String` | no |  | The URL of an image. |

Returns: `Controller` The controller.

The layout prints them with `@{meta}`. `keywords` can be an array.

Example: Meta tags
```js
this.meta('Products', 'All our products', ['shop', 'books']);
this.view('products');
```

### controller.file(filename, [download], [headers], [callback])

Type: `method`

Answers with a file.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | yes |  | The file in `public/`, or `~` and an absolute path. |
| `download` | `String|Boolean` | no |  | A name for the downloaded file; `true` uses the name of the file. |
| `headers` | `Object` | no |  | Extra response headers. |
| `callback` | `Function` | no |  | Runs when the file is sent. |

Returns: `Controller` The controller.

The file is read from `public/`. A name that starts with `~` is an absolute path.

Example: Download
```js
function invoice() {
	this.file('~' + PATH.private('invoices/1.pdf'), 'invoice.pdf');
}
```

### controller.binary(buffer, type, [encoding], [download], [headers])

Type: `method`

Answers with a buffer.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `buffer` | `Buffer` | yes |  | The data. |
| `type` | `String` | yes |  | The content type. |
| `encoding` | `String` | no |  | A conversion of the data. |
| `download` | `String` | no |  | A name for the downloaded file. |
| `headers` | `Object` | no |  | Extra response headers. |

Returns: `Controller` The controller.

`encoding` converts the buffer before it is sent (`binary`, `utf8`, `ascii`).

Example: An image in memory
```js
function pixel() {
	var buffer = Buffer.from('R0lGODlhAQABAAAAACw=', 'base64');
	this.binary(buffer, 'image/gif');
}
```

### controller.stream(stream, type, [download], [headers], [callback], [nocompress])

Type: `method`

Answers with a readable stream.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `stream` | `Stream` | yes |  | A readable stream. |
| `type` | `String` | yes |  | The content type. |
| `download` | `String` | no |  | A name for the downloaded file. |
| `headers` | `Object` | no |  | Extra response headers. |
| `callback` | `Function` | no |  | Runs when the stream is sent. |
| `nocompress` | `Boolean` | no | `false` | Disables the compression. |

Returns: `Controller` The controller.

The answer is compressed unless `nocompress` is `true`. The first two arguments can be swapped (`type`, `stream`).

Example: A CSV file
```js
function exportcsv() {
	var stream = Fs.createReadStream(PATH.databases('export.csv'));
	this.stream(stream, 'text/csv', 'export.csv');
}
```

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

Type: `method`

Redirects the client to another URL.

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

Returns: `Controller` The controller.

The status is `302`, or `301` when `permanent` is `true`.

Example: After a form
```js
function save() {
	this.redirect('/thanks/');
}
```

### controller.empty([headers])

Type: `method`

Answers with an empty body.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `headers` | `Object|Number` | no |  | Extra headers, or a status code. |

Returns: `Controller` The controller.

A number instead of the headers sets the status code. For `204 No Content` use also `controller.nocontent([headers])`.

Example: Accepted
```js
this.empty(202);
```

### controller.success([success], [value])

Type: `method`

Answers with the JSON `{ "success": true }`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `success` | `Boolean` | no | `true` | The value of `success`. |
| `value` | `Object` | no |  | A value added as `value`. |

Returns: `Controller` The controller.

`success(value)` answers `{ "success": true, "value": value }`. `success(false)` answers `{ "success": false }`.

Example: With a value
```js
function create() {
	var id = UID();
	this.success(true, id);
	// {"success":true,"value":"..."}
}
```

### controller.invalid([status], [error])

Type: `method`

Answers with an error as JSON.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `status` | `Number|String|Error|ErrorBuilder` | no |  | A status code, the name of the error or the error. |
| `error` | `String` | no |  | The text of the error. |

Returns: `ErrorBuilder` The builder with the errors.

The errors are answered as a JSON array with the status `400` (the `default_errorbuilder_status` config). A number as the first argument sets the status; an `Error` or an `ErrorBuilder` is answered as it is. The answer is sent in the next tick, so you can still add errors to the returned builder.

Example: Validation
```js
function save() {
	if (!this.body.email)
		return this.invalid('email', 'The email is required');
	this.success();
}
```

Example: Another status
```js
this.invalid(409, 'The user exists');
```

### controller.done([value])

Type: `method`

Creates a callback that answers success or an error.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Boolean|Object` | no |  | `true` adds the response as `value`; another value is added as `value` itself. |

Returns: `Function` A callback `(err, response)`.

The callback has the form `(err, response)`. On error it calls `controller.invalid(err)`. Otherwise it answers `{ "success": true }`; with `done(true)` the response is added as `value`, and with another value that value is added.

Example: Any callback (err, response)
```js
function remove(id) {
	// removeproduct(id, callback) is your own function
	removeproduct(id, this.done());
}

function create() {
	// answers { "success": true, "value": response }
	createproduct(this.body, this.done(true));
}
```

### controller.callback([view])

Type: `method`

Creates a callback that answers the response as JSON or with a view.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `view` | `String` | no |  | The name of a view. |

Returns: `Function` A callback `(err, data)`.

The callback has the form `(err, data)`. When `err` is an `ErrorBuilder` and you did not pass a view, its errors are answered as JSON. Any other error answers the error page `404`, or `500` when the `ErrorBuilder` contains an `Error`. Without an error it answers `data` as JSON, or renders the view with `data` as the model.

Example: JSON
```js
function list() {
	// loadproducts(callback) is your own function
	loadproducts(this.callback());
}
```

Example: A view
```js
function list() {
	loadproducts(this.callback('products'));
}
```

### controller.throw404([problem])

Type: `method`

Answers with the error page 404 Not Found.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `problem` | `String` | no |  | A description of the problem, available in the error route as `controller.exception`. |

Returns: `Controller` The controller.

It runs the route `#404` when you declared one; otherwise the framework renders its own error page. The same family answers other statuses: `throw400()`, `throw401()`, `throw403()`, `throw409()`, `throw500()`, `throw501()` and `throw503()`. Each one has an alias named `view400()` … `view503()`. Nothing happens when the request was already answered.

Example: Missing record
```js
function detail(id) {
	var self = this;
	// findproduct(id, callback) is your own function
	findproduct(id, function(err, item) {
		if (item)
			self.view('detail', item);
		else
			self.throw404();
	});
}
```

Example: Your own page
```js
exports.install = function() {
	ROUTE('#404', notfound);
};

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

### controller.throw403([problem])

Type: `method`

Answers with the error page 403 Forbidden.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `problem` | `String` | no |  | A description of the problem, available in the error route as `controller.exception`. |

Returns: `Controller` The controller.

It runs the route `#403` when you declared one. Alias: `view403()`.

Example: Only for admins
```js
function admin() {
	if (!this.user.admin)
		return this.throw403();
	this.view('admin');
}
```

### controller.throw500([error])

Type: `method`

Logs an error and answers with the error page 500.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `error` | `Error|String` | no |  | The error. |

Returns: `Controller` The controller.

The error is logged by the framework (`DEF.onError`). Then the route `#500` runs when you declared one. Alias: `view500()`.

Example: In a promise
```js
async function stats() {
	try {
		this.json(await loadstats());
	} catch (err) {
		this.throw500(err);
	}
}
```

### controller.cookie(name, [value], [expires], [options])

Type: `method`

Reads a cookie of the request or writes a cookie to the response.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the cookie. |
| `value` | `String` | no |  | The value to write. |
| `expires` | `String` | no |  | When the cookie expires, for example `'7 days'`. |
| `options` | `Object` | no |  | `domain`, `path`, `secure`, `httponly`, `samesite`. |

Returns: `String|Controller` The value when reading, the controller when writing.

With one argument it returns the value of the cookie, or an empty string. With a value it adds a `Set-Cookie` header. `expires` is a text such as `'5 days'` or `'2 hours'`; a negative one (`'-1 day'`) removes the cookie. Instead of `expires` you can pass the options object with `expires` inside it.

Options: `domain`, `path` (default `/`), `secure` (default the `default_cookies_secure` config), `httponly`, and `samesite` (`Lax`, `Strict` or `None`; default `Lax`, the `default_cookies_samesite` config).

Example: Write and read
```js
function login() {
	this.cookie('session', 'token', '7 days', { httponly: true });
	this.redirect('/');
}

function home() {
	var session = this.cookie('session');
	this.plain(session);
}
```

Example: Remove
```js
this.cookie('session', '', '-1 day');
```

### controller.header(name, value)

Type: `method`

Sets a header of the response.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the header. |
| `value` | `String` | yes |  | The value. |

Returns: `Controller` The controller.

Example: A header
```js
this.header('X-Total', '42');
this.json(items);
```

### controller.nocache()

Type: `method`

Disables the HTTP cache of the answer.

Returns: `Controller` The controller.

Example: Fresh data
```js
function stats() {
	this.nocache();
	this.json(getstats());
}
```

### controller.csrf()

Type: `method` · Since: `0.0.37`

Creates a CSRF token for the current request.

Returns: `String` The token.

Routes with the `csrf` flag verify the token from the `x-csrf-token` header or from the `?csrf=` argument of the URL. In views the same token is `@{csrf}`.

Example: Send the token
```js
exports.install = function() {
	ROUTE('GET /api/token/', token);
	ROUTE('POST /api/save/ csrf', save);
};

function token() {
	this.json({ token: this.csrf() });
}
```

### controller.autoclear([enable])

Type: `method`

Keeps or removes the uploaded files when the request ends.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `enable` | `Boolean` | no | `true` | `false` keeps the files. |

Returns: `Controller` The controller.

`autoclear(false)` keeps the temporary files of `controller.files` after the answer, for work that continues later. `controller.clear()` removes them immediately.

Example: Process later
```js
function upload() {
	this.autoclear(false);
	var file = this.files[0];
	this.success();
	// file.path stays on the disk: process it, then remove it
}
```

### controller.sse(data, [eventname], [id], [retry])

Type: `method`

Sends a server-sent event.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `data` | `String|Object` | yes |  | The data of the event. |
| `eventname` | `String` | no |  | The name of the event. |
| `id` | `String` | no |  | The ID of the event. |
| `retry` | `Number` | no |  | How long the browser waits before it reconnects, in milliseconds. |

Returns: `Boolean` `false` when the event cannot be sent (the client disconnected or the request was answered).

The first call answers with the headers of `text/event-stream` and keeps the connection open. An object is serialized as JSON. When `retry` is missing, the first call uses the timeout of the route. The previous event ID sent by the browser is in `controller.sseID`. The stream ends with `controller.close()`.

Example: A clock
```js
exports.install = function() {
	ROUTE('GET /clock/', clock, ['delay']);
};

function clock() {
	var self = this;
	var timer = setInterval(function() {
		if (!self.sse({ time: new Date() }))
			clearInterval(timer);
	}, 1000);
}
```

### controller.proxy(options)

Type: `method`

Forwards the request to another URL and answers with its response.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `options` | `Object|String` | yes |  | The target URL, or the options. |

Returns: `undefined` Nothing.

The method, body, query string and headers of the request are sent to the target (except `host`, `connection`, `accept-encoding` and the `x-forwarded-*` headers). The status and the body of the response are answered back. On error it calls `controller.invalid(err)`.

Options: `url` (required), `method`, `headers`, `timeout` (default `10000` ms) and `callback(err, response)`, which runs before the answer.

Example: Forward an API
```js
exports.install = function() {
	ROUTE('GET /api/weather/', weather);
};

function weather() {
	this.proxy('https://api.example.com/weather');
}
```

### controller.baa([label])

Type: `method`

Reads Basic access authentication, or asks the browser for it.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `label` | `String` | no |  | The realm shown by the browser. |

Returns: `Object|null` The credentials without a label; `null` with a label.

Without an argument it returns `{ user, password, empty }` from the `Authorization` header. With a label it answers `401` with the `WWW-Authenticate` header, so the browser shows a login dialog.

Example: A protected page
```js
function admin() {
	var auth = this.baa();
	if (auth.empty || auth.user !== 'admin' || auth.password !== CONF.admin_password) {
		this.baa('Administration');
		return;
	}
	this.view('admin');
}
```

### controller.isConnected

Type: `property`

Tells whether the client is still connected.

Returns: `Boolean`

It is `false` after the client closed the connection or after `controller.close()`. Check it in long work before you answer.

Example: Long work
```js
function report() {
	var self = this;
	// longtask(callback) is your own function
	longtask(function(err, data) {
		if (self.isConnected)
			self.json(data);
	});
}
```

### controller.isController

Type: `property`

Always `true` for a controller.

Returns: `Boolean`

Useful to tell a controller from a `$` object in a shared function.

Example: A shared function
```js
function getuser(ctx) {
	return ctx.isController ? ctx.user : ctx.controller.user;
}
```

### controller.secured

Type: `property`

Tells whether the request came over HTTPS.

Returns: `Boolean`

It is `true` when the protocol is `https:` (or `wss:`). Behind a proxy it depends on the URL the framework sees. Same as `req.secured`.

Example: Force HTTPS
```js
function index() {
	if (!this.secured)
		return this.redirect('https://' + this.req.host + this.url);
	this.view('index');
}
```

### controller.referrer

Type: `property`

The `Referer` header of the request.

Returns: `String`

An empty string when the header is missing.

Example: Go back
```js
function back() {
	this.redirect(this.referrer || '/');
}
```

### controller.robot

Type: `property`

Tells whether the user agent looks like a bot.

Returns: `Boolean`

It tests the `User-Agent` header for words like `bot`, `crawler` and `spider`.

Example: Example
```js
function index() {
	if (this.robot)
		return this.plain('Hello robot');
	this.view('index');
}
```

### controller.ua

Type: `property`

The parsed user agent as a short text with the browser and the system.

Returns: `String`

Use `req.useragent(true)` for an object with the browser, the OS and the device. Same as `req.ua`.

Example: Example
```js
function index() {
	console.log(this.ua);
	this.view('index');
}
```

### controller.uri

Type: `property`

The parsed URL of the request.

Returns: `Object`

An object of `url.parse()` with `pathname`, `query`, `hostname` and the other parts.

Example: Example
```js
function index() {
	this.plain(this.uri.pathname + ' ' + (this.uri.query || ''));
}
```

### controller.split

Type: `property`

The parts of the path of the URL.

Returns: `String[]`

`/products/shoes/` gives `['products', 'shoes']`.

Example: Example
```js
// GET /docs/{page}/
function docs() {
	this.plain(this.split.join(' > '));
}
```

### controller.subdomain

Type: `property`

The subdomain of the request as an array.

Returns: `String[]`

`shop.eu.example.com` gives `['shop', 'eu']`; `www` is ignored. It is `null` without a subdomain.

Example: Example
```js
function index() {
	var tenant = this.subdomain ? this.subdomain[0] : 'default';
	this.view('index', { tenant: tenant });
}
```

### controller.sessionid

Type: `property`

The id of the session of the request.

Returns: `String`

Set by your `AUTH()` delegate or by the session mechanism. Same as `req.sessionid`.

Example: Example
```js
function logout() {
	// removesession(id) is your own function
	removesession(this.sessionid);
	this.redirect('/');
}
```

### controller.sseID

Type: `property`

The id of the last event the browser received.

Returns: `String`

The value of the `Last-Event-ID` header that the browser sends when it reconnects to a server-sent events route, or `null`.

Example: Example
```js
function events() {
	var last = this.sseID;
	this.sse({ resumed: !!last });
}
```

### controller.route

Type: `property`

The route that the request matched.

Returns: `Object`

An internal object of the framework with the URL, the flags, the schema and the options of the route. Read it, do not change it.

Example: Example
```js
function index() {
	console.log(this.route.url);
	this.empty();
}
```

### controller.options

Type: `property`

The custom options of the route.

Returns: `Object`

The object that you pass to `ROUTE()` as options.

Example: Example
```js
exports.install = function() {
	ROUTE('GET /reports/', report, { title: 'Reports' });
};

function report() {
	this.plain(this.options.title);
}
```

### controller.flags

Type: `property`

The flags of the route.

Returns: `String[]`

An array with the flags of the route, for example `['get', 'json']`.

Example: Example
```js
function index() {
	this.json(this.flags);
}
```

### controller.schema

Type: `property`

The name of the schema of the route.

Returns: `String`

For a route like `POST /api/users/ *Users --> save` it is `'Users'`. An empty string when the route has no schema.

Example: Example
```js
function action() {
	console.log(this.schema);
	this.empty();
}
```

### controller.name

Type: `property`

The name of the controller.

Returns: `String`

The name of the file in `/controllers/` (without `.js`) that declared the route.

Example: Example
```js
function index() {
	this.plain(this.name);
}
```

### controller.breadcrumb

Type: `property`

The breadcrumb of the current sitemap item.

Returns: `Object[]`

The items set by `controller.sitemap()`; in views the same list is in `@{sitemap}`.

Example: Example
```js
function detail() {
	this.sitemap('detail');
	this.json(this.breadcrumb);
}
```

### controller.jsonp(name, obj, [headers], [beautify], [replacer])

Type: `method`

Answers with JSONP: a call of a JavaScript function with the data.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the JavaScript function. |
| `obj` | `Object` | yes |  | The data. |
| `headers` | `Object` | no |  | Extra response headers. |
| `beautify` | `Boolean` | no | `false` | Formats the JSON. |
| `replacer` | `Function` | no |  | A replacer for `JSON.stringify()`. |

Returns: `Controller` The controller.

The body is `name(json)` with the content type `application/x-javascript`. Without `name` the function is `callback`. An `ErrorBuilder` is answered as its errors.

Example: Name from the query string
```js
function data() {
	this.jsonp(this.query.callback, { count: 10 });
}
```

### controller.throw400([problem])

Type: `method`

Answers with the error page 400 Bad Request.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `problem` | `String` | no |  | A description of the problem. |

Returns: `Controller` The controller.

It runs the route `#400` when you declared one; otherwise the framework renders its own error page. The problem is in `controller.exception` of the error route. Alias: `controller.view400()`.

Example: Answer 400
```js
function action() {
	this.throw400('Bad Request');
}
```

### controller.throw401([problem])

Type: `method`

Answers with the error page 401 Unauthorized.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `problem` | `String` | no |  | A description of the problem. |

Returns: `Controller` The controller.

It runs the route `#401` when you declared one; otherwise the framework renders its own error page. The problem is in `controller.exception` of the error route. Alias: `controller.view401()`.

Example: Answer 401
```js
function action() {
	this.throw401('Unauthorized');
}
```

### controller.throw409([problem])

Type: `method`

Answers with the error page 409 Conflict.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `problem` | `String` | no |  | A description of the problem. |

Returns: `Controller` The controller.

It runs the route `#409` when you declared one; otherwise the framework renders its own error page. The problem is in `controller.exception` of the error route. Alias: `controller.view409()`.

Example: Answer 409
```js
function action() {
	this.throw409('Conflict');
}
```

### controller.throw501([problem])

Type: `method`

Answers with the error page 501 Not Implemented.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `problem` | `String` | no |  | A description of the problem. |

Returns: `Controller` The controller.

It runs the route `#501` when you declared one; otherwise the framework renders its own error page. The problem is in `controller.exception` of the error route. Alias: `controller.view501()`.

Example: Answer 501
```js
function action() {
	this.throw501('Not Implemented');
}
```

### controller.throw503([problem])

Type: `method`

Answers with the error page 503 Service Unavailable.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `problem` | `String` | no |  | A description of the problem. |

Returns: `Controller` The controller.

It runs the route `#503` when you declared one; otherwise the framework renders its own error page. The problem is in `controller.exception` of the error route. Alias: `controller.view503()`.

Example: Answer 503
```js
function action() {
	this.throw503('Service Unavailable');
}
```

### controller.view400([problem])

Type: `method`

Alias of `controller.throw400()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `problem` | `String` | no |  | The problem. |

Returns: `Controller` The controller.

It answers the error page 400 in the same way.

Example: Same as throw400()
```js
function detail() {
	this.view400();
}
```

### controller.view401([problem])

Type: `method`

Alias of `controller.throw401()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `problem` | `String` | no |  | The problem. |

Returns: `Controller` The controller.

It answers the error page 401 in the same way.

Example: Same as throw401()
```js
function detail() {
	this.view401();
}
```

### controller.view403([problem])

Type: `method`

Alias of `controller.throw403()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `problem` | `String` | no |  | The problem. |

Returns: `Controller` The controller.

It answers the error page 403 in the same way.

Example: Same as throw403()
```js
function detail() {
	this.view403();
}
```

### controller.view404([problem])

Type: `method`

Alias of `controller.throw404()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `problem` | `String` | no |  | The problem. |

Returns: `Controller` The controller.

It answers the error page 404 in the same way.

Example: Same as throw404()
```js
function detail() {
	this.view404();
}
```

### controller.view409([problem])

Type: `method`

Alias of `controller.throw409()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `problem` | `String` | no |  | The problem. |

Returns: `Controller` The controller.

It answers the error page 409 in the same way.

Example: Same as throw409()
```js
function detail() {
	this.view409();
}
```

### controller.view500([error])

Type: `method`

Alias of `controller.throw500()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `error` | `Error` | no |  | The error, logged by the framework. |

Returns: `Controller` The controller.

It answers the error page 500 in the same way.

Example: Same as throw500()
```js
function detail() {
	this.view500();
}
```

### controller.view501([problem])

Type: `method`

Alias of `controller.throw501()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `problem` | `String` | no |  | The problem. |

Returns: `Controller` The controller.

It answers the error page 501 in the same way.

Example: Same as throw501()
```js
function detail() {
	this.view501();
}
```

### controller.view503([problem])

Type: `method`

Alias of `controller.throw503()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `problem` | `String` | no |  | The problem. |

Returns: `Controller` The controller.

It answers the error page 503 in the same way.

Example: Same as throw503()
```js
function detail() {
	this.view503();
}
```

### controller.nocontent([headers])

Type: `method`

Answers `204 No Content` without a body.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `headers` | `Object` | no |  | Extra response headers. |

Returns: `Controller` The controller.

Example: Nothing to answer
```js
function ping() {
	this.nocontent();
}
```

### controller.destroy()

Type: `method`

Closes the connection without an answer.

Returns: `Controller` The controller.

The socket is destroyed. Nothing happens when the request was already answered.

Example: Drop a request
```js
function upload() {
	if (this.req.headers['content-length'] > 1000000)
		return this.destroy();
	this.success();
}
```

### controller.close([end])

Type: `method`

Ends the answer, mostly a stream of server-sent events.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `end` | `Boolean` | no | `true` | Calls `res.end()`. |

Returns: `Controller` The controller.

It ends the response of `controller.sse()` and marks the controller as disconnected. With `end` set to `false` the response is only marked as finished.

Example: Stop a stream
```js
function events() {
	var self = this;
	self.sse({ step: 1 });
	setTimeout(function() {
		self.close();
	}, 5000);
}
```

### controller.cancel()

Type: `method`

Marks the controller as canceled.

Returns: `Controller` The controller.

It sets `controller.isCanceled` to `true`. Called in a handler of `ON('controller')`, it stops the action of the route from running, so the handler must answer itself.

Example: Stop requests in maintenance
```js
ON('controller', function(controller) {
	if (CONF.maintenance) {
		controller.cancel();
		controller.throw503('Maintenance');
	}
});
```

### controller.clear()

Type: `method`

Removes the uploaded files of the request now.

Returns: `Controller` The controller.

The temporary files of `controller.files` are deleted and `body`, `query` and the cookies of the request are cleared.

Example: After the work
```js
function upload() {
	var self = this;
	var file = self.files[0];
	file.move(PATH.databases(file.filename), function() {
		self.clear();
		self.success();
	});
}
```

### controller.custom()

Type: `method`

Lets you answer with the Node.js response yourself.

Returns: `Boolean` `true` when you can answer.

The framework marks the request as answered and stops waiting for it. Then write to `controller.res` with `writeHead()` and `end()`. It returns `false` when the request was already answered.

Example: Write the response
```js
function raw() {
	if (this.custom()) {
		this.res.writeHead(200, { 'Content-Type': 'text/plain' });
		this.res.end('OK');
	}
}
```

### controller.error(err)

Type: `method`

Logs an error with the name of the controller and the URL.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `err` | `Error|String` | yes |  | The error. |

Returns: `Controller` The controller.

The error goes to `F.error()` and to `controller.exception`; the request is not answered. An `ErrorBuilder` is answered as JSON instead.

Example: Log and continue
```js
function action() {
	this.error(new Error('Cache is empty'));
	this.json([]);
}
```

### controller.successful(callback)

Type: `method`

Creates a callback that answers the error and passes only the result on.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | yes |  | Runs on success with the results. |

Returns: `Function` A callback `(err, a, b, c)`.

The returned function has the form `(err, a, b, c)`. On error it calls `controller.invalid(err)`; otherwise it calls `callback(a, b, c)` with the controller as `this`.

Example: Only the success path
```js
function detail(id) {
	NOSQL('products').one().where('id', id).callback(this.successful(function(item) {
		this.view('detail', item);
	}));
}
```

### controller.hostname([path])

Type: `method`

Creates an absolute URL with the host of the request.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | no |  | A path to add. |

Returns: `String` The URL, for example `https://example.com/products/`.

The protocol, the host name and the port of the request with `path` added.

Example: A link for an email
```js
function invite() {
	this.json({ url: this.hostname('/invite/' + UID() + '/') });
}
```

### controller.image(filename, make, [headers], [callback])

Type: `method`

Answers with an image changed by the image processor.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String|Stream` | yes |  | The image. |
| `make` | `Function` | yes |  | `function(image)`. |
| `headers` | `Object` | no |  | Extra response headers. |
| `callback` | `Function` | no |  | Runs when the response ends. |

Returns: `Controller` The controller.

`filename` is a file in `/public/` (or a full path with `~` in front) or a stream. `make(image)` changes the image with the methods of `Image` (`resize()`, `quality()`, ...). The result is cached in `/tmp/`. It needs GraphicsMagick or ImageMagick.

Example: A thumbnail
```js
function thumbnail() {
	this.image('/img/photo.jpg', function(image) {
		image.resize(200, 200);
		image.quality(80);
	});
}
```

### controller.memorize(key, expire, [disabled], fn, [fnFrom])

Type: `method`

Caches the whole answer of an action.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String` | yes |  | The key in the cache. |
| `expire` | `String|Date` | yes |  | How long, for example `'5 minutes'`. |
| `disabled` | `Boolean` | no | `false` | `true` skips the cache. |
| `fn` | `Function` | yes |  | Creates the answer; runs with the controller as `this`. |
| `fnFrom` | `Function` | no |  | Runs before an answer from the cache. |

Returns: `Controller` The controller.

The first call runs `fn` and stores the answer (a view, JSON or text) under `key` for `expire`. Later calls answer from the cache, and `fnFrom` runs before that. With `disabled` set to `true` the cache is skipped. The theme is added to the key.

Example: Cache the home page
```js
function index() {
	this.memorize('home', '5 minutes', DEBUG, function() {
		this.view('index');
	});
}
```

### controller.description(value)

Type: `method`

Sets the meta description of the page.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String` | yes |  | The description. |

Returns: `Controller` The controller.

In the layout it is written by `@{meta}`. `controller.keywords()` sets the keywords and `controller.author()` the author the same way.

Example: Meta tags
```js
function index() {
	this.title('Shop');
	this.description('Shoes and clothes');
	this.view('index');
}
```

### controller.keywords(value)

Type: `method`

Sets the meta keywords of the page.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String|Array` | yes |  | The keywords. |

Returns: `Controller` The controller.

An array is joined with commas. In the layout it is written by `@{meta}`.

Example: Keywords
```js
function index() {
	this.keywords(['shoes', 'clothes']);
	this.view('index');
}
```

### controller.head([value], [...])

Type: `method`

Adds tags into the head of the layout, or reads them.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String` | no |  | A file name or an HTML tag. |

Returns: `Controller|String` The controller, or the HTML without arguments.

A `.css` file becomes a `<link>` and a `.js` file a `<script>`; relative names point to `/public/css/` and `/public/js/`. A value that starts with `<` is added as it is. Each value is added once. Without arguments it returns the HTML; in the layout use `@{head}`.

Example: Files for one page
```js
function editor() {
	this.head('editor.css', 'editor.js');
	this.view('editor');
}
```

### controller.place(name, [value], [...])

Type: `method`

Adds content into a named place of the layout, or reads it.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the place. |
| `value` | `String` | no |  | The content. |

Returns: `Controller|String` The controller, or the content with only `name`.

A `.js` value becomes a `<script>` and a `.css` value a `<link>`; other values are added as they are. In the layout use `@{place('name')}`.

Example: Scripts at the end of the page
```js
function index() {
	this.place('footer', '/js/chart.js');
	this.view('index');
}
```

### controller.theme(name)

Type: `method`

Sets the theme of the views of this request.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the theme. |

Returns: `Controller` The controller.

Views, layouts and static files are then looked up in `/themes/{name}/` first. The default comes from `CONF.default_theme`.

Example: A theme per customer
```js
function index() {
	this.theme(this.query.dark ? 'dark' : 'default');
	this.view('index');
}
```

### controller.component(name, [settings], [model])

Type: `method`

Renders a component to HTML.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the component. |
| `settings` | `Object` | no |  | The settings of the component. |
| `model` | `Object` | no |  | The model; the model of the view by default. |

Returns: `String` The HTML, or an empty string for an unknown component.

The component is a file in `/components/`. Its CSS and JS are added to the head of the layout. In views use `@{component('name')}`.

Example: HTML of a component
```js
function widget() {
	this.html(this.component('chart', { color: 'red' }));
}
```

### controller.helper(name, [arg], [...])

Type: `method`

Runs a view helper from `DEF.helpers`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the helper. |
| `arg` | `Object` | no |  | Arguments for the helper. |

Returns: `String` The output of the helper.

The helper runs with the controller as `this`. An unknown helper returns an empty string.

Example: Use a helper in an action
```js
DEF.helpers.price = function(value) {
	return value.format(2) + ' EUR';
};

function price() {
	this.plain(this.helper('price', 10));
}
```

### controller.public(name, [path])

Type: `method`

Creates the URL of a file in `/public/`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The file. |
| `path` | `String` | no |  | A path joined to a relative URL. |

Returns: `String` The URL.

It respects the static URL settings and the theme. The family `controller.public_js()`, `public_css()`, `public_image()`, `public_video()`, `public_font()` and `public_download()` does the same for its own directory.

Example: A URL in JSON
```js
function config() {
	this.json({ logo: this.public_image('logo.png'), file: this.public('docs/terms.pdf') });
}
```

### controller.public_js(name, [tag])

Type: `method`

Creates the URL of a file in the public `js` directory.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The file. |
| `tag` | `Boolean` | no | `false` | Returns an HTML tag. |

Returns: `String` The URL.

The directory comes from the configuration (`static_url_script`, default `/js/`). With `tag` set to `true` it returns the HTML tag (`<script>` or `<link>`).

Example: URL of a file
```js
function index() {
	this.plain(this.public_js('app.js'));
}
```

### controller.public_css(name, [tag])

Type: `method`

Creates the URL of a file in the public `css` directory.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The file. |
| `tag` | `Boolean` | no | `false` | Returns an HTML tag. |

Returns: `String` The URL.

The directory comes from the configuration (`static_url_style`, default `/css/`). With `tag` set to `true` it returns the HTML tag (`<script>` or `<link>`).

Example: URL of a file
```js
function index() {
	this.plain(this.public_css('app.css'));
}
```

### controller.public_image(name)

Type: `method`

Creates the URL of a file in the public `img` directory.

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

Returns: `String` The URL.

The directory comes from the configuration (`static_url_image`, default `/img/`).

Example: URL of a file
```js
function index() {
	this.plain(this.public_image('logo.png'));
}
```

### controller.public_video(name)

Type: `method`

Creates the URL of a file in the public `videos` directory.

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

Returns: `String` The URL.

The directory comes from the configuration (`static_url_video`, default `/videos/`).

Example: URL of a file
```js
function index() {
	this.plain(this.public_video('intro.mp4'));
}
```

### controller.public_font(name)

Type: `method`

Creates the URL of a file in the public `fonts` directory.

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

Returns: `String` The URL.

The directory comes from the configuration (`static_url_font`, default `/fonts/`).

Example: URL of a file
```js
function index() {
	this.plain(this.public_font('icons.woff2'));
}
```

### controller.public_download(name)

Type: `method`

Creates the URL of a file in the public `download` directory.

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

Returns: `String` The URL.

The directory comes from the configuration (`static_url_download`, default `/download/`).

Example: URL of a file
```js
function index() {
	this.plain(this.public_download('manual.pdf'));
}
```

### controller.runtest(url, [name], [callback])

Type: `method`

Adds a test of a route in the tests of the framework.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | The route to test. |
| `name` | `String` | no |  | The name of the test. |
| `callback` | `Function` | no |  | `function(result)` that returns `true` on success. |

Returns: `Object` The test.

The tests of one controller run one after another. `url` is a route like `'GET /api/products/'` or `'API /api/ products_query'` (then the name of the test is the operation). `callback(result)` gets `{ err, value, response, name }` and returns `true` when the test passes; without it, a test passes when there is no error.

Example: Test routes from a route
```js
function selftest() {
	this.runtest('GET /api/products/', function(result) {
		return !result.err && result.value instanceof Array;
	});
	this.success();
}
```

### req.host

Type: `property`

The `Host` header of the request.

Returns: `String`

The host name with the port, for example `example.com:8000`.

Example: Example
```js
function index() {
	this.plain(this.req.host);
}
```

### req.secured

Type: `property`

Tells whether the request came over HTTPS.

Returns: `Boolean`

It is `true` when the protocol is `https:` or `wss:`.

Example: Example
```js
MIDDLEWARE('https', function($) {
	if ($.req.secured)
		$.next();
	else
		$.res.redirect('https://' + $.req.host + $.req.url);
});
```

### req.isAuthorized

Type: `property`

The result of the authorization.

Returns: `Boolean`

It is `true` until your `AUTH()` delegate runs, then it is `true` when the delegate accepted the user and `false` when it rejected it.

Example: Example
```js
function index() {
	this.plain(this.req.isAuthorized ? 'Signed in' : 'Guest');
}
```

### req.isStaticFile

Type: `property`

Tells whether the request asks for a static file.

Returns: `Boolean`

It is `true` when the URL has a file extension and static files are allowed. Useful in `DEF.onLocale` and middleware.

Example: Example
```js
DEF.onLocale = function(req) {
	return req.isStaticFile ? '' : (req.query.lang || 'en');
};
```

### req.xhr

Type: `property`

Tells whether the request came from JavaScript.

Returns: `Boolean`

It is `true` when the header `X-Requested-With` is `XMLHttpRequest`.

Example: Example
```js
function index() {
	if (this.req.xhr)
		this.json({ ok: true });
	else
		this.view('index');
}
```

### req.ip

Type: `property`

The IP address of the client.

Returns: `String`

Behind a proxy it is the first address of `X-Forwarded-For`. It can be set.

Example: Example
```js
function index() {
	this.plain(this.req.ip);
}
```

### req.uri

Type: `property`

The parsed URL of the request.

Returns: `Object`

An object of `url.parse()` with `pathname`, `query`, `hostname` and `port`.

Example: Example
```js
function index() {
	this.plain(this.req.uri.pathname);
}
```

### req.path

Type: `property`

The parts of the path in lower case.

Returns: `String[]`

`/Products/Shoes/` gives `['products', 'shoes']`. `req.split` keeps the original case.

Example: Example
```js
function index() {
	this.json(this.req.path);
}
```

### req.split

Type: `property`

The parts of the path of the URL.

Returns: `String[]`

The parts as they were in the URL. Same as `controller.split`.

Example: Example
```js
function index() {
	this.json(this.req.split);
}
```

### req.subdomain

Type: `property`

The subdomain as an array, or `null`.

Returns: `String[]`

`www` is ignored. `a.localhost` gives `['a']`.

Example: Example
```js
function index() {
	this.json(this.req.subdomain);
}
```

### req.mobile

Type: `property`

Tells whether the user agent is a mobile device.

Returns: `Boolean`

It tests the `User-Agent` header. It can be set.

Example: Example
```js
function index() {
	this.view(this.req.mobile ? 'mobile' : 'index');
}
```

### req.robot

Type: `property`

Tells whether the user agent looks like a bot.

Returns: `Boolean`

It tests the `User-Agent` header.

Example: Example
```js
function index() {
	this.plain(this.req.robot ? 'bot' : 'human');
}
```

### req.ua

Type: `property`

The parsed user agent as a short text with the browser and the system.

Returns: `String`

The same as `req.useragent()`.

Example: Example
```js
function index() {
	this.plain(this.req.ua);
}
```

### req.query

Type: `property`

The query string as an object.

Returns: `Object`

It is parsed on the first read and can be set.

Example: Example
```js
function index() {
	this.json(this.req.query);
}
```

### req.body

Type: `property`

The parsed body of the request.

Returns: `Object`

A JSON or form body. Same as `controller.body`.

Example: Example
```js
function save() {
	this.json(this.req.body);
}
```

### req.files

Type: `property`

The uploaded files.

Returns: `HttpFile[]`

An array of `HttpFile` objects for routes with the `upload` flag. Same as `controller.files`.

Example: Example
```js
function upload() {
	this.json(this.req.files.map(function(file) {
		return file.filename;
	}));
}
```

### req.user

Type: `property`

The user accepted by the `AUTH()` delegate, or `null`.

Returns: `Object`

Same as `controller.user`.

Example: Example
```js
function index() {
	this.json(this.req.user);
}
```

### req.session

Type: `property`

The session object of the request, or `null`.

Returns: `Object`

Set by your `AUTH()` delegate or the session mechanism. Same as `controller.session`.

Example: Example
```js
function index() {
	this.json(this.req.session);
}
```

### req.useragent([structured])

Type: `method`

Parses the `User-Agent` header.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `structured` | `Boolean` | no | `false` | Returns an object. |

Returns: `String|Object` The user agent.

Without an argument it returns a short text with the names found in the header, such as the browser and the system. With `true` it returns `{ os, browser, device }`, where `device` is `desktop`, `mobile`, `tablet` or `tv`. The result is cached on the request.

Example: Details of the device
```js
function index() {
	this.json(this.req.useragent(true));
}
```

### req.cookie(name)

Type: `method`

Reads a cookie of the request.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the cookie. |

Returns: `String` The value.

The value is decoded. A missing cookie gives an empty string. `controller.cookie(name)` does the same.

Example: Read a cookie in middleware
```js
MIDDLEWARE('lang', function($) {
	$.req.$language = $.req.cookie('lang') || 'en';
	$.next();
});
```

### req.authorization()

Type: `method`

Reads the Basic authorization header.

Returns: `Object` `{ user, password, empty }`.

It decodes `Authorization: Basic ...` to `{ user, password, empty }`. `empty` is `true` when the user or the password is missing.

Example: Basic auth
```js
function admin() {
	var auth = this.req.authorization();
	if (auth.empty || auth.user !== 'admin' || auth.password !== CONF.admin_password) {
		this.header('WWW-Authenticate', 'Basic realm="Admin"');
		return this.throw401();
	}
	this.view('admin');
}
```

### req.authorize(callback)

Type: `method`

Runs the `AUTH()` delegate for this request yourself.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | yes |  | `function(err, user, isAuthorized)`. |

Returns: `Request` The request.

`callback(err, user, isAuthorized)` gets the result of the delegate. Without a delegate `isAuthorized` is `false`. Useful for routes that do not use the authorization flags.

Example: Check a user on a public route
```js
function index() {
	var self = this;
	self.req.authorize(function(err, user, isAuthorized) {
		self.view('index', { user: isAuthorized ? user : null });
	});
}
```

### req.clear()

Type: `method`

Removes the uploaded files of the request.

Returns: `Request` The request.

Same as `controller.clear()`.

Example: Clear the files
```js
function upload() {
	this.req.clear();
	this.success();
}
```

### req.csrf()

Type: `method` · Since: `0.0.37`

Creates a CSRF token for the request.

Returns: `String` The token.

Same as `controller.csrf()`; it uses `DEF.onCSRFcreate(req)`.

Example: A token in middleware
```js
MIDDLEWARE('token', function($) {
	$.res.setHeader('X-CSRF-Token', $.req.csrf());
	$.next();
});
```

### req.encrypt([enable])

Type: `method`

Encrypts the text answer of this request.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `enable` | `Boolean` | no | `true` | `false` turns it off. |

Returns: `Request` The request.

The answer is encrypted with `CONF.secret_encryption` and gets the header `X-Encryption: a`. `controller.encrypt([enable])` does the same.

Example: Encrypt one answer
```js
function secret() {
	this.req.encrypt();
	this.json({ token: UID() });
}
```

### req.hostname([path])

Type: `method`

Creates an absolute URL with the host of the request.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | no |  | A path to add. |

Returns: `String` The URL.

The protocol, the host name and the port of the request with `path` added. Same as `controller.hostname()`.

Example: Absolute URL
```js
function index() {
	this.plain(this.req.hostname('/login/'));
}
```

### req.nocache()

Type: `method`

Disables the HTTP cache of the answer.

Returns: `Request` The request.

It calls `res.nocache()`.

Example: In middleware
```js
MIDDLEWARE('nocache', function($) {
	$.req.nocache();
	$.next();
});
```

### res.controller

Type: `property`

The controller of the request.

Returns: `Controller`

Set when a controller handles the request.

Example: Example
```js
MIDDLEWARE('log', function($) {
	console.log($.res.controller ? 'controller' : 'no controller');
	$.next();
});
```

### res.success

Type: `property`

Tells whether the response was sent.

Returns: `Boolean`

It is `true` after the framework answered the request.

Example: Example
```js
function action() {
	var self = this;
	setTimeout(function() {
		if (!self.res.success)
			self.empty();
	}, 1000);
}
```

### res.nocompress

Type: `property`

Turns off the compression of HTML and static files for this response.

Returns: `Boolean`

With `true` the framework does not minify the HTML and the static files it sends.

Example: Example
```js
MIDDLEWARE('raw', function($) {
	$.res.nocompress = true;
	$.next();
});
```

### res.json(obj)

Type: `method`

Answers with an object as JSON.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `obj` | `Object` | yes |  | The value. |

Returns: `Response` The response.

The status comes from the response options (`200` by default).

Example: JSON from a route with (req, res)
```js
ROUTE('GET /api/ping/', function(req, res) {
	res.json({ ok: true });
});
```

### res.content(code, body, type, [compress], [headers])

Type: `method`

Answers with a body and a content type.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `code` | `Number` | yes |  | The HTTP status. |
| `body` | `String` | yes |  | The body. |
| `type` | `String` | yes |  | The content type. |
| `compress` | `Boolean` | no |  | Compression. |
| `headers` | `Object` | no |  | Extra response headers. |

Returns: `Response` The response.

Bodies over 4 kB are compressed with GZIP.

Example: A CSV
```js
ROUTE('GET /export/', function(req, res) {
	res.content(200, 'id;name\n1;Peter', 'text/csv');
});
```

### res.send([code], body, [type])

Type: `method`

Answers in the style of Express.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `code` | `Number` | no | `200` | The HTTP status. |
| `body` | `String|Object|Number` | yes |  | The body. |
| `type` | `String` | no |  | The content type. |

Returns: `Response` The response.

A string is `text/html`, a number is answered as the text of that status, an object is JSON and an `ErrorBuilder` is answered as its errors. It is meant for middleware written for Express.

Example: Express style
```js
ROUTE('GET /hello/', function(req, res) {
	res.send('<b>Hello</b>');
});
```

### res.binary(buffer, type, [encoding], [download], [headers])

Type: `method`

Answers with a buffer.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `buffer` | `Buffer` | yes |  | The data. |
| `type` | `String` | yes |  | The content type. |
| `encoding` | `String` | no |  | The encoding of the buffer. |
| `download` | `String` | no |  | A file name to download. |
| `headers` | `Object` | no |  | Extra response headers. |

Returns: `Response` The response.

`download` sets the file name of `Content-Disposition`.

Example: A generated file
```js
ROUTE('GET /file/', function(req, res) {
	res.binary(Buffer.from('Hello'), 'text/plain', 'binary', 'hello.txt');
});
```

### res.image_nocache(input, make, [headers], [callback])

Type: `method`

Answers with a changed image without the cache of `/tmp/`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `input` | `String|Stream` | yes |  | The image. |
| `make` | `Function` | yes |  | `function(image)`. |
| `headers` | `Object` | no |  | Extra response headers. |
| `callback` | `Function` | no |  | Runs at the end. |

Returns: `Response` The response.

Works like `res.image()`, but the result is created for every request.

Example: Image with a timestamp
```js
ROUTE('GET /stamp/', function(req, res) {
	res.image_nocache(PATH.public('img/photo.jpg'), function(image) {
		image.resize(300, 200);
	});
});
```

### res.nocache()

Type: `method`

Disables the HTTP cache of the response.

Returns: `Response` The response.

It removes `If-None-Match` and `If-Modified-Since` from the request and sets `Cache-Control: private, no-cache, no-store, max-age=0`.

Example: In a route with (req, res)
```js
ROUTE('GET /now/', function(req, res) {
	res.nocache();
	res.json({ now: new Date() });
});
```

### res.throw409([problem])

Type: `method`

Answers with the error page 409 Conflict.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `problem` | `String` | no |  | A description of the problem. |

Returns: `Response` The response.

It runs the route `#409` when you declared one.

Example: Answer 409
```js
ROUTE('GET /legacy/', function(req, res) {
	res.throw409();
});
```

### res.throw501([problem])

Type: `method`

Answers with the error page 501 Not Implemented.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `problem` | `String` | no |  | A description of the problem. |

Returns: `Response` The response.

It runs the route `#501` when you declared one.

Example: Answer 501
```js
ROUTE('GET /legacy/', function(req, res) {
	res.throw501();
});
```
