
# Sessions

A session keeps data for one client across requests, such as a shopping cart or the logged-in user. The data stays on the server; the client only holds a random id in a cookie (`JSESSIONID` by default) and sends it back with each request. Code that has the request gets the session with `request.getSession()`.

## Why

HTTP forgets everything between two requests. Browsers need the server to remember who they are. A session does this without putting the data in the browser, where the user could read or change it.

Use sessions for browsers: carts, wizards that span several pages, a login with a form. APIs called by programs usually send a token with each request (a bearer token) and need no session. The security starter keeps the logged-in user in the session after a form or OAuth2 login, and creates a session only at a login.

## Example

```dart
import 'package:spring_boot_starter_web/spring_boot_starter_web.dart';

@RestController()
@RequestMapping('/cart')
class CartController {
  // Each visitor has a cart that lives as long as the session.
  @PostMapping('/items')
  List<String> add(ServerHttpRequest request, @RequestParam() String item) {
    final session = request.getSession()!;
    final cart = session.getAttribute('cart') as List<String>? ?? [];
    final updated = [...cart, item];
    session.setAttribute('cart', updated);
    return updated;
  }

  // Look without creating a session: a visitor without one has no cart.
  @GetMapping('/items')
  List<String> items(ServerHttpRequest request) =>
      request.getSession(create: false)?.getAttribute('cart') as List<String>? ??
      const [];

  // Empty the cart and forget the visitor.
  @PostMapping('/clear')
  void clear(ServerHttpRequest request) =>
      request.getSession(create: false)?.invalidate();
}

@RestController()
class LoginController {
  @PostMapping('/login')
  Future<void> login(ServerHttpRequest request, @RequestParam() String user) async {
    // ... check the password ...
    // A new id after the login: an id someone saw before stops working.
    if (request.getSession(create: false) != null) {
      await request.changeSessionId();
    }
    request.getSession()!.setAttribute('user', user);
  }
}
```

```yaml
# lib/resources/application.yaml
server:
  session:
    timeout: 15m             # without a request; 30m by default
    max-sessions: 50000      # 10000 by default; -1: no limit
    cookie:
      name: SHOPSESSION      # JSESSIONID by default
      same-site: strict      # lax by default
      secure: true           # by default: secure when the request was
```

The first request that calls `getSession()` gets:

```text
Set-Cookie: SHOPSESSION=k3Jx...; Path=/; Secure; HttpOnly; SameSite=Strict
```

## Getting the session

`request.getSession()` and the other members below are an extension on `ServerHttpRequest`. They work in any code that has the request: a controller (take a `ServerHttpRequest` parameter), a filter that runs after the session filter, an interceptor, or anywhere through `RequestContextHolder.currentRequest`.

| Member | Meaning |
|---|---|
| `HttpSession? getSession({bool create = true})` | The request's session. Without one, `create: true` (the default) makes a new session and sends its cookie with the response; `create: false` returns `null`. Works with a repository that answers at once, as the in-memory one does. |
| `Future<HttpSession?> getSessionAsync({bool create = true})` | The same for any repository, also one that answers with `Future`s. |
| `Future<String> changeSessionId()` | Gives the session a new id, keeps its values, sends the new id in the cookie, and returns it. Throws a `StateError` when the request has no session. |
| `String? requestedSessionId` | The id the client sent in its cookie, live or not; `null` without a cookie. |
| `bool isRequestedSessionIdValid` | Whether that id names the session this request uses: `false` when it is unknown, expired, invalidated, or changed during this request. |

Rules:

- A handler cannot take an `HttpSession` parameter. Take the `ServerHttpRequest` and call `getSession()`.
- Without the starter's session filter (a request built by hand, outside the dispatcher), these members throw a `StateError`.
- With a repository that answers with `Future`s, `getSession()` throws a `StateError` when it would have to create a session: use `getSessionAsync()`.
- **The cookie goes out with the response headers.** Create the session before the response starts: before a stream or a `StreamingResponseBody` writes its first bytes. A session created after that gets no cookie (a warning is logged).
- **The client never chooses an id.** An unknown id from a cookie is ignored, and a session created later gets a new random one, so an attacker cannot plant an id in a victim's browser (session fixation). Ids longer than 128 characters are ignored without a lookup.

## `HttpSession`

| Member | Meaning |
|---|---|
| `id` | The id the cookie carries: 256 random bits, base64url (43 characters). Changes with `changeSessionId()`. |
| `creationTime` | When the session was created. |
| `lastAccessedTime` | When a request last came with this session. The timeout counts from here. |
| `maxInactiveInterval` | How long the session lives without a request (`server.session.timeout`). Set it to change the timeout of this session only. Zero or negative: it never expires. |
| `isNew` | Whether this request created the session, so the client does not know it yet. |
| `getAttribute(name)` | The value stored under `name`, or `null`. |
| `setAttribute(name, value)` | Stores `value`; `null` removes the name. The in-memory repository keeps the object itself, not a copy. |
| `removeAttribute(name)` | Removes the value. |
| `attributeNames` | The names of the stored values (a copy). |
| `invalidate()` | Ends the session, as a logout does: its values are dropped and its id is never accepted again. |
| `isInvalidated` | Whether the session has ended: invalidated or expired. |

