---
title: Controller
project: Total.js V5
version: 0.0.20
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/controller/
updated: 2026-11-18T16:57:24.576Z
---

# Controller

> Properties and methods of the controller `$` that every route action receives.

The controller is the `$` argument of every route action. It holds the request data (`$.params`, `$.query`, `$.body`, `$.files`, `$.headers`, `$.user`...) and the methods that send the response (`$.json()`, `$.success()`, `$.invalid()`, `$.view()`, `$.file()`, `$.redirect()`...). For a walkthrough with examples, read the guide [Controller](../../guides/controller/).

## API

### $.req

Type: `property`

The Node.js request object.

Returns: `IncomingMessage`

The `http.IncomingMessage` of the request. Use it only for what the controller does not offer.

### $.res

Type: `property`

The Node.js response object.

Returns: `ServerResponse`

The `http.ServerResponse` of the request. When you write to it yourself, call `$.custom()` first so the framework does not answer the request too.

### $.method

Type: `property`

The HTTP method of the request.

Returns: `String`

An upper-case string such as `GET`, `POST`, `PUT`, `PATCH` or `DELETE`.

Example: Example
```js
ROUTE('POST /api/items/', function($) {
	// $.method === 'POST'
	$.success();
});
```

### $.url

Type: `property`

The path of the URL.

Returns: `String`

The path without the query string. A path without a file extension always ends with `/`, and double slashes are merged. The letters keep their case.

Example: Example
```js
ROUTE('GET /docs/', function($) {
	// /docs?page=1 gives '/docs/'
	$.plain($.url);
});
```

### $.uri

Type: `property`

The parsed URL.

Returns: `Object`

An object with `pathname` (the same as `$.url`), `search` (the query string without `?`), `split` (the segments), `ext` (the file extension) and `file` (`true` for a request of a static file).

### $.split

Type: `property`

The segments of the path.

Returns: `String[]`

An array of the parts of the path: `/blog/2025/hello/` gives `['blog', '2025', 'hello']`. The root path `/` gives an empty array.

Example: Example
```js
ROUTE('GET /blog/*', function($) {
	$.json($.split);
});
```

### $.params

Type: `property`

The dynamic parts of the URL.

Returns: `Object`

Each `{name}` of the route becomes a key with the matching segment of the path as a string. Convert numbers and dates yourself.

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

function order($) {
	var id = $.params.id;
	$.json({ id: id });
}
```

### $.query

Type: `property`

The query string as an object.

Returns: `Object`

Values are strings: `?page=2&q=shoes` gives `{ page: '2', q: 'shoes' }`. You can assign a new object. In an API route, it contains the query of the `schema` field.

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

### $.body

Type: `property`

The parsed body of the request.

Returns: `Object`

For `POST`, `PUT`, `PATCH` and `DELETE` requests. A JSON body is parsed into an object, a URL-encoded form into an object of strings, and a `multipart/form-data` request gives the fields of the form. Other content types keep `{}` and the raw data is in `$.payload`. In an API route, it contains the `data` of the request.

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

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

### $.payload

Type: `property`

The raw body as a Buffer.

Returns: `Buffer`

The bytes of the body for every content type except `multipart/form-data`. Use it for XML, plain text or binary uploads. It is released when the response ends.

Example: Example
```js
ROUTE('POST /api/xml/', function($) {
	var xml = $.payload.toString('utf8');
	$.plain('Received ' + xml.length + ' chars');
});
```

### $.files

Type: `property`

The uploaded files.

Returns: `HttpFile[]`

An array of files (`HttpFile`) from a `multipart/form-data` request, empty for other requests. The files are temporary and are removed when the response ends, unless you move them or call `$.autoclear(false)`.

Example: Example
```js
function upload($) {
	var names = [];
	for (var file of $.files)
		names.push(file.filename + ' (' + file.size + ' bytes)');
	$.json(names);
}
```

### $.headers

Type: `property`

The request headers.

Returns: `Object`

The headers object of Node.js: names are in lower case.

Example: Example
```js
function info($) {
	$.json({ agent: $.headers['user-agent'], lang: $.headers['accept-language'] });
}
```

### $.ip

Type: `property`

The IP address of the client.

Returns: `String`

The first address of `X-Forwarded-For` when the header exists (behind a proxy), otherwise the remote address of the connection.

Example: Example
```js
function track($) {
	console.log('Request from', $.ip);
	$.success();
}
```

### $.ua

Type: `property`

A short name of the client from the User-Agent header.

Returns: `String`

The system and the browser found in `User-Agent`, for example `Mac OS Chrome`, or an empty string without the header.

### $.mobile

Type: `property`

`true` for a mobile device.

Returns: `Boolean`

`true` when `User-Agent` matches a phone or a tablet (Android, iPhone, iPad, Mobile, Tablet...).

### $.robot

Type: `property`

`true` for a crawler.

Returns: `Boolean`

`true` when `User-Agent` contains `search`, `agent`, `bot`, `crawler` or `spider`.

### $.xhr

Type: `property`

`true` for an XMLHttpRequest.

Returns: `Boolean`

`true` when the request has the header `X-Requested-With: XMLHttpRequest`. `$.fallback()` answers such requests with JSON instead of an HTML page.

### $.protocol

Type: `property`

The protocol of the request.

Returns: `String`

`https` for an encrypted connection or when a proxy says so (`X-Forwarded-Proto: https`, `X-Forwarded-SSL: on` or `X-Forwarded-Port: 443`), otherwise `http`.

### $.address

Type: `property`

The full URL of the request.

Returns: `String`

The protocol, the host and the original URL with the query string, for example `https://example.com/products/?page=2`.

### $.user

Type: `property`

The signed-in user.

Returns: `Object`

The object your authorization delegate returned for the request, or `undefined` when nobody is signed in. See [Authorization](../../guides/authorization/).

Example: Example
```js
ROUTE('+GET /api/account/', function($) {
	$.json({ name: $.user.name });
});
```

### $.language

Type: `property`

The language of the request.

Returns: `String`

The value your localization delegate returned, or an empty string. It selects the translation of views and of error messages. See [Localization](../../guides/localization/).

### $.response

Type: `property`

The response that will be sent.

Returns: `Object`

An object with `status` (default `200`), `headers` (an object of response headers), `cache` (HTTP cache for files) and `minify`. Change it before you call a response method.

Example: Status and a header
```js
function create($) {
	$.response.status = 201;
	$.response.headers['x-version'] = '1';
	$.json({ id: UID() });
}
```

### $.json(value, [beautify], [replacer])

Type: `method`

Sends JSON.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object` | yes |  | The value to serialize. |
| `beautify` | `Boolean` | no | `false` | `true` indents the JSON with tabs. |
| `replacer` | `Function|Array` | no |  | A replacer for `JSON.stringify()`. |

Serializes `value` with `JSON.stringify()`, sets `content-type: application/json` and headers that disable caching (`cache-control: private, no-cache, no-store, max-age=0`, `expires: -1`). `beautify` indents the output with tabs. `replacer` is passed to `JSON.stringify()` as its second argument: a function `(key, value)` or an array of keys to keep.

Example: Example
```js
ROUTE('GET /api/products/', function($) {
	$.json([{ id: 1, name: 'Shoes' }]);
});
```

Example: Beautify and hide a key
```js
ROUTE('GET /api/debug/', function($) {
	$.json({ id: 1, password: 'secret' }, true, function(key, value) {
		return key === 'password' ? undefined : value;
	});
});
```

### $.jsonstring(value)

Type: `method`

Sends a string that is already JSON.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String` | yes |  | A JSON string. |

Sends the string as it is with the same headers as `$.json()`. Use it for JSON you have cached or read from a file.

Example: Example
```js
function cached($) {
	$.jsonstring('{"ok":true}');
}
```

### $.success([value])

Type: `method`

