---
title: Message Service and APIs
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/message-service-and-apis/
updated: 2026-11-16T15:41:15.818Z
---

# Message Service and APIs

> TMS functions, the TMS client, API(), NEWAPI(), TotalAPI() and API routes.

TMS channels are declared with `NEWPUBLISH()`, `NEWSUBSCRIBE()` and `NEWCALL()`, and another app connects with `TMSCLIENT()`. `API()` calls providers registered with `NEWAPI()`. The guide [Message Service and APIs](../../guides/message-service-and-apis/) explains how the parts work together; this page is the exact reference.

## API

### NEWPUBLISH(name, [schema])

Type: `method` · Since: `0.0.42`

Declares a TMS channel that your app publishes to.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Name of the channel |
| `schema` | `String|Object` | no |  | An inline declaration (`id:UID, name:String`), a JSON schema object with `$id`, or the name of a JSON schema or a Total.js schema. Leave it out to remove the channel |

Returns: `undefined`

The channel and its JSON schema are sent to every TMS client in the `meta` message. A schema name that does not exist throws an error. Without `schema` (or with `null`), the channel is removed. Redeclaring an existing channel keeps its first schema.

Example: Declare a channel
```js
NEWPUBLISH('orders_created', 'id:UID, total:Number, email:Email');
```

Example: Remove a channel
```js
NEWPUBLISH('orders_created');
```

### PUBLISH(name, data)

Type: `method` · Since: `0.0.42`

Sends a message to TMS clients subscribed to the channel.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Name of a channel declared with `NEWPUBLISH()` |
| `data` | `Object` | yes |  | The message |

Returns: `undefined`

Only clients that announced a subscription to `name` receive the message. It does nothing when no TMS client is connected or when `name` was not declared with `NEWPUBLISH()`. The data is not validated on the server; `TMSCLIENT()` converts it with the channel schema.

Example: Publish after an insert
```js
NEWPUBLISH('orders_created', 'id:UID, total:Number');

function created(order) {
	PUBLISH('orders_created', { id: order.id, total: order.total });
}
```

### NEWSUBSCRIBE(name, [schema], [callback])

Type: `method` · Since: `0.0.42`

Declares a TMS channel that clients publish to and your app receives.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Name of the channel |
| `schema` | `String|Object` | no |  | An inline declaration (`id:UID, name:String`), a JSON schema object with `$id`, or the name of a JSON schema or a Total.js schema. Leave it out to remove the channel |
| `callback` | `Function` | no |  | A handler `function(data, client)` |

Returns: `undefined`

Incoming messages of the channel are validated with `schema`; invalid messages are dropped and valid ones go to the handlers added with `SUBSCRIBE()`. `callback` is a shortcut for `SUBSCRIBE(name, callback)`. Without `schema`, the channel is removed (its handlers stay).

Example: Declare a channel with a handler
```js
NEWSUBSCRIBE('products_updated', '*id:UID, price:Number', function(data, client) {
	NOSQL('products').modify({ price: data.price }).where('id', data.id);
});
```

### SUBSCRIBE(name, callback)

Type: `method` · Since: `0.0.42`

Adds a handler for messages of a TMS subscribe channel.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Name of the channel |
| `callback` | `Function` | yes |  | `function(data, client)` |

Returns: `undefined`

The handler receives the validated data and the WebSocket client that sent it. A channel can have many handlers. Messages arrive only for channels declared with `NEWSUBSCRIBE()`. The app announces its subscriptions to the clients in the next `meta` message.

Example: Add a handler
```js
NEWSUBSCRIBE('products_updated', '*id:UID, price:Number');

SUBSCRIBE('products_updated', function(data, client) {
	console.log(client.ip, 'updated', data.id);
});
```

### UNSUBSCRIBE(name, [callback])

Type: `method` · Since: `0.0.42`

Removes one handler or all handlers of a TMS channel.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Name of the channel |
| `callback` | `Function` | no |  | The handler to remove |

Returns: `Boolean` `true` when something was removed

With `callback`, only that handler is removed (pass the same function you gave to `SUBSCRIBE()`). Without it, all handlers of the channel are removed.

Example: Remove a handler
```js
function onupdate(data) {
	console.log(data);
}

SUBSCRIBE('products_updated', onupdate);
UNSUBSCRIBE('products_updated', onupdate);
```

### NEWCALL(name, schema, [callback])

Type: `method` · Since: `0.0.45`

