# What Is the Session TTL in ego-lite and How Is It Managed?

> Discover the 2-second session TTL in ego-lite. Learn how the ensureSession() function automatically refreshes CDP connections to prevent stale sessions.

- Repository: [CitroLabs/ego-lite](https://github.com/citrolabs/ego-lite)
- Tags: how-to-guide
- Published: 2026-08-27

---

**The session TTL in ego-lite is hard-coded to 2 seconds (2000 ms), automatically refreshing CDP sessions via the `ensureSession()` function in [`browser-runtime.ts`](https://github.com/citrolabs/ego-lite/blob/main/browser-runtime.ts) to prevent stale connections.**

The citrolabs/ego-lite browser automation library implements a strict session time-to-live (TTL) mechanism to maintain reliable Chrome DevTools Protocol (CDP) connections. Unlike long-lived sessions that risk becoming stale when browser tabs change, ego-lite treats each session as valid for only a brief window. Understanding this **session TTL in ego-lite** is essential for debugging connection issues and optimizing script reliability.

## How the 2-Second Session TTL Is Defined

### The SESSION_TTL_MS Constant

In [`package/ego-browser/src/browser-runtime.ts`](https://github.com/citrolabs/ego-lite/blob/main/package/ego-browser/src/browser-runtime.ts), the TTL is defined by the constant:

```typescript
const SESSION_TTL_MS = 2000; // 2 seconds

```

This hard-coded value represents the maximum age a CDP session remains valid before the runtime requires re-authentication through `Target.attachToTarget`.

### Session State Tracking in state.ts

The runtime tracks session vitality in [`package/ego-browser/src/state.ts`](https://github.com/citrolabs/ego-lite/blob/main/package/ego-browser/src/state.ts) using two mutable properties:

- `state.sessionId` — Stores the active CDP session identifier string.
- `state.sessionAt` — Records the Unix timestamp (in milliseconds) when the session was last established or refreshed.

## Session Lifecycle: The ensureSession() Logic

The core session management occurs in `ensureSession()` within [`browser-runtime.ts`](https://github.com/citrolabs/ego-lite/blob/main/browser-runtime.ts). This function evaluates session freshness before every CDP operation to determine whether to reuse or recreate the connection.

### Reusing Fresh Sessions

If `state.sessionId` exists and `Date.now() - state.sessionAt < SESSION_TTL_MS`, the existing session is returned immediately. This optimization avoids unnecessary `Target.attachToTarget` calls for rapid sequential operations that occur within the 2-second window.

### Creating New Sessions After Expiry

When the TTL expires or no session exists, the runtime executes the following sequence:

1. Creates a new session by calling `Target.attachToTarget` on the active tab.
2. Invokes `enablePageEvents()` to activate necessary CDP domain events.
3. Updates `state.sessionAt = Date.now()` to reset the TTL clock and stores the new `sessionId`.

## Handling Session Loss and Invalidation

When CDP requests fail with a "session lost" error (matched against the internal `SESSION_LOST` regex), the runtime automatically calls `invalidateSession()`. This function clears `state.sessionId`, `state.sessionAt`, and related flags, forcing the next operation to establish a completely fresh connection regardless of the TTL timer.

## Practical Code Examples

Automatic session handling requires no manual TTL management:

```javascript
// The runtime automatically ensures a fresh session if the TTL has expired.
await cdp('Runtime.evaluate', { expression: 'navigator.userAgent' });

```

Explicitly forcing a new session (rarely needed):

```javascript
// Invalidate the current session so the next call creates a fresh one.
invalidateSession();
await cdp('Runtime.evaluate', { expression: 'document.title' });

```

Inspecting session state for debugging:

```javascript
import { state } from './state.js';

console.log('Current session ID:', state.sessionId);
console.log('Session age (ms):', Date.now() - state.sessionAt);

```

## Summary

- The **session TTL in ego-lite** is strictly 2 seconds, defined by `SESSION_TTL_MS` in [`browser-runtime.ts`](https://github.com/citrolabs/ego-lite/blob/main/browser-runtime.ts).
- Session validity is tracked via `state.sessionAt` and `state.sessionId` in [`state.ts`](https://github.com/citrolabs/ego-lite/blob/main/state.ts).
- The `ensureSession()` function automatically reuses fresh sessions or creates new ones via `Target.attachToTarget`.
- `invalidateSession()` provides manual control to clear state when errors are detected using the `SESSION_LOST` regex pattern.

## Frequently Asked Questions

### What is the exact session TTL value in ego-lite?

According to the citrolabs/ego-lite source code, the TTL is hard-coded to **2000 milliseconds (2 seconds)** via the `SESSION_TTL_MS` constant in [`package/ego-browser/src/browser-runtime.ts`](https://github.com/citrolabs/ego-lite/blob/main/package/ego-browser/src/browser-runtime.ts). This short window ensures sessions never become stale during browser tab transitions.

### How does ego-lite know when to create a new CDP session?

The `ensureSession()` function evaluates `Date.now() - state.sessionAt < SESSION_TTL_MS`. If this check returns false, or if `state.sessionId` is null, the runtime creates a new session by attaching to the target and updates `state.sessionAt` to the current timestamp.

### Can I configure or extend the session TTL?

No. The 2-second TTL is a hard-coded safety mechanism in the runtime layer. You cannot configure it, but you can manually trigger a refresh using `invalidateSession()` if you need to force a new session outside the normal lifecycle.

### What happens when a CDP session is lost unexpectedly?

The runtime detects "session lost" errors using the `SESSION_LOST` regex and automatically calls `invalidateSession()`, which clears `state.sessionId` and `state.sessionAt`. This forces the next CDP request to establish a fresh attachment.