> ## Documentation Index
> Fetch the complete documentation index at: https://docs.base44.com/llms.txt
> Use this file to discover all available pages before exploring further.

# actors

***

## Overview

Actors module for interacting with [actors](https://docs.base44.com/developers/backend/resources/actors/overview.md) from your app.

An actor is a long-running backend process that multiple clients connect to simultaneously. A session
is a running instance of an actor, identified by the actor name and a session ID. Each
session manages its own state, storage, and client connections independently.

The actors module provides the functionality to:

* Manage connections: [Open](#connect) and [close](#close) a WebSocket connection to a session.
* Exchange messages: [Send](#send) and [listen](#subscribe) for messages to and from an actor.
* Manage subscriptions: [Subscribe](#subscribe) and [unsubscribe](#unsubscribe) from actor messages without closing the connection.
* Call methods: [Run](#session-methods) a method you wrote in the actor on a session, without connecting to it.

For a sample flow, see
[connect a client to a session](https://docs.base44.com/developers/backend/resources/actors/sample-flows.md#connect-a-client-to-a-session).

### Authentication modes

This module is available to use with a client in all authentication modes:

* **Anonymous or user authentication** (`base44.actors`): Opens connections to sessions,
  exchanges messages, and calls an actor's methods.
* **[Service role authentication](https://docs.base44.com/developers/references/sdk/getting-started/client.md#service-role)**
  (`base44.asServiceRole.actors`): Calls an actor's methods. Server code can't hold a
  connection, so it can't connect to a session.

The actor receives each client's [identity](https://docs.base44.com/developers/backend/resources/actors/reference.md#connections)
when the client connects or calls a method. A client that hasn't logged in is anonymous, a client that
has [logged in](https://docs.base44.com/developers/references/sdk/docs/interfaces/auth.md) is authenticated, and server
code calling with the service role is `service`.

## Session methods

Represents a reference to an actor session, identified by actor name and session ID.

Call [`connect()`](#connect) to open a WebSocket and get a
[connection](https://docs.base44.com/developers/backend/resources/actors/overview.md#connections) that sends and receives
messages.

You can also call a method you wrote in the actor by name, such as a `kick()` method that
removes a user from a chat room. The method runs on the session even when no client is
connected, and the call resolves to its return value.

A method call takes one argument, which can be any JSON value. To pass several values, wrap
them in an object. The actor receives the caller's identity, which is the current user, or an
anonymous visitor when the client uses anonymous authentication. If the actor refuses the call,
the promise rejects with a
[`Base44Error`](https://docs.base44.com/developers/references/sdk/getting-started/work-with-sdk#error-handling).

To type a method's argument and return value, add the actor's `methods` to
[`ActorRegistry`](#actorregistry). To learn which methods an actor accepts, how arguments are
encoded, and the size and rate limits, see
[callable methods](https://docs.base44.com/developers/backend/resources/actors/reference.md#callable-methods).

#### Examples

```typescript Connect to a session and listen for messages theme={null}
const conn = base44.actors.chatRoom("session-1").connect();
conn.subscribe((msg) => {
  console.log(msg);
});
```

```typescript Call a method on a session theme={null}
const { kicked } = await base44.actors.chatRoom("session-1").kick({ userId: "user-123" });
```

### connect()

> **connect**(`options?`): `Connection`\<`N`>

Creates or returns the connection for this session.

Calling `connect()` again on the same session reference returns the same
connection until it closes.

For a sample flow, see
[connect a client to a session](https://docs.base44.com/developers/backend/resources/actors/sample-flows.md#connect-a-client-to-a-session).

#### Parameters

**options** `ActorConnectOptions`

Optional connection settings, such as a stable connection ID.

> [accordion] Properties
>
> **id** `string`
>
> Connection ID that the actor receives as `conn.id`.
>
> To let the actor recognize a client when it reconnects, use a stable
> value, such as an ID stored per browser tab. If you omit this property, the
> SDK generates a new connection ID.

#### Returns

[`Connection`](#connection-methods)

The connection for this actor session.

> [accordion] Properties
>
> **id** `string` *required*
>
> Connection ID that the actor receives as `conn.id`.

#### Example

```typescript Connect to a session theme={null}
const conn = base44.actors.chatRoom("session-1").connect({ id: "tab-1" });
```

## Connection methods

Represents a client's [WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API) connection to an actor session, returned after calling
[`connect()`](#connect). The WebSocket queues messages you send before it opens.

Learn more about
[connections](https://docs.base44.com/developers/backend/resources/actors/reference.md#connections).

### subscribe()

> **subscribe**(`callback`): `ActorSubscription`

Registers a listener for messages from the actor.

You can register multiple listeners on the same connection.

#### Parameters

**callback** `(data) =\> void` *required*

Callback that runs for each message the actor sends to this connection.

#### Returns

[`ActorSubscription`](#subscription-methods)

A subscription handle. Call `unsubscribe()` on it to remove this listener without closing the socket.

#### Example

```typescript Listen for messages from the actor theme={null}
const sub = conn.subscribe((msg) => {
  console.log(msg);
});

// Stop listening without closing the socket.
sub.unsubscribe();
```

***

### send()

> **send**(`data`): `void`

Sends a message to the actor.

The WebSocket queues messages until it opens. When you call [`close()`](#close),
the WebSocket drops any messages you send afterward.

#### Parameters

**data** `ToServerFor\<N\>` *required*

Message to send to the actor. The type comes from [`ActorRegistry`](#actorregistry) when you register the actor there.

#### Returns

`void`

#### Example

```typescript Send a message to the actor theme={null}
conn.send({ type: "message", text: "Hello" });
```

***

### close()

> **close**(): `void`

Closes the connection and removes all listeners.

You can call this method more than once. A connection also closes itself
when it fails permanently.

#### Returns

`void`

#### Example

```typescript Close the connection theme={null}
conn.close();
```

## Subscription methods

Represents a listener for messages from the actor, registered with
[`subscribe()`](#subscribe).

### unsubscribe()

> **unsubscribe**(): `void`

Removes this listener. Other listeners and the socket stay open.

#### Returns

`void`

#### Example

```typescript Remove a listener theme={null}
sub.unsubscribe();
```

## Type Definitions

### ActorClient

Selects a session for a named actor.

TypeScript infers message types and method types when you register the actor in
[`ActorRegistry`](#actorregistry). [`ActorNameRegistry`](#actornameregistry)
provides autocomplete for actor names only.

#### Parameters

#### instanceId

`string`

Session ID that identifies which session to connect to.

#### Returns

`ActorRef`\<`N`>

A [reference to the actor session](#session-methods).

#### Example

```typescript Select a session theme={null}
const session = base44.actors.chatRoom("session-1");
```

### ActorRegistry

Maps actor names to their message types and method types.

Extend this interface when you want typed actor messages and method calls without generating
types with the CLI:

* `toServer`: Defines incoming messages that a client sends to the actor.
* `toClient`: Defines outgoing messages that the actor sends to connected clients.
* `methods`: Defines the actor's methods that you can call on a session. Each entry's argument
  and return types become the types of the matching [method call](#session-methods).

To generate types from deployed actors, use the
[`types generate`](https://docs.base44.com/developers/references/cli/commands/types-generate) CLI command.

To learn how incoming and outgoing messages work, see
[message types](https://docs.base44.com/developers/backend/resources/actors/overview.md#message-types).

#### Example

```typescript Type messages for an actor theme={null}
declare module "@base44/sdk" {
  interface ActorRegistry {
    chatRoom: {
      toClient: { type: "joined" | "left" | "message"; userId?: string; from?: string; text?: string };
      toServer: { type: "message"; text: string };
      methods: { kick: (args: { userId: string }) => { kicked: boolean } };
    };
  }
}
```

### ActorNameRegistry

Lists actor names when your project includes types generated by the CLI
with [`types generate`](https://docs.base44.com/developers/references/cli/commands/types-generate).

The generated names provide autocomplete for deployed actors. To define
incoming and outgoing message types manually, augment [`ActorRegistry`](#actorregistry).


## Related topics

- [Panoramica degli actor](https://docs.base44.com/it/developers/backend/resources/actors/overview.md)
- [Creare un actor](https://docs.base44.com/it/developers/backend/resources/actors/create-actor.md)
- [File e codice degli actor](https://docs.base44.com/it/developers/backend/resources/actors/reference.md)
- [Actor: flussi di esempio](https://docs.base44.com/it/developers/backend/resources/actors/sample-flows.md)
- [Struttura del progetto](https://docs.base44.com/it/developers/backend/overview/project-structure.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.