> ## Documentation Index
> Fetch the complete documentation index at: https://docs.manalens.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# How to keep Safari visitors for more than 7 days

> Set the web SDK anonymous ID cookie from your own server, so Safari keeps it for a year instead of 7 days. Examples for Next.js middleware and Express.

Safari keeps a cookie written by JavaScript for at most 7 days, and clears `localStorage` after 7 days without a visit. A Safari visitor who comes back after a week gets a new anonymous ID. So they count as a new visitor and lose their first touch for [attribution](https://docs.manalens.dev/attribution/installs.md).

A cookie that your site's own server sets in a `Set-Cookie` header keeps its full lifetime. So set the web SDK's `mn_anonymous_id` cookie on your server, and tell the SDK to only read it.

This needs web SDK 0.17.0 and `@manalens/node` 0.5.0 or later.

## 1. Set the cookie on every page response

The helpers are in `@manalens/node`. `@manalens/node/cookies` has only the cookie helpers and no Node.js imports, so it also runs in edge runtimes such as Next.js middleware.

```ts Next.js middleware theme={null}
// middleware.ts
import { NextResponse, type NextRequest } from 'next/server';
import { anonymousIdCookie, SDK_COOKIES, ANONYMOUS_ID_MAX_AGE_SECONDS } from '@manalens/node/cookies';

export function middleware(request: NextRequest) {
  const response = NextResponse.next();
  const secure = request.nextUrl.protocol === 'https:';
  const { anonymousId } = anonymousIdCookie({ cookieHeader: request.headers.get('cookie'), secure });
  if (anonymousId) {
    response.cookies.set(SDK_COOKIES.anonymousId, anonymousId, {
      path: '/',
      maxAge: ANONYMOUS_ID_MAX_AGE_SECONDS,
      sameSite: 'lax',
      secure,
      httpOnly: false, // the web SDK reads it
      // domain: '.example.com', // to share it with every subdomain
    });
  }
  return response;
}

export const config = { matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'] };
```

```js Express theme={null}
import express from 'express';
import { ensureAnonymousId } from '@manalens/node';

const app = express();
app.set('trust proxy', true); // behind a load balancer, so req.secure is right
app.use((req, res, next) => {
  req.anonymousId = ensureAnonymousId(req, res, { domain: 'example.com' });
  next();
});
```

```js Any framework theme={null}
import { anonymousIdCookie } from '@manalens/node/cookies';

const { anonymousId, setCookie } = anonymousIdCookie({ cookieHeader: request.headers.cookie, domain: 'example.com' });
if (setCookie) response.headers.append('Set-Cookie', setCookie);
```

What the helpers do:

* They keep a valid ID from the cookie (a UUID, as the web SDK makes) and make a new one otherwise.
* They set the cookie again on every response, so the one-year expiry starts again at each visit: `Path=/`, `Max-Age=31536000`, `SameSite=Lax`, `Secure`, and `Domain` when you pass `domain`. It is not `HttpOnly`, because the web SDK reads it.
* After the visitor opts out (`mn_opt_out=true`), they make and refresh nothing, and return no ID.
* The cookie is only in the response. To use the ID in the same request, for example in a [server event](https://docs.manalens.dev/sdks/server.md), use the returned `anonymousId`.

Pass `domain` (`example.com`) to share the ID with every subdomain, as the web SDK does by default with `crossSubdomainCookies`.

## 2. Turn on `serverCookie` in the web SDK

```html HTML snippet theme={null}
<script
  src="SCRIPT_URL_FROM_THE_SETUP_PAGE"
  data-publishable-key="YOUR_PUBLISHABLE_KEY"
  data-server-cookie="true"
  defer
></script>
```

```ts npm theme={null}
init({ publishableKey: 'YOUR_PUBLISHABLE_KEY', serverCookie: true });
```

With `serverCookie`, the SDK reads the server's cookie and never writes it from JavaScript. A write from JavaScript brings back Safari's 7-day limit. When the cookie is missing (a page your middleware does not cover), the SDK makes and stores the ID as it does without the option. `reset()`, `optOut()` and `setConsent(false)` still delete the cookie.

## Check it

1. Open your site in Safari with an empty cookie store.
2. In Web Inspector, open **Storage**, **Cookies**. `mn_anonymous_id` expires in one year, not in 7 days.
3. Reload. The value stays the same and matches `getAnonymousId()` in the console.

## Limits

* **Same server.** The cookie must come from the server that serves your pages. Safari 16.4 and later also cap a server cookie at 7 days when the responding server's IP address is not the site's IP address. For example, a page is on one host and the cookie comes from a separate API host behind another provider.
* **No static hosts.** A static host with no server code cannot set it. `events.manalens.dev` cannot set it either: it is another site.
* **No cached responses.** Do not set it on a response that a shared cache (a CDN) stores. Every visitor of that cached page will get the same ID. Exclude cached routes from the middleware, or mark the responses `Cache-Control: private`.
* **Consent.** In [consent mode](https://docs.manalens.dev/sdks/web.md#consent), set the cookie only after the visitor agrees. From `@manalens/node` 0.7.0, pass `requireConsent: true` and your `publishableKey` to `ensureAnonymousId()` or `anonymousIdCookie()`. The helper then sets the cookie only when the request has this project's consent cookie (`consentCookieName(publishableKey)`) with the value `1`. It does not set the cookie with Global Privacy Control. The web SDK writes the consent cookie only with `crossSubdomainCookies` on (the default). See [consent mode](https://docs.manalens.dev/sdks/node.md#consent-mode) in the Node.js SDK.

See [what we collect](https://docs.manalens.dev/data/what-we-collect.md#browser-storage) for every name the web SDK stores.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.