---
name: "X-Up-Context"
area: "API"
kind: "HTTP header"
parent: "up.protocol module"
visibility: "experimental"
url: "https://unpoly.com/api/X-Up-Context"
---
<nav aria-label="Unpoly docs">[All docs](https://unpoly.com/index.md) · [up.protocol module](https://unpoly.com/api/up.protocol.md)</nav>

# X-Up-Context

**This feature is experimental**. Please [share](https://github.com/unpoly/unpoly/discussions) your experiences so we know what to keep or change.

This request header contains the targeted layer's [context](https://unpoly.com/learn/layer-context.md), serialized as JSON.

## Example {#example}

The current layer has a context `{ lives: 3 }`. When the user updates a fragment, Unpoly automatically includes the following request headers:

```http
X-Up-Context: { "lives": 3 }
X-Up-Target: main
```

The server may choose to render HTML based on that context, e.g. by including a live counter in the response. It responds with the following HTTP:

```http
Vary: X-Up-Context

<main>
  3 lives left
  ...
</main>
```

> #### Note
>
> Request headers that influenced a response should be listed in a [`Vary`](https://unpoly.com/api/Vary.md) response header. This tells Unpoly to [partition its cache](https://unpoly.com/learn/optimizing-responses.md#vary) for that URL so that each request header value gets separate cache entries.

## Updating context from the server {#updating-context-from-the-server}

The server may update the layer context by sending a `X-Up-Context` response header with changed key/value pairs:

```http
Content-Type: text/html
X-Up-Context: { "lives": 2 }

<html>
  ...
</html>
```

> #### Important
>
> HTTP headers [may only contain US-ASCII (7-bit) characters](https://www.rfc-editor.org/rfc/rfc7230#section-3.2.4). If you have higher code points in a JSON value, you may [encode those characters using Unicode escape sequences](https://makandracards.com/makandra/536174-http-headers-can-only-transport-us-ascii-characters-safely).

Upon seeing the response header, Unpoly will merge the server-provided context object into the layer's context object, adding or replacing keys as needed. Client-side context keys not mentioned in the response will remain unchanged.

There is no explicit protocol to _remove_ keys from the context, but the server may send a key with a `null` value to effectively remove a key.

The frontend will use the server-provided context updates for both successful (HTTP status `200 OK`) and error (status `4xx` or `5xx`) responses. If no `X-Up-Context` response header is set, the updating layer's context will not be changed.

It is recommended that the server only places changed key/value pairs into the `X-Up-Context` response header, and not echo the entire context object. Otherwise any client-side changes made while the request was in flight will get overridden by the server-provided context.

