# Connection.toCookie

The [state](https://ethect.dev/reference/connection/state/) of a connection as a cookie, so that a server
renders with the account before any wallet answers. [`Connection.fromCookie`](#fromcookie)
reads it back from `document.cookie` or from a `Cookie` header. Neither fails, and neither
throws.

## Usage

```ts
import { Effect, Layer, Stream } from "effect";
import { Connection, Wallets } from "@ethect/core";

// The cookies of the page. A server has no `document`: it reads the header of its request.
const cookies = typeof document === "undefined" ? undefined : document.cookie;

// The app starts from the connection of the last visit.
const App = Connection.layer({ initial: Connection.fromCookie(cookies) }).pipe(
  Layer.provideMerge(Wallets.browser),
);

// Whatever changes (account, chain, wallet, disconnection), the cookie follows.
const persist = Connection.changes.pipe(
  Stream.runForEach((state) =>
    Effect.sync(() => {
      document.cookie = Connection.toCookie(state);
      // "connection=%7B%22v%22%3A1%2C…%7D; Path=/; Max-Age=31536000; SameSite=Lax"
    }),
  ),
);
```

`toCookie` gives the whole text of the cookie: its name, its value, and the attributes that
make a browser keep it until the next visit. `fromCookie` takes the whole text of the
cookies, and finds its own among them.

### On a server

The same function reads the `Cookie` header of a request. A request with no cookie has no
header: `null` and `undefined` read as `disconnected`.

```ts
import { Layer } from "effect";
import { Connection, Wallets } from "@ethect/core";

// The layers of one request: the cookie is the state, and there is no wallet.
const Server = (request: Request) =>
  Connection.layer({
    initial: Connection.fromCookie(request.headers.get("cookie")),
  }).pipe(Layer.provideMerge(Wallets.of([])));
```

A server that writes the cookie itself sends the same text as a `Set-Cookie` header:
`headers.append("Set-Cookie", Connection.toCookie(state))`.

### Another name, another lifetime

```ts
import { Connection } from "@ethect/core";

declare const state: Connection.State;
declare const header: string | null;

// Every option. Each one that is left out has the default of the table below.
const cookie = Connection.toCookie(state, {
  name: "wallet",
  maxAge: "30 days",
  path: "/app",
  domain: "example.com",
  secure: true,
  sameSite: "strict",
});
// "wallet=%7B…%7D; Path=/app; Domain=example.com; Max-Age=2592000; SameSite=Strict; Secure"

const initial = Connection.fromCookie(header, { name: "wallet" }); // read under the same name
```

### fromCookie

Reads the connection in the text of cookies. The result is a state to start from: pass it to
[`Connection.layer`](https://ethect.dev/reference/connection/layer/) as `initial`.

```ts
import { Connection } from "@ethect/core";

Connection.fromCookie("theme=dark; connection=%7B%22v%22%3A1%2C%22wallet%22%3A%22io.metamask%22%2C%22accounts%22%3A%5B%220xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266%22%5D%2C%22chainId%22%3A1%7D");
// { status: "reconnecting", wallet: "io.metamask", accounts: ["0xf39fd6e5…fffb92266"], chainId: 1 }

Connection.fromCookie("theme=dark; connection=%7B%22v%22%3A1%7D"); // { status: "disconnected" }
Connection.fromCookie("theme=dark"); // { status: "disconnected" }: no such cookie
Connection.fromCookie(null); // { status: "disconnected" }: no cookie at all
Connection.fromCookie("connection=%7B%22v%2"); // { status: "disconnected" }: cut
```

A framework that hands you the value of one cookie, already decoded, has done this part: give
that value to [`Connection.fromJson`](https://ethect.dev/reference/connection/json/#fromjson).

## What is written

| Part | By default | Option |
| --- | --- | --- |
| the name | `connection` | `name` |
| the value | what [`toJson`](https://ethect.dev/reference/connection/json/) gives, percent-encoded | |
| `Path` | `/`: every page of the site reads it | `path` |
| `Domain` | left out: the host that set the cookie, and not its subdomains | `domain` |
| `Max-Age` | `31536000`: a year | `maxAge` |
| `SameSite` | `Lax` | `sameSite` |
| `Secure` | left out | `secure` |
| `HttpOnly` | never | |

| What is read | `fromCookie` gives |
| --- | --- |
| a cookie of that name with a stored connection | `reconnecting`, with its wallet, accounts and chain |
| a cookie of that name with `{"v":1}` | `disconnected` |
| no text, no cookie of that name, a value that is cut, that is not percent-encoded, or that is not what `toJson` writes | `disconnected` |

## Returns

| Function | Type |
| --- | --- |
| `toCookie(state, options?)` | `string` |
| `fromCookie(cookies, options?)` | `Connection.Disconnected \| Connection.Reconnecting` |

## Parameters

### state

- **Type:** [`Connection.State`](https://ethect.dev/reference/connection/state/)

The state to store: usually each one that
[`Connection.changes`](https://ethect.dev/reference/connection/state/#changes) gives.

### cookies

- **Type:** `string | null | undefined`

The text of every cookie, as `name=value` pairs: `document.cookie` in a browser, the `Cookie`
header on a server. `null` and `undefined` are a request with no cookie.

### options.name (optional)

- **Type:** `string`
- **Default:** `"connection"`

The name of the cookie, for `toCookie` and for `fromCookie` alike: read under the name you
wrote.

### options.maxAge (optional)

- **Type:** `Duration.Input`
- **Default:** a year

How long the browser keeps the cookie: `"30 days"`, `Duration.weeks(2)`, or a number of
milliseconds. It is written in whole seconds. `0` makes the browser forget the cookie.

### options.path (optional)

- **Type:** `string`
- **Default:** `"/"`

The pages that are sent the cookie.

### options.domain (optional)

- **Type:** `string`

Give it for the subdomains of a site to share the connection: `"example.com"`. Left out, the
cookie is for the host that set it.

### options.secure (optional)

- **Type:** `boolean`
- **Default:** `false`

Whether the cookie is only sent over HTTPS.

### options.sameSite (optional)

- **Type:** `"strict" | "lax" | "none"`
- **Default:** `"lax"`

Whether another site that links to yours, or embeds it, has the cookie sent.

## Behavior

- **A cookie is a hint, never an identity.** Anyone can write a cookie with any address in
  it. Render with it, and decide nothing from it: what an account may see or do is proved by
  a signature that your server checks.
- **A stored connection reads as `reconnecting`, never as `connected`.** Only the wallet can
  say that it is connected: [`reconnect`](https://ethect.dev/reference/connection/connect/#reconnect) asks it.
- **Neither function fails, and neither throws**, whatever text and whatever options it is
  given.
- **Accounts are written in EIP-55, and read in any case.** A cookie written in lowercase,
  as ethect wrote them before, reads as it did.
- **The cookie is never `HttpOnly`.** The page has to read it with `document.cookie`, to know
  which wallet to ask. It holds nothing to hide: the id of a wallet, its accounts and its
  chain. No provider, no permission, no key and no signature.
- **A disconnection is stored too.** The cookie of a `disconnected` state holds `{"v":1}`, so
  the next visit does not connect the user again behind their back.
- **Only what percent-encoding writes is read.** A value with a quote or a brace in it was
  not written by `toCookie`, and one cut in the middle of an escape cannot be decoded: both
  read as `disconnected`.
- **The first cookie of the name is the one.** When two paths each have one, a browser sends
  the closest path first.
- **The name is encoded as the value is**, so no name breaks the cookie. A name of letters,
  digits, `-`, `_` and `.` is written as it is.
- **`SameSite=None` is always `Secure`.** A browser refuses the one without the other.
- **An option that cannot be written is the default.** A path or a domain with a `;`, a space
  or a character that is not ASCII is left out, and a `maxAge` that is not a finite duration
  is a year.
- **A browser keeps about 4,000 bytes per cookie.** An account takes 51 once encoded. A
  wallet that gives more than seventy-five accounts makes a cookie the browser drops, and
  the next visit then starts `disconnected`.

## Under the hood

Nothing is sent, and no wallet is asked: these are two pure functions.

```text
toCookie(state, options)
  name = percent-encoded toJson(state)
  ; Path ; Domain, if given ; Max-Age, in seconds ; SameSite ; Secure, if asked or SameSite=None

fromCookie(cookies, options)
  the text is split at each ";"
  the first pair whose name is the one asked for
  its value, if it is percent-encoded and decodes → fromJson(value)
  anything else                                     → { status: "disconnected" }
```