- Using an invalidated session (`getAttribute`, `setAttribute`, `removeAttribute`, `attributeNames`, `invalidate`) throws a `StateError`.
- After `invalidate()`, the cookie stays in the browser; its next request simply has no session. `getSession()` in the same request creates a new one.
- Store values that the repository can keep. In memory, anything works. A repository that writes to a database needs values it can serialize.

## After a login: `changeSessionId`

Before a login, the session id may have been seen by someone else: on a shared computer, in a log, through a script on a page. After the login, the session holds the user. Call `await request.changeSessionId()` right after a successful login: the session keeps its data (the cart survives), but the old id stops working, and the response sends the new one. The security starter does this for its logins, unless `sessionFixation(changeSessionId: false)` turns it off.

## Expiry and the session limit

- A session expires after `maxInactiveInterval` without a request. An expired session is removed when a request finds it, and all expired ones at most once a minute when a session is created.
- At most `server.session.max-sessions` sessions are kept. At the limit, a new session first removes every expired one. When the store is still full, the new session is **refused**: `getSession()` throws a `TooManyActiveSessionsException`, the request gets `503 Service Unavailable`, and a warning is logged (`Session limit 10000 reached: refused a new session (raise server.session.max-sessions)`), at most once a minute. A live session is never removed to make room.
- The limit keeps clients from filling the memory by opening sessions. With the security starter, anonymous requests do not create sessions; raise the limit when logged-in users alone fill it.

## Properties

### `server.session.timeout`

| Type | Default |
|---|---|
| `Duration` | `30m` |

How long a session lives without a request. A plain number is **seconds** (`1800`); a unit works too (`15m`, `8h`). Each request with the session starts the time again. Shorten it for sensitive applications (banking: `5m`); lengthen it for carts that should survive a long pause. Zero or negative: sessions never expire (they are then only removed by `invalidate()`, and count against `max-sessions` forever).

```yaml
server:
  session:
    timeout: 15m
```

### `server.session.max-sessions`

| Type | Default |
|---|---|
| `int` | `10000` |

The most sessions kept at once by the in-memory repository; `-1` for no limit. What happens at the limit is described above. Raise it when you have more concurrent logged-in users; estimate the memory: each session holds its attributes. A repository bean of your own does its own accounting.

```yaml
server:
  session:
    max-sessions: 50000
```

### `server.session.cookie.name`

| Type | Default |
|---|---|
| `String` | `JSESSIONID` |

The name of the session cookie. Change it when two applications on the same host would share the name, or to not tell the world which technology runs the site. A blank value is the default.

### `server.session.cookie.domain`

| Type | Default |
|---|---|
| `String` | none |

The cookie's `Domain`. Without it the browser sends the cookie back only to the host that set it, which is the safest choice. Set it (`example.com`) to share the session between subdomains (`shop.example.com`, `account.example.com`) served by the same session store.

### `server.session.cookie.path`

| Type | Default |
|---|---|
| `String` | the context path, or `/` |

The cookie's `Path`: the paths the browser sends it to. By default, `server.context-path` (`/shop`) or `/`. Narrow it when only part of the site uses sessions.

### `server.session.cookie.http-only`

| Type | Default |
|---|---|
| `bool` | `true` |

Whether the cookie is `HttpOnly`, hidden from the page's scripts. Keep it `true`: a script injected into a page (XSS) then cannot steal the session id.

### `server.session.cookie.secure`

| Type | Default |
|---|---|
| `bool` | not set |

Whether the cookie is `Secure`, sent back over HTTPS only. Not set: decided per request, secure when the request came over HTTPS. Behind a reverse proxy that terminates TLS, the server sees `http`: either set `server.forward-headers-strategy` so the request knows it was HTTPS (see [Behind a reverse proxy](server/reverse-proxy.md)), or set this key to `true`. Set `false` only for local development over plain HTTP, where it is not needed anyway.

### `server.session.cookie.same-site`

| Type | Default |
|---|---|
| `lax`, `strict`, `none`, `unset` | `lax` |

The cookie's `SameSite` attribute, which decides whether the browser sends the cookie with requests that come from other sites.

| Value | Header | Meaning |
|---|---|---|
| `lax` | `SameSite=Lax` | Sent with requests of the site, and with top-level navigations from other sites (a link). Not with a cross-site `POST` or `fetch`. Protects against most CSRF. |
| `strict` | `SameSite=Strict` | Sent only with requests of the site. A link from another site arrives without the session. |
| `none` | `SameSite=None` | Sent with every request, also cross-site. Browsers require `Secure` with it. Needed when another site embeds yours (an iframe) or calls it with credentials. |
| `unset` | none | No attribute: the browser's default (Lax in current browsers). |

