> Part of the walkerOS documentation. Project overview and full index: <https://www.walkeros.io/llms.txt>

# Session

<!-- -->

<!-- -->

[Source code](https://github.com/elbwalker/walkerOS/tree/main/packages/web/core/src/session)[ ](https://www.npmjs.com/package/@walkeros/web-core)

<!-- -->

[Package](https://www.npmjs.com/package/@walkeros/web-core)

There are multiple ways to define and measure a session. Sessions represent a period when a user actively engages with a website, often used for attribution and conversion tracking. Different tools may define and detect sessions in different ways.

The `sessionStart` util helps to detect a new session independently and triggers a `session start` event or [executes custom code](#callback). It works client-side and is cookieless by default. The Util returns [Session Data](#session-data) information. There are [Config Parameters](#config-parameters) to customize the session detection.

In the cookieless mode (default), only the [sessionWindow](#sessionwindow) Util is used. With config parameter `storage: true`, the [sessionStorage](#sessionstorage) gets called before the `sessionWindow`.

note

Working with storage usually requires consent and is not activated by default. Use the [consent](#consent) option to control the storage access permissions.

## Session data[​](#session-data "Direct link to Session data")

Depending on the `storage` and `consent` parameters, the `sessionStart` function returns an object with several properties. If a new session is detected, `isStart` is set to `true`, otherwise `false`.

| Property  | Type    | Description                                         |
| --------- | ------- | --------------------------------------------------- |
| isStart   | boolean | If this is a new session or a known one             |
| storage   | boolean | If the storage was used to determine the session    |
| id        | string  | Randomly generated or previously stored session id  |
| start     | number  | Timestamp of session start                          |
| marketing | boolean | If the session was started by a marketing parameter |
| referrer  | string  | Hostname of the referring site if available         |

With `storage: true` and granted `consent`, the returning object will be extended with the following:

| Property | Type    | Description                                       |
| -------- | ------- | ------------------------------------------------- |
| updated  | number  | Timestamp of last update                          |
| isNew    | boolean | If this is the first visit on a device            |
| device   | string  | Randomly generated or previously stored device id |
| count    | number  | Total number of sessions                          |
| runs     | number  | Total number of runs (like page views)            |

## sessionStart[​](#sessionstart "Direct link to sessionStart")

Example of calling `sessionStart` on a user's first visit:

```
// On page https://www.walkeros.io/docs/session?utm_campaign=docs
sessionStart({ storage: true });

// will automatically create the event
{
  event: "session start",
  data: {
    isStart: true,
    storage: true,
    id: 'r4nd0m1d',
    start: 1711715862000,
    marketing: true,
    campaign: 'docs',
    // Additionally in storage mode
    updated: 1711715862000,
    isNew: true,
    device: 'd3v1c31d',
    count: 1,
    runs: 1,
  },
  // ...
}
```

info

In addition, with `storage: true` and optionally granted `consent`, the `id` and `device` values are set automatically as `user.session` and `user.device` ids.

### Config parameters[​](#config-parameters "Direct link to Config parameters")

The `sessionStart` function is designed to work out of the box. All parameters are optional for customization:

| Parameter           | Type                   | Description                                                                          |
| ------------------- | ---------------------- | ------------------------------------------------------------------------------------ |
| [consent](#consent) | Array\<string>         | The consent state to permit or deny storage access                                   |
| [storage](#storage) | boolean                | If the storage should be used                                                        |
| [cb](#callback)     | false or<br />function | Callback function called after detection, or `false` to disable the default callback |

info

There are additional config parameters [for storage](#sessionstorage) and [for window](#sessionwindow) available.

#### Consent[​](#consent "Direct link to Consent")

Setting a consent state to wait for before detecting a new session is used to decide if storage access is allowed or not. If set, it registers an [on consent event](https://www.walkeros.io/docs/collector/commands.md#on) and won't start until a consent choice is available. If at least one permission was granted, the `sessionStorage` detects a new session; otherwise, the `sessionWindow`.

```
sessionStart({ consent: 'marketing' }); // Won't start automatically
// User makes a consent choice and CMP calls:
elb('walker consent', { marketing: true }); // Triggers the session detection
// Returns a session with storage access
```

#### Storage[​](#storage "Direct link to Storage")

Option to enable the [sessionStorage](#sessionstorage) util to detect a new session with more accuracy and enhanced data.

```
sessionStart({ storage: true });
```

#### Callback[​](#callback "Direct link to Callback")

The `cb` parameter can be used to disable the default callback or to define a custom one. The default callback triggers a `session start` event if `isStart` is `true`. And additionally, with `storage: true`, the user's `session` and `device` ids are also set via `elb('walker user', user);`. The default callback function is passed as the third parameter.

```
const session = sessionStart({ cb: false }); // Disables the default callback

sessionStart({
  cb: (session, instance, defaultCb) => {
    console.log(session);
    defaultCb(session, instance); // Call the default callback
  },
});
```

### Detection process[​](#detection-process "Direct link to Detection process")

Based on the [storage](#storage) option either the [sessionStorage](#sessionstorage) or the [sessionWindow](#sessionwindow) is used to detect a new session. If a [consent](#consent) state is set, the session detection gets scheduled via an [on-consent](https://www.walkeros.io/docs/collector/commands.md#on) command. It will only run once per `run`.

<!-- -->

## sessionStorage[​](#sessionstorage "Direct link to sessionStorage")

### Config parameters[​](#config-parameters-1 "Direct link to Config parameters")

Additional config parameters for storage-based session detection:

| Property       | Type    | Description                                                                    | Default      |
| -------------- | ------- | ------------------------------------------------------------------------------ | ------------ |
| deviceKey      | string  | The key to store the device ID in the storage                                  | elbDeviceId  |
| deviceStorage  | string  | The storage type for the device ID (`local`, `session`, `cookie`)              | local        |
| deviceAge      | number  | The age in days to consider the device ID as expired                           | 30           |
| sessionKey     | string  | The key to store the session ID in the storage                                 | elbSessionId |
| sessionStorage | string  | The storage type for the session ID (`local`, `session`, `cookie`)             | local        |
| domain         | string  | Cookie domain, e.g. `example.com` to share IDs across subdomains (cookie only) |              |
| length         | number  | Minutes after the last update to consider session as expired                   | 30           |
| pulse          | boolean | Update the current session to stay active                                      | false        |

info

There are additional config parameters for [sessionWindow](#sessionwindow) available.

#### Cookie storage[​](#cookie-storage "Direct link to Cookie storage")

Set `deviceStorage` and/or `sessionStorage` to `cookie` to persist the IDs as cookies. Use `domain` to set the cookie on a parent domain so all subdomains share the same session and device IDs:

```
sessionStart({
  storage: true,
  deviceStorage: 'cookie',
  sessionStorage: 'cookie',
  domain: 'example.com', // Shared across www.example.com, shop.example.com, ...
});
```

Without `domain`, cookies are host-only and bound to the exact (sub)domain that set them. When adding `domain` to an existing setup, previously written host-only cookies remain until they expire, so both variants can coexist temporarily.

### Detection process[​](#detection-process-1 "Direct link to Detection process")

Basic rules to detect a new session:

<!-- -->

## sessionWindow[​](#sessionwindow "Direct link to sessionWindow")

### Config parameters[​](#config-parameters-2 "Direct link to Config parameters")

| Parameter                              | Type    | Description                                                              |
| -------------------------------------- | ------- | ------------------------------------------------------------------------ |
| [data](#custom-data)                   | object  | Custom data to enhance the default `data` properties                     |
| [domains](#internal-domains)           | array   | Internal domains to prevent new sessions from triggering when navigating |
| [isStart](#manual-new-session-control) | boolean | Manual new session control                                               |
| [parameters](#marketing-parameters)    | object  | Marketing parameters to enhance the default and support custom ones      |
| [referrer](#referrer-customization)    | string  | Referrer customization                                                   |
| [url](#url-customization)              | string  | URL customization                                                        |

#### Custom data[​](#custom-data "Direct link to Custom data")

Enhance the default `data` properties with custom information, like a session count:

```
const count = 2;
const session = sessionStart({ data: { count } });
```

This will return a `data` object like `{ id: "r4nd0m", count: 2 }`.

#### Internal domains[​](#internal-domains "Direct link to Internal domains")

Define internal domains to prevent new sessions from triggering when navigating between them:

```
const session = sessionStart({
  domains: ['subdomain.walkeros.io', 'example.com'],
});
```

A user coming from `subdomain.walkeros.io` or `example.com` to e.g. `www.walkeros.io`, will no longer trigger a new session.

#### Manual new session control[​](#manual-new-session-control "Direct link to Manual new session control")

Determine if it's a new session using the `isStart` parameter. This might require consent for storage access, which isn't implemented by default.

Usually, the `sessionId` written to the storage is set up to expire and should be updated with each page view. If the `sessionId` is missing, it may be an expired but at least a new session.

```
if (!storageRead('sessionId')) {
  const session = sessionStart({ isStart: true });
  storageWrite('sessionId', session.id);
}
```

> For more information on storage and expiration, check the storage configuration options in this guide.

#### Marketing parameters[​](#marketing-parameters "Direct link to Marketing parameters")

The helper util `getMarketingParameters` is used to extract common parameters like all `utm variants`, typical clickIds like `fbclid`, `gclid`, and others.

To enhance the default and support custom ones add `parameters`, like `{ elb_campaign: 'campaign' }` to add `campaign: "docs"` to `data` for a url with `?elb_campaign=docs`.

A session with marketing parameters will be flagged with `data.marketing = true` automatically.

```
interface MarketingParameters {
  [key: string]: string;
}

sessionStart({
  parameters: { elb_campaign: 'docs' },
});
```

### Click IDs and platform resolution[​](#click-ids-and-platform-resolution "Direct link to Click IDs and platform resolution")

When the URL contains a known ad-platform click ID, `getMarketingParameters` adds two fields to its result:

* `clickId`: the URL parameter name that was found (e.g. `gclid`).
* `platform`: the canonical platform identifier (e.g. `google`).

The raw value is also stored under the parameter name itself, so a URL like `https://example.com/?gclid=abc` produces:

```
{

  clickId: 'gclid',

  gclid: 'abc',

  platform: 'google',

}
```

If a URL contains multiple click IDs, every raw value is preserved, but `clickId` and `platform` reference the **highest-priority** match. See [`clickIds.ts`](https://github.com/elbwalker/walkerOS/blob/main/packages/core/src/clickIds.ts) for the full list and priority order.

#### Extending the registry from flow\.json[​](#extending-the-registry-from-flowjson "Direct link to Extending the registry from flow.json")

Pass a `clickIds` array in the session source settings. Entries with a `param` matching a default override the platform name in place; new params append to the end of the priority list.

```
{

  "version": 4,

  "flows": {

    "default": {

      "config": { "platform": "web" },

      "sources": {

        "session": {

          "package": "@walkeros/web-source-session",

          "config": {

            "settings": {

              "clickIds": [

                { "param": "xyzclid", "platform": "xyz" },

                { "param": "fbclid", "platform": "facebook" }

              ]

            }

          }

        }

      }

    }

  }

}
```

#### Referrer customization[​](#referrer-customization "Direct link to Referrer customization")

By default the `document.referrer` is used, but it can be overwritten with the `referrer` parameter.

```
sessionStart({ referrer: 'https://example.com' });
```

Domains can be extended, e.g., internal sub-domains. Data can be pre-defined, e.g., to use your ID.

#### URL customization[​](#url-customization "Direct link to URL customization")

By default, the `window.location.href` is used, but it can be overwritten with the `url` parameter.

```
sessionStart({ url: 'https://example.com' });
```

### Detection process[​](#detection-process-2 "Direct link to Detection process")

Basic rules to detect a new session:

1. **Storage Check** (*Optional*): First, check for an existing sessionId in storage. If none is found, consider it a new session. This usually requires consent.
2. **Page reload**: If the entry type is a page reload, it's not a new session.
3. **Marketing Parameters**: The presence of marketing parameters in the URL indicates a new session.
4. **Referrer Check**: A different referrer from the current domain signals a new session.

<!-- -->

note

Be aware of potential multiple unintended events for the same user due to referrer hiding. For more details, learn about [Referrer Hiding](https://en.wikipedia.org/wiki/HTTP_referer#Referrer_hiding).
