# Multiple sessions

The JavaScript SDK supports multiple isolated sessions within a single connection, each with their own authentication and context.

The JavaScript SDK allows you to create multiple isolated sessions within a single connection. Each session maintains its own namespace, database, variables, and authentication state, while sharing the underlying connection to SurrealDB. This is useful when different parts of your application need to operate under different credentials or contexts simultaneously.

## API references

<table>
	<thead>
		<tr>
			<th scope="col">Method</th>
			<th scope="col">Description</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/javascript/api/core/surreal.md#newsession"> <code> db.newSession() </code></a></td>
			<td scope="row" data-label="Description">Creates a new isolated session on the connection</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/javascript/api/core/surreal-session.md#forksession"> <code> session.forkSession() </code></a></td>
			<td scope="row" data-label="Description">Creates a copy of a session, inheriting its state</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/javascript/api/core/surreal-session.md#closesession"> <code> session.closeSession() </code></a></td>
			<td scope="row" data-label="Description">Destroys a session and releases its resources</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/javascript/api/core/surreal-session.md#reset"> <code> session.reset() </code></a></td>
			<td scope="row" data-label="Description">Resets a session's state without destroying it</td>
		</tr>
	</tbody>
</table>

## Creating isolated sessions

Call `.newSession()` on a `Surreal` instance to create a new session. The new session starts with no namespace, database, or authentication, and must be configured independently.

```ts
const session = await db.newSession();

await session.use({ namespace: 'production', database: 'main' });

await session.signin({
    namespace: 'production',
    database: 'main',
    access: 'user_access',
    variables: {
        email: 'user@example.com',
        password: 'secure_password',
    },
});

const users = await session.select(new Table('users'));
```

Sessions support all the same query methods as the main `Surreal` instance, including `.query()`, `.select()`, `.create()`, `.update()`, `.delete()`, and [the rest of the query methods](/docs/reference/javascript/concepts/executing-queries.md).

## Forking an existing session

The `.forkSession()` method creates a new session that inherits the namespace, database, variables, and authentication state from the parent session. This is useful when you need a temporary context that starts with the same setup.

```ts
const primary = await db.newSession();
await primary.use({ namespace: 'app', database: 'main' });
await primary.signin({ username: 'admin', password: 'secret' });

const forked = await primary.forkSession();
await forked.use({ database: 'analytics' });
```

The forked session operates independently after creation. Changes to the parent session do not affect the fork, and vice versa.

## Automatic cleanup with await using

Sessions support the [await using](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/await_using) declaration. When you declare a session with `await using`, JavaScript automatically closes the session when execution leaves the current scope.

```ts
{
    await using session = await db.newSession();
    await session.use({ namespace: 'main', database: 'main' });
    const data = await session.select(new Table('users'));
}
```

This is equivalent to manually calling `session.closeSession()` in a `finally` block, but with cleaner syntax.

## Closing and resetting sessions

When you are done with a session, call `.closeSession()` to destroy it and release server-side resources.

```ts
const session = await db.newSession();

await session.select(new Table('users'));

await session.closeSession();
```

If you want to clear a session's state without destroying it, use `.reset()`. This removes all variables and invalidates authentication, but keeps the session alive for reuse.

```ts
await session.reset();
```

> [!NOTE]
> Using a session after it has been closed throws an [`InvalidSessionError`](/docs/reference/javascript/api/errors.md#invalidsessionerror).

## Reconnection behaviour

Sessions are automatically restored when the underlying connection reconnects after a drop. The SDK re-establishes each session's namespace, database, variables, and authentication state on the server. If a session used the `authentication` property from the original `.connect()` call, it will be re-authenticated automatically.

Sessions that were authenticated via `.signin()` or `.signup()` rely on the [`auth`](/docs/reference/javascript/api/core/surreal-session.md#event-auth) event for re-authentication. See [Authentication](/docs/reference/javascript/concepts/authentication.md#listening-to-authentication-events) for details.

## Subscribing to session events

Each session emits its own events, independent of other sessions and the main `Surreal` instance. You can subscribe to the `auth` and `using` events on any session.

```ts
session.subscribe('auth', (tokens) => {
    if (tokens) {
        console.log('Session authenticated');
    } else {
        console.log('Session signed out');
    }
});

session.subscribe('using', (using) => {
    console.log('Now using:', using.namespace, '/', using.database);
});
```

## Learn more

- [SurrealSession API reference](/docs/reference/javascript/api/core/surreal-session.md) for the full session interface
- [Surreal.newSession()](/docs/reference/javascript/api/core/surreal.md#newsession) for session creation details
- [Authentication](/docs/reference/javascript/concepts/authentication.md) for session-level authentication
- [Transactions](/docs/reference/javascript/concepts/transactions.md) for atomic operations within sessions
