# Sessions

> How a Nullgate session works: when to reuse it, when to create a new one, and what happens after Nullgate loses the session state.

Use one session per visit. It holds the browser identity and state from earlier pages.

```python
with Nullgate() as ng, httpx.Client(headers={"User-Agent": UA}) as http:
    session = ng.session(user_agent=UA)  # once per visit
    for url in (login_url, account_url):
        page = session.page(url, http.get(url).text)  # once per loaded page
        sensor = page.sensor(script=http.get(page.sensor_url).text, cookies=http.cookies)
        sensor.wait()
        http.post(sensor.url, content=sensor.body, headers=sensor.headers)
```

```typescript
const session = new Nullgate().session({ userAgent }); // once per visit
for (const url of [loginUrl, accountUrl]) {
  const response = await http(url);
  const page = session.page(response.url, await response.text()); // once per loaded page
  const sensor = await page.sensor({
    script: await (await http(page.sensorUrl)).text(),
    cookies,
  });
  await sensor.wait();
  await post(sensor);
}
```

## What a session holds

| Part               | Where it comes from                                                                                             |
| ------------------ | --------------------------------------------------------------------------------------------------------------- |
| `user_agent`       | You. It must be the User-Agent your HTTP client sends to the target                                             |
| `profile`          | A UUID that names the browser identity. The SDK makes a random one unless you pass yours                        |
| `timezone`         | Optional IANA name, for example `Europe/Berlin`                                                                 |
| Session identifier | Nullgate returns it with every result. The SDK stores it and sends it with the next request of the same product |

Creating a session or a page makes no network request.

## When to reuse and when to create

| Situation                                                   | Do this                                                        |
| ----------------------------------------------------------- | -------------------------------------------------------------- |
| Next request on the same page                               | Same `page`                                                    |
| Next page of the same visit                                 | Same `session`, new `session.page(url, html)`                  |
| The same target account tomorrow                            | New `session` with the same `profile`, User-Agent and timezone |
| Another target account, another proxy or another User-Agent | New `session` with a new `profile`                             |

Store the `profile` UUID with the target account:

```python
session = ng.session(user_agent=UA, profile="6f1c2a52-8f0e-4c7b-9b55-0d0f6d2b7a11")
```

```typescript
const session = ng.session({
  userAgent,
  profile: "6f1c2a52-8f0e-4c7b-9b55-0d0f6d2b7a11",
});
```

## One request at a time

The SDK queues requests per session and product. Over raw HTTP, a concurrent request with the same `session` fails with [`session_busy`](https://nullgate.club/en/errors#session_busy). Different sessions can run in parallel without a session limit.

## When the state is lost

Nullgate keeps state for 100 seconds after the last successful request. After that, or with a new session object, the next request starts a new visit.

| What                                          | After the state is lost                                                               |
| --------------------------------------------- | ------------------------------------------------------------------------------------- |
| A request with all required source data       | Succeeds. You get no session-expired error                                            |
| The browser identity                          | Stays the same if `profile`, User-Agent and timezone are the same                     |
| What Nullgate remembered about earlier pages  | Gone. Load the page again with your client and start its requests from the first one |

**Akamai sensors.** Retention is scoped to the document and session. A new document, new session or changed script needs the full script. Pass `script` on every SDK call. The SDK handles retention and retries `script_required` once with the full script. After state loss, raw HTTP with only a digest returns HTTP 428 `script_required`, without charges or state changes.

- Over raw HTTP, changing `profile`, User-Agent or timezone in a live session returns [`invalid_request`](https://nullgate.club/en/errors#invalid_request). Start a new session with `"session": null`.
- If Nullgate cannot save state, it returns [`unavailable`](https://nullgate.club/en/errors#unavailable) without charging you. Retry.

## Advanced

### Observed document identity and timing

Optional document UUID and start time (Unix milliseconds): `session.page(url, html, document_id=..., started_at_ms=...)` or `session.page(url, html, { documentId, startedAtMs })` in TypeScript. The SDK defaults to a new UUID and the current time. For FWCIM, an explicit start must match `timing.navigationStart`.

### API transport

Custom transport applies only to Nullgate API calls, not target requests or the ThreatMetrix connection. Retrying generation can incur another charge.

```python
class CountingTransport(httpx.HTTPTransport):
    count = 0

    def handle_request(self, request):
        self.count += 1
        return super().handle_request(request)

with Nullgate(transport=CountingTransport()) as ng:
    account = ng.account()
```

```typescript
let count = 0;
const ng = new Nullgate(process.env.NULLGATE_API_KEY, {
  fetch: async (input, init) => {
    count++;
    return globalThis.fetch(input, init);
  },
});
const account = await ng.account();
```

Sync Python takes `httpx.BaseTransport`. Async `nullgate.aio.Nullgate` takes `httpx.AsyncBaseTransport`, for example `httpx.AsyncHTTPTransport()`.

### Report a generation

To flag an Akamai request, FWCIM result or ThreatMetrix profile for support, call `result.report()` or `ng.report(request_id)` (`ng.report(requestId)` in TypeScript). Await in async Python and TypeScript.

The SDK sends only `{"request_id": "..."}` to `/analytics/report`, not target responses or cookies. Nullgate records a diagnostic signal without storing pages, scripts, snapshots or reproductions.

Any well-formed request ID returns HTTP 200 `{"ok": true}`, even if unknown. True means delivery, not target acceptance or refund. False means delivery failed. Report only to flag a generation.