Registers a TMS remote call that clients can run.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Name of the call |
| `schema` | `String|Object` | yes |  | An inline declaration (`id:UID, name:String`), a JSON schema object with `$id`, or the name of a JSON schema or a Total.js schema, or `*Schema --> action` |
| `callback` | `Function|String` | no |  | `function(data, next, client)` or an operation name |

Returns: `undefined`

The data of a call is validated with `schema`; a validation error goes back to the client. `callback(data, next, client)` answers with `next(err, response)`. Instead of a function, `callback` can be the name of an operation. With no callback and a schema like `*Orders --> create`, the call runs that schema action. `NEWCALL(name, null)` removes the call. A call that does not exist answers with error `404`.

Example: A call with a function
```js
NEWCALL('products_detail', '*id:UID', function(data, next, client) {
	NOSQL('products').one().where('id', data.id).callback(next, 404);
});
```

Example: A call that runs a schema action
```js
NEWCALL('orders_create', '*Orders --> create');
```

### { type: 'meta' | 'publish' | 'subscribe' | 'subscribers' | 'call' | 'ping' }

Type: `type`

The JSON messages exchanged on the TMS endpoint.

Returns: `Object`

Every message is a JSON object with `type`:

- `meta` (server to client): `name`, `publish`, `subscribe` and `call` (arrays of `{ id, schema }`) and `subscribers` (channels the app subscribes to). Sent after connecting and one second after any change.
- `publish` (server to client): `{ id, data }`, sent by `PUBLISH()`.
- `subscribe` (client to server): `{ id, data }`, a message for a `NEWSUBSCRIBE()` channel.
- `subscribers` (client to server): `{ subscribers: [names] }`, the channels the client wants to receive.
- `call` (both ways): `{ id, data, callbackid }`; the answer adds `success: true` or `error: true`.
- `ping`: answered with `pong`.

You need this only to write a TMS client without `TMSCLIENT()`. A new client starts with an empty list of subscriptions and receives `publish` messages only for the channels it lists in `subscribers`.

Example: A client subscribes and calls
```json
{ "type": "subscribers", "subscribers": ["orders_created"] }
{ "type": "call", "id": "products_detail", "data": { "id": "1a2b3c" }, "callbackid": "1" }
```

### secret_tms : token

Type: `config` · Since: `0.0.42`

The token that TMS clients must send.

Returns: `String`

Clients send it in the `x-token` header. A wrong token closes the connection with code `4001`; more than five failed attempts from one IP address block it until the daily reset. Changing the token closes the TMS connections. The value can also be a number. Default: empty, every client is accepted.

Example: Protect TMS
```text
allow_tms  : true
secret_tms : my-secret-token
```

### default_tms_maxlength : 1024

Type: `config` · Since: `0.0.80`

Maximum size of a TMS message in kB.

Returns: `Number`

Applied to the WebSocket route of the TMS endpoint (`default_tms_url`). Default: `1024` (1 MB).

Example: Allow bigger messages
```text
default_tms_maxlength : 5120
```

### publish: true | String

Type: `property` · Since: `0.0.72`

Option of schema.action() and NEWACTION() that declares a TMS publish channel.

Returns: `Boolean|String`

The channel is named after the action: `Schema.action` for `schema.action()`, the action name for `NEWACTION()`. `true` uses the `input` (or `output`) of the action as the channel schema. A string is its own inline schema; a string that starts with `+` adds its fields to the input. Send messages with `$.publish()`.

Example: Publish from an action
```js
NEWSCHEMA('Orders', function(schema) {
	schema.action('create', {
		input: '*email:Email, *total:Number',
		publish: '+id:UID',
		action: function($, model) {
			model.id = UID();
			$.publish(model);
			$.success(model.id);
		}
	});
});
```

### $.publish(value)

Type: `method` · Since: `0.0.72`

Publishes a message to the TMS channel of the current action.

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

Returns: `SchemaOptions` The same `$`, for chaining

Works in actions declared with the `publish` option; the channel name is the action ID. Like `PUBLISH()`, it does nothing without a connected TMS client. The fields of `value` are copied to a new object.

Example: Publish and answer
```js
action: function($, model) {
	$.publish(model).success();
}
```

### TMSCLIENT(url, [token], [callback])

Type: `method` · Since: `0.0.45`

Connects to the TMS endpoint of another Total.js app.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | URL of the TMS endpoint, for example `https://app.example.com/$tms/` |
| `token` | `String` | no |  | The server `secret_tms` |
| `callback` | `Function` | no |  | `function(err, client, meta)` |