Sends `{ success: true, value: value }`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object` | no |  | An optional value for the `value` key. |

A shortcut for the usual answer of an API. Without `value` the response is `{"success":true}`.

Example: Example
```js
function remove($) {
	NOSQL('products').remove().id($.params.id);
	$.success($.params.id);
}
```

### $.invalid(error)

Type: `method`

Sends an error as JSON.

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

Accepts a string, an `Error`, an `ErrorBuilder` or an HTTP status code. The response is a JSON array such as `[{"error":"Name is required"}]` with the status `400`, or the given status code (`$.invalid(404)` gives `[{"error":"404: Not Found"}]` with status `404`). Text written as `@(text)` is translated from a resource. Without an argument it sends `401`. The response is sent asynchronously.

Example: Example
```js
function save($) {
	if (!$.body.email) {
		$.invalid('@(Email is required)');
		return;
	}
	$.success();
}
```

### $.invalidsafe(message, [error])

Type: `method`

Sends an error message and logs the real error.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `message` | `String|Number|ErrorBuilder` | yes |  | The error for the client. |
| `error` | `Error|String` | no |  | The error for the log. |

Sends `message` as `$.invalid(message)` does and writes `error` to the error log with `F.error()` and the URL of the request. The client gets only the message. `message` can also be an `ErrorBuilder`.

Example: Example
```js
function report($) {
	F.Fs.readFile(PATH.root('reports/2025.csv'), function(err, buffer) {
		if (err)
			$.invalidsafe('The report is not available', err);
		else
			$.content(buffer, 'text/csv');
	});
}
```

### $.html(value)

Type: `method`

Sends HTML.

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

Sets `content-type: text/html` and sends the string. It is minified when the configuration key `$minifyhtml` is `true` (the default).

Example: Example
```js
ROUTE('GET /hello/', function($) {
	$.html('<h1>Hello</h1>');
});
```

### $.throw(error)

Type: `method`

Writes an error to the log.

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

Returns: `Controller` The same controller.

Passes `error` with the URL of the request to the error handler of the framework (`DEF.onError`): it is printed, kept in `F.errors` and emitted as the `error` event. Nothing is sent to the client. Returns `$`.

Example: Example
```js
function save($) {
	NOSQL('visits').insert({ url: $.url, dtcreated: NOW }).callback(function(err) {
		err && $.throw(err);
	});
	$.success();
}
```

### $.plain(value)

Type: `method`

Sends plain text.

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

Sets `content-type: text/plain`. `$.text()` is the same method.

Example: Example
```js
ROUTE('FILE /robots.txt', function($) {
	$.plain('User-agent: *');
});
```

### $.xml(value)

Type: `method`

Sends XML.

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

Sets `content-type: text/xml` and sends the string.

Example: Example
```js
function feed($) {
	$.xml('<?xml version="1.0"?><rss></rss>');
}
```

### $.empty()

Type: `method`

Sends status 204 without a body.

Use it when a request needs no data in the answer.

Example: Example
```js
ROUTE('POST /api/ping/', function($) {
	$.empty();
});
```

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

Type: `method`

Redirects the client.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | The target URL. |
| `permanent` | `Boolean` | no | `false` | `true` for a permanent redirect (301). |

Sets the `Location` header and the status `302`, or `301` when `permanent` is `true`.

Example: Example
```js
ROUTE('GET /old/', function($) {
	$.redirect('/new/', true);
});
```

### $.view([name], [model])

Type: `method`

Renders a view and sends it as HTML.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | no |  | The name of the view, without the extension. |
| `model` | `Object` | no |  | The model for the view. |

Returns: `View` The view instance.

Renders the view `name` from the `/views/` directory with `model` and sends it with `$.html()`. With the layout from `$.layout()`. Without `name` it only returns a new `View` instance for the controller. See [Views](../../guides/views/).

Example: Example
```js
function detail($) {
	NOSQL('products').one().id($.params.id).callback(function(err, response) {
		if (response)
			$.view('detail', response);
		else
			$.fallback(404);
	});
}
```

### $.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. |

The view rendered with `$.view()` is placed into the layout `name`.

Example: Example
```js
function admin($) {
	$.layout('layout-admin');
	$.view('dashboard');
}
```

### $.file(path, [download])

Type: `method`

Sends a file from the disk.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes |  | An absolute path of the file. |
| `download` | `Boolean|String` | no |  | A file name for the download, or `true`. |

Sets the content type from the extension and supports `Range` requests, gzip and HTTP cache headers. JS, CSS and HTML files are minified unless their name contains `.min`, `-min` or `@min`. With `download` the browser saves the file: pass `true` to keep its name or a string to rename it. A missing file gives `404`.

Example: Example
```js
ROUTE('GET /download/', function($) {
	$.file(PATH.root('reports/2025.pdf'), 'report.pdf');
});
```

### $.stream(type, stream, [download])

Type: `method`

Sends a readable stream.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `type` | `String` | yes |  | The content type. |
| `stream` | `ReadableStream` | yes |  | The stream. |
| `download` | `String` | no |  | A file name for the download. |

Pipes `stream` to the response with the content type `type` (default `application/octet-stream`). Text types are compressed with gzip when the client supports it. A string `download` sends the stream as an attachment with that name.

Example: Example
```js
function exportcsv($) {
	var stream = F.Fs.createReadStream(PATH.root('export.csv'));
	$.stream('text/csv', stream, 'export.csv');
}
```

### $.binary(buffer, type, [download])

Type: `method`

Sends a Buffer.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `buffer` | `Buffer` | yes |  | The data. |
| `type` | `String` | yes |  | The content type. |
| `download` | `String` | no |  | A file name for the download. |

Sends the bytes with the content type `type`. A string `download` sends them as an attachment with that name.

Example: Example
```js
function pixel($) {
	var buffer = Buffer.from('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7', 'base64');
	$.binary(buffer, 'image/gif');
}
```

### $.content(value, [type])

Type: `method`

Sends a string or a Buffer with a content type.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String|Buffer` | yes |  | The content. |
| `type` | `String` | no | `'application/octet-stream'` | The content type. |