Another value stops the start.

```yaml
server:
  session:
    cookie:
      same-site: none
      secure: true
```

## Where sessions live

The starter declares three beans:

| Bean | Type | Role |
|---|---|---|
| `httpSessionRepository` | `InMemoryHttpSessionRepository` | Keeps the sessions, unless the application declares an `HttpSessionRepository`. |
| `httpSessionManager` | `HttpSessionManager` | Reads the cookie, finds the session, writes the cookie. |
| `httpSessionFilter` | `HttpSessionFilter` | Attaches the session to each request, at order `-1000`, before the security filter chain (`-100`). |

Sessions in memory are lost when the process stops and are not shared between several instances of the application. To keep them in a database or Redis, so they survive a restart or are shared behind a load balancer, declare your own `HttpSessionRepository` bean; the in-memory one backs off.

| `HttpSessionRepository` | Meaning |
|---|---|
| `createSession()` | A new, empty `StoredHttpSession` with a fresh random id (`newSessionId()` makes one). The starter then sets its timeout from `server.session.timeout`. |
| `findById(id)` | The live session with this id, or `null` when it is unknown, invalidated or expired. Called once per request that carries the cookie. |
| `changeSessionId(session)` | Gives the session a new id and forgets the old one, keeping its values. |
| `deleteById(id)` | Removes the session. |

Each method may return a value or a `Future` (`FutureOr`). With `Future`s, code must use `getSessionAsync()`.

`StoredHttpSession` is an `HttpSession` with what a repository needs: `touch(now)` records a request (`lastAccessedTime`), `isNew` is set by the manager, and `isExpired(now)` says whether the session has gone unused for longer than `maxInactiveInterval`.

```dart
@Configuration()
class SessionConfig {
  // Sessions in the application's database, shared by every instance.
  // DatabaseSessions is the application's own implementation.
  @Bean()
  HttpSessionRepository httpSessionRepository(Database database) =>
      DatabaseSessions(database);
}
```

`InMemoryHttpSessionRepository({timeout, maxSessions, clock})` takes a `clock` for tests that control time:

```dart
var now = DateTime(2026);
final repository = InMemoryHttpSessionRepository(
  timeout: const Duration(minutes: 5),
  clock: () => now,
);
final session = repository.createSession();
now = now.add(const Duration(minutes: 6));
expect(repository.findById(session.id), isNull);
```

## With a pool of isolates

With `server.isolates.count` above one, every isolate runs the whole application, and so every isolate has its own `InMemoryHttpSessionRepository`. A request may reach any isolate.

- **A session made by one isolate is unknown to the others.** The user is logged in for some requests and not for others; the cart is full, then empty.
- **An isolate that does not know the id treats it like any unknown id**: it is ignored, and when that isolate creates a session, its new cookie replaces the old one in the browser.
- **`server.session.max-sessions` counts per isolate.**
- **A test over one connection does not show it.** The requests of a kept-alive connection stay with the isolate that took it. Browsers open several connections.

The pool says so once, when it first adds an isolate:

```text
Each isolate keeps its own sessions in memory, and a request may reach any isolate: what one keeps the others do not see. Keep it where all of them do (a database, a shared store), or accept one copy per isolate.
```

Sessions cannot live with one copy per isolate. Declare an `HttpSessionRepository` bean that keeps them where every isolate sees them, as [above](#where-sessions-live); the in-memory one backs off, and the warning no longer names sessions. See [A pool of isolates](server/isolates.md#what-changes-with-more-than-one-isolate).

## In Spring (Java)

```java
@PostMapping("/cart/items")
void add(HttpSession session, @RequestParam String item) {
  List<String> cart = (List<String>) session.getAttribute("cart");
  ...
  session.setAttribute("cart", cart);
}
```

```properties
server.servlet.session.timeout=15m
server.servlet.session.cookie.name=SHOPSESSION
```

Differences that matter:

- The keys are `server.session.*`, not `server.servlet.session.*`: there is no servlet container.
- No `HttpSession` parameter: call `request.getSession()`.
- The cookie is `SameSite=Lax` by default. Spring Boot leaves `SameSite` unset.
- The number of sessions is limited (`max-sessions`, 10000). Spring Boot has no such key; Tomcat's `maxActiveSessions` is unlimited by default. At the limit, expired sessions are removed, then a new one is refused with `503`, as WebFlux's `InMemoryWebSessionStore` does.
- A repository of your own is an `HttpSessionRepository` bean. Spring uses Spring Session for that.

## See also

- [Headers and cookies](controllers/headers-and-cookies.md)
- [Filters](filters.md)
- [Behind a reverse proxy](server/reverse-proxy.md)
- [A pool of isolates](server/isolates.md)
- [Durations](../spring-core-dart/conversion/durations.md)
- [All properties](properties.md)