Returns: `WebSocketClient` The TMS client

Returns a WebSocket client (see [WebSockets](../../guides/websockets/)) with the extra methods `subscribe()`, `publish()` and `call()`. An `http` URL is changed to `ws` and the client reconnects when the server goes down. `token` is sent in the `x-token` header. `callback(err, client, meta)` runs once, after the first `meta` message.

Example: Connect
```js
TMSCLIENT('https://orders.example.com/$tms/', 'my-secret-token', function(err, client, meta) {
	console.log('Connected to', meta.name);
});
```

### client.subscribe(name, callback)

Type: `method` · Since: `0.0.45`

Receives messages of a publish channel of the server.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Name of a channel declared with `NEWPUBLISH()` on the server |
| `callback` | `Function` | yes |  | `function(data)` |

Returns: `undefined`

The data is converted with the channel schema from `meta`, and handlers run only for channels the server publishes. The client sends its list of subscriptions to the server shortly after each call and again after reconnecting.

Example: Subscribe
```js
client.subscribe('orders_created', function(data) {
	console.log(data.id, data.total);
});
```

### client.publish(name, data)

Type: `method` · Since: `0.0.45`

Sends a message to a subscribe channel of the server.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Name of a channel declared with `NEWSUBSCRIBE()` on the server |
| `data` | `Object` | yes |  | The message |

Returns: `undefined`

The server validates it with the schema of its `NEWSUBSCRIBE()` channel. Nothing is sent while the client is not connected.

Example: Publish
```js
client.publish('products_updated', { id: '1a2b3c', price: 99 });
```

### client.call(name, data, [callback], [timeout])

Type: `method` · Since: `0.0.45`

Runs a remote call registered on the server with NEWCALL().

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Name of the call |
| `data` | `Object` | yes |  | Data of the call |
| `callback` | `Function` | no |  | `function(err, response)` |
| `timeout` | `Number` | no | `10000` | Timeout in milliseconds |

Returns: `Promise|undefined` A promise when there is no callback

`callback(err, response)` receives the response; errors from the server arrive as an `ErrorBuilder`. Without a callback it returns a promise. Before the connection is ready, it fails with `TMS is offline`; without an answer in time, with `408: Timeout`.

Example: Call with a callback
```js
client.call('products_detail', { id: '1a2b3c' }, function(err, response) {
	console.log(err, response);
});
```

Example: Call with await
```js
var product = await client.call('products_detail', { id: '1a2b3c' });
```

### client.ready

Type: `property` · Since: `0.0.45`

`true` when the client is connected and has received the meta.

Returns: `Boolean`

It becomes `false` when the connection closes and `true` again after the next `meta`.

Example: Check the state
```js
if (client.ready)
	client.publish('products_updated', { id: id, price: price });
```

### client.meta

Type: `property` · Since: `0.0.45`

The last meta message received from the server.

Returns: `Object`

It contains the server `name` and the `publish`, `subscribe` and `call` lists with JSON schemas. See TMS messages.

Example: List the remote calls
```js
console.log(client.meta.call.map(item => item.id));
```

### client.on('meta', function(meta) {})

Type: `event` · Since: `0.0.45`

Emitted each time the server sends its meta.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `meta` | `Object` | yes |  | The meta message |

The server sends the meta after connecting, after reconnecting and after any change of its channels or calls.

Example: Watch changes
```js
client.on('meta', function(meta) {
	console.log('Server publishes', meta.publish.length, 'channels');
});
```

### client.on('ready', function() {})

Type: `event` · Since: `0.0.45`

Emitted after each meta message, when the client is ready.

Use it to run code after every reconnection; the `TMSCLIENT()` callback runs only the first time.

Example: After every connection
```js
client.on('ready', function() {
	console.log('TMS ready');
});
```

### NEWAPI(name, [callback])

Type: `method` · Since: `0.0.65`

Registers an API provider used by API().

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Name of the provider, several separated by commas, or `*` |
| `callback` | `Function` | no |  | `function(opt, next)`. Leave it out to remove the provider |

Returns: `undefined`

`callback(opt, next)` runs for each `API()` call with this name, with the call object as `this`. `opt` has `name`, `schema`, `data`, `controller`, and `files` and `output` when set. Answer with `next(err, response)`. `name` is not case-sensitive, can list several names separated by commas, and `*` registers a fallback for unknown names. A name without `callback` removes the provider. The provider `TotalAPI` (alias `TAPI`) is registered by default.