Sends `value` with the header `content-type: type`; without `type` it is `application/octet-stream`. A string is sent as UTF-8. Unlike `$.binary()`, it takes a string too and has no download name.

Example: CSV
```js
ROUTE('GET /export/', function($) {
	$.content('id,name\n1,Mug\n', 'text/csv');
});
```

### $.image(opt)

Type: `method`

Processes an image and sends it.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `opt` | `Object` | yes |  | The options. |

Loads an image stream, lets you change it and sends the result. `opt.ext` (required) is the extension of the output, `opt.load(next, opt)` calls `next(stream)` with the source, `opt.image(img, opt)` changes the image (see [Images](../../guides/images/)), `opt.cache` is a key to keep the result in the temporary directory, and `opt.date` a date for the HTTP cache.

Example: Example
```js
function thumbnail($) {
	$.image({
		ext: 'jpg',
		cache: 'thumb_' + $.params.id,
		load: function(next) {
			next(F.Fs.createReadStream(PATH.public('photos/' + $.params.id + '.jpg')));
		},
		image: function(img) {
			img.resize(200, 200);
		}
	});
}
```

### $.filefs(name, id, [download], [checkmeta])

Type: `method`

Sends a file from a file storage.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the file storage. |
| `id` | `String` | yes |  | The identifier of the file. |
| `download` | `Boolean|String` | no |  | Send as an attachment. |
| `checkmeta` | `Function` | no |  | A check of the metadata. |

Returns: `Object` The options passed to the storage.

Sends the file `id` from the file storage `name` (see [File storage](../../guides/file-storage/)). `download` sends it as an attachment, `true` with its stored name or a string for another name. `checkmeta` is a function that receives the metadata of the file and decides whether it can be sent.

Example: Example
```js
ROUTE('GET /files/{id}/', function($) {
	$.filefs('files', $.params.id);
});
```

### $.proxy(opt)

Type: `method`

Forwards the request to another server.

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

Sends the method, the headers, the body and the query string of the request to `opt` (a URL, or an object with `url`, `method`, `headers`, `timeout` (default 10000 ms) and `callback(err, response)`) and answers with the response of that server.

Example: Example
```js
ROUTE('GET /api/weather/', function($) {
	$.proxy('https://weather.example.com/today/');
});
```

### $.fallback(code, [error])

Type: `method`

Sends an error page.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `code` | `Number` | yes |  | The HTTP status code. |
| `error` | `String|Error` | no |  | The error for debug mode. |

When a route `#code` exists (for example `ROUTE('#404', fn)`), its action handles the request; the status stays `200` unless the action sets `$.response.status`. Otherwise it sends the built-in error page with the status `code`, or `$.invalid(code)` for XHR requests. `error` is shown on the page in debug mode.

Example: Example
```js
exports.install = function() {
	ROUTE('GET /secret/', function($) {
		$.fallback(404);
	});
	ROUTE('#404', function($) {
		$.view('404');
	});
};
```

### $.callback([err], [value])

Type: `method`

Answers from a callback.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `err` | `Error` | no |  | An error. |
| `value` | `Object` | no |  | The value to send. |

Returns: `Function` A callback when called without arguments.