Example: A custom provider
```js
NEWAPI('Payments', function(opt, next) {
	RESTBuilder.POST('https://payments.example.com/' + opt.schema + '/', opt.data).callback(next);
});
```

### API(name, schema, [data], [$])

Type: `method`

Sends a request to a registered API provider.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Name of the provider, for example `TotalAPI` |
| `schema` | `String` | yes |  | The endpoint or operation of the provider |
| `data` | `Object` | no |  | Data of the request |
| `$` | `Object` | no |  | A controller or `$`, passed to the provider as `opt.controller` |

Returns: `APICall` The call object

Returns a call object. The request starts on the next tick, so chain the options and the callback right away. Without a provider for `name` (and no `*` provider), the call fails with `API is not initialized`.

Example: Total API
```js
API('TotalAPI', 'check').callback(function(err, response) {
	console.log(err, response);
});
```

Example: Inside an action
```js
action: function($, model) {
	API('Payments', 'charge', model).callback($);
}
```

### api.callback(fn)

Type: `method`

Sets the callback of the API call.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function|Object` | yes |  | `function(err, response)`, or `$` |

Returns: `APICall` The call, for chaining

`fn(err, response)`. Pass `$` (or an object with `callback`) to answer an action with the result.

Example: With $
```js
API('TotalAPI', 'check').callback($);
```

### api.promise([$])

Type: `method`

Returns a promise with the response.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `$` | `Object` | no |  | An object with `invalid()`, such as `$` |

Returns: `Promise` The response

With `$`, an error is sent with `$.invalid()` and the promise never resolves; without it the promise is rejected with an error named `API(name --> schema)`.

Example: Await the response
```js
var response = await API('TotalAPI', 'check').promise($);
```

### api.output(type)

Type: `method`

Sets the output format of the response.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `type` | `String` | yes |  | The output format |

Returns: `APICall` The call, for chaining

The provider reads it as `opt.output`. The `TotalAPI` provider supports `json` (default), `html`, `text`, `plain`, `base64`, `buffer` or `binary`, `stream`, and `#name id filename` to save the response to a FileStorage.

Example: Save the response to FileStorage
```js
API('TotalAPI', 'service_name', data).output('#invoices ' + UID() + ' invoice.pdf').callback(console.log);
```

### api.file(filename, path, [name])

Type: `method`

Adds a file to the request.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | yes |  | Name of the file |
| `path` | `String` | yes |  | Path to the file on disk |
| `name` | `String` | no | `'file' + index` | Name of the form field |

Returns: `APICall` The call, for chaining

Adds `{ name, filename, path }` to `opt.files`. The `TotalAPI` provider then sends the data and files as a multipart request.

Example: Send a file
```js
API('Payments', 'upload', { id: id }).file('scan.png', PATH.public('scan.png')).callback(console.log);
```

### api.error(err, [reverse])

Type: `method`

Turns an empty response into an error.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `err` | `String` | yes |  | The error |
| `reverse` | `Boolean` | no | `false` | Fail when the response is not empty |

Returns: `APICall` The call, for chaining

An empty response (or an empty array) becomes `err`. With `reverse`, a non-empty response becomes the error instead. Alias: `api.err()`.

Example: Require a response
```js
API('Payments', 'detail', { id: id }).error('404').callback($);
```

### api.fail(fn)

Type: `method`

Runs a function when the call fails.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `function(err)` |

Returns: `APICall` The call, for chaining

`fn(err)` runs in addition to the callback.

Example: Log errors
```js
API('Payments', 'charge', model).fail(console.error).data(console.log);
```

### api.data(fn)

Type: `method`

Runs a function with the response when the call succeeds.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `function(response)` |

Returns: `APICall` The call, for chaining

`fn(response)` runs in addition to the callback, only without an error.

Example: Use the response
```js
API('TotalAPI', 'check').data(function(response) {
	console.log(response);
});
```

### api.audit($, [message], [type])

Type: `method`

Writes an audit log entry when the call succeeds.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `$` | `Object` | yes |  | The `$` of an action or operation |
| `message` | `String` | no |  | The audit message |
| `type` | `String` | no |  | Type of the entry |

Returns: `APICall` The call, for chaining

Calls `$.audit(message, type)`. Variables in the message are filled from the data of the call with `$.variables()`.