Without arguments it returns a function `(err, response)` that calls `$.invalid(err)` or `$.json(response)`. With arguments it answers at once: `$.invalid(err)`, `$.success()` when `value` is `undefined`, or `$.json(value)`.

Example: Example
```js
ROUTE('GET /api/products/', function($) {
	NOSQL('products').find().callback($.callback());
});
```

### $.done([value])

Type: `method`

Returns a callback that answers with success.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object|Boolean` | no |  | The value, or `true` for the response of the callback. |

Returns: `Function` A callback.

The returned function `(err, response)` calls `$.invalid(err)` on an error, otherwise sends `{ success: true, value: value }`. Pass `true` to use the `response` of the callback as the value.

Example: Example
```js
ROUTE('POST /api/products/', function($) {
	NOSQL('products').insert($.body).callback($.done(true));
});
```

### $.successful(callback)

Type: `method`

Returns a callback that handles errors for you.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | yes |  | Called when there is no error. |

Returns: `Function` A callback.

The returned function `(err, a, b, c)` calls `$.invalid(err)` on an error, otherwise `callback(a, b, c)` with the controller as `this`.

Example: Example
```js
ROUTE('GET /api/products/', function($) {
	NOSQL('products').find().callback($.successful(function(response) {
		$.json(response);
	}));
});
```

### $.custom()

Type: `method`

Tells the framework you send the response yourself.

Marks the controller as finished so that no response method writes to it. Then write to `$.res` with the Node.js API.

Example: Example
```js
ROUTE('GET /events/', function($) {
	$.custom();
	$.res.writeHead(200, { 'content-type': 'text/event-stream' });
	$.res.write('data: hello\n\n');
});
```

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

Type: `method`

Reads or sets a cookie.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the cookie. |
| `value` | `String` | no |  | The value to set. |
| `expires` | `Date|String|Object` | no |  | The expiration, or the options. |
| `options` | `Object` | no |  | The options of the cookie. |

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

With only `name` it returns the decoded value of the cookie, or an empty string. With `value` it adds a `Set-Cookie` header (a cookie with the same name set earlier in the request is replaced) and returns the controller. `expires` is a `Date`, a string such as `'7 days'`, or the options object. The options are `expires`, `domain`, `path` (default `/`), `secure` (default from `$cookiesecure`), `httponly` and `samesite` (default from `$cookiesamesite`, `'Lax'`).

Example: Example
```js
function login($) {
	$.cookie('session', 'abc123', '7 days', { httponly: true, samesite: 'Strict' });
	$.success();
}

function profile($) {
	$.json({ session: $.cookie('session') });
}
```

### $.httpcache(date)

Type: `method`

Sets the HTTP cache headers.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `date` | `Date|String` | yes |  | The date of the last change. |

Sets `Last-Modified` to `date`, `ETag`, and `Expires` and `Cache-Control` when they are not set yet.

Example: Example
```js
function article($) {
	var updated = new Date(2025, 0, 1);
	if ($.notmodified(updated.toUTCString()))
		return;
	$.httpcache(updated);
	$.view('article');
}
```

### $.notmodified(date)

Type: `method`

Answers 304 when the client has the same version.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `date` | `String` | yes |  | The date of the last change as a UTC string. |

Returns: `Boolean` `true` when the 304 response was sent.

Compares `date` (a UTC string) with the `If-Modified-Since` header. When they are equal it sends `304 Not Modified` and returns `true`.

### $.hostname([path])

Type: `method`

Returns the protocol and the host.

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

Returns: `String` The URL.

Gives `protocol://host` of the request with an optional path appended.

Example: Example
```js
function share($) {
	$.json({ url: $.hostname('/products/' + $.params.id + '/') });
}
```

### $.href([key], [value])

Type: `method`

Returns the query string with one parameter changed.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String|Object` | no |  | The name of the parameter, or an object with the parameters to set. |
| `value` | `String|Number|Array|Object` | no |  | The new value. |

Returns: `String` The query string with `?`, or an empty string.

Without arguments it returns the query string of the request (`?page=2&sort=name`), or an empty string. `$.href(key, value)` returns it with `key` set to `value`; the other parameters stay. Without `value` the current value of `key` is kept. More arguments after `value` are names of parameters to remove. An array value writes the parameter once for each item and an object value is written as JSON. `$.href({ key: value, ... })` returns the URL of the request with the query string changed by the keys of the object. It works like `@{href()}` in views.

Example: Paging
```js
// GET /products/?page=2&sort=name
function products($) {
	$.json({
		next: $.href('page', 3),           // ?page=3&sort=name
		current: $.href()                  // ?page=2&sort=name
	});
}
```

Example: Remove a parameter, or change several
```js
// GET /products/?page=2&sort=name&q=pen
$.href('page', 1, 'sort');           // ?page=1&q=pen
$.href({ page: 1, sort: 'price' });  // /products/?page=1&sort=price&q=pen
```

### $.touch([url])

Type: `method`

Clears the cached state of a static file.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | no | `$.url` | The URL of the file. |

Returns: `Controller` The same controller.

Calls `TOUCH(url)`; without `url` it uses the URL of the request. Use it after the route changes a file in `public/`. Returns `$`.

Example: Example
```js
ROUTE('POST /api/theme/', function($) {
	F.Fs.writeFile(PATH.public('css/theme.css'), $.body.css || '', function(err) {
		if (err) {
			$.invalidsafe('The theme can\'t be saved', err);
			return;
		}
		$.touch('/css/theme.css');
		$.success();
	});
});
```

### $.action(name, model)

Type: `method`

Runs an action with this controller.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the action, for example `Products/list`. |
| `model` | `Object` | yes |  | The data for the action. |

Returns: `Object` The action instance.

Calls the action `name` (see [Actions](../../guides/actions/)) with `model` and the controller. Call `.autorespond()` on the result to answer the request with the output of the action.

Example: Example
```js
ROUTE('POST /api/orders/', function($) {
	$.action('Orders/create', $.body).autorespond();
});
```

### $.authorize([callback])

Type: `method`

Runs the authorization delegate manually.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | no |  | Receives `(err, user)`. |

Returns: `Promise` When called without a callback.

Calls your authorization delegate for this request. When it returns a user, `$.user` is set. The callback is `(err, user)`; without a callback the method returns a `Promise` with the user (or `undefined`).

Example: Example
```js
ROUTE('GET /api/me/', async function($) {
	var user = await $.authorize();
	$.json({ signed: !!user });
});
```

### $.csrf()

Type: `method`

Creates a CSRF token.

Returns: `String` The token.

Returns a token bound to the IP address and the browser of the client, valid for the time in `$csrfexpiration` (default `30 minutes`). It needs the configuration key `secret_csrf`; without it the token is an empty string.

Example: Example
```js
ROUTE('GET /form/', function($) {
	$.view('form', { token: $.csrf() });
});
```

### $.autoclear([value])

Type: `method`

Keeps or removes uploaded files after the response.

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

Uploaded files are removed when the response ends. `$.autoclear(false)` keeps them, for example when you process them later.

### $.cancel()

Type: `method`

Stops the processing of the request in an event.

Call it in `ON('request', fn)` or `ON('controller', fn)` when the handler answers the request itself.

Example: Example
```js
ON('request', function($) {
	if ($.url === '/health/') {
		$.cancel();
		$.plain('OK');
	}
});
```

### HttpFile

Type: `class`

An uploaded file in `$.files`.

Properties: `name` (the field of the form), `filename`, `type` (the content type), `size` (bytes), `extension`, `width` and `height` (images), `path` (the temporary file), and `isImage`, `isVideo`, `isAudio`.

Methods:

- `move(filename, [callback])` (also `rename()`) moves the file; without a callback it returns a `Promise`. A moved file is not removed after the response.
- `copy(filename, callback)` copies the file.
- `read([callback])` reads the file into a `Buffer`; without a callback it returns a `Promise`.
- `md5([callback])` computes the MD5 hash in hex; without a callback it returns a `Promise`.
- `stream([opt])` returns a read stream; `pipe(stream, [opt])` pipes the file into a stream.
- `image([shell])` returns an image object for [Images](../../guides/images/).
- `fs(storage, id, [callback])` saves the file into a [file storage](../../guides/file-storage/).

Example: Save to a file storage
```js
ROUTE('POST /upload/ <10MB', function($) {
	var file = $.files[0];
	file.fs('files', UID(), function(err, meta) {
		if (err)
			$.invalid(err);
		else
			$.success(meta.id);
	});
});
```