Example: Audit a payment
```js
API('Payments', 'charge', model).audit($, 'Charged {amount}').callback($);
```

### api.controller($)

Type: `method`

Passes a controller to the provider.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `$` | `Object` | yes |  | A controller or `$` |

Returns: `APICall` The call, for chaining

Sets `opt.controller` to `$.controller` (or `$` itself).

Example: Pass the controller
```js
API('Payments', 'charge', model).controller($).callback($);
```

### api.debug()

Type: `method`

Logs the result of the call to the console.

Returns: `APICall` The call, for chaining

Prints the provider name, the schema, the error and the response.

Example: Debug a call
```js
API('TotalAPI', 'check').debug().callback(NOOP);
```

### TotalAPI([token], type, data, [callback], [filename])

Type: `method`

Sends one request to Total API.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `token` | `String` | no | `CONF.totalapi` | Total API token |
| `type` | `String` | yes |  | The Total API service |
| `data` | `Object` | yes |  | Data of the request |
| `callback` | `Function|Controller` | no |  | `function(err, response)`, or a controller to stream a file |
| `filename` | `String` | no |  | File name of a streamed file |

Returns: `Promise|undefined` A promise when there is no callback

Posts `data` to `https://{default_tapi}.api.totaljs.com/{type}/`. The token defaults to `totalapi` (or `secret_totalapi`). A non-object `data` is sent as `{ value: data }`. Without a callback it returns a promise. A binary response goes to the callback as a stream, or, when `callback` is a controller, is sent to the client with `filename`. With `allow_totalapi: false`, only `check` works; other calls fail with `totalapi_inactive`.

Example: Check the token
```js
TotalAPI('check', {}, function(err, response) {
	console.log(err, response);
});
```

Example: Await
```js
var response = await TotalAPI('check', {});
```

### totalapi : token

Type: `config`

The Total API token.

Returns: `String`

Used by `TotalAPI()`, the `TotalAPI` provider of `API()` and the audit logger. `secret_totalapi` is read when `totalapi` is empty.

Example: Set the token
```text
totalapi : my-totalapi-token
```

### default_tapi : eu

Type: `config`

The Total API server region.

Returns: `String`

Requests go to `https://{default_tapi}.api.totaljs.com/`. Default: `eu`.

Example: Region
```text
default_tapi : eu
```

### allow_totalapilogger : false

Type: `config` · Since: `0.0.42`

Sends audit logs to Total API.

Returns: `Boolean`

When `true` and a Total API token is set, audit entries are sent to the Total API `logger` service instead of `DEF.onAudit()`. Default: `false`.

Example: Enable
```text
totalapi             : my-totalapi-token
allow_totalapilogger : true
```

### ROUTE('[+|-]API /url/ [+|#|-]name[/{param}] [*Schema --> action]', [fn], [flags])

Type: `method`

Declares an API route: one POST URL that runs actions by name.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | The route declaration |
| `fn` | `Function` | no |  | A custom handler with the controller as `this` |
| `flags` | `Array` | no |  | Route flags |

Returns: `Object` The route

The client posts `{ "schema": "name/param?query", "data": {} }` to the URL. The sign before the name sets how the data is handled: `+` validates it like `POST`, `#` like `PATCH` (partial), `-` sends none like `GET`. URL parameters can have a type after `:` (`uid`, `number`, `guid`, `date`); the first becomes `$.id`. Without `*Schema --> action`, the route runs the action with the same name (`--> name`). `+API` requires a signed-in user and `-API` an anonymous one. Unknown names answer `404`, invalid parameters `400`.

Example: API routes
```js
exports.install = function() {
	ROUTE('+API /api/ -orders_list      *Orders --> list');
	ROUTE('+API /api/ +orders_create    *Orders --> create');
	ROUTE('+API /api/ -orders_read/{id} *Orders --> read');
};
```

Example: A request
```json
{ "schema": "orders_read/1a2b3c?fields=id,total" }
```

### ROUTE('API /url/ name', function() {})

Type: `method` · Since: `0.0.95`

An API route action handled by your own function.

Instead of `*Schema --> action`, pass a function. It runs with the controller as `this`; `this.params` holds the URL parameters, `this.body` the posted `{ schema, data }` and `this.id` the first parameter. Answer with any controller method.

Example: A custom action
```js
exports.install = function() {
	ROUTE('API /api/ -ping', function() {
		this.success();
	});
	ROUTE('API /api/ +echo', function() {
		this.json(this.body.data);
	});
};
```
