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

# Mercure

> [Mercure](https://mercure.rocks/) is a real-time communication protocol and hub designed for modern web apps. It allows servers to instantly push updates to browsers, mobile clients, and backend workers through Server-Sent Events (SSE).


export const DynamicCodeBlock = ({language = 'yaml', filename, icon, lines, wrap, expandable, highlight, focus, children}) => {
  const STORAGE_KEY = 'upsun_versions_cache';
  const COMPOSABLE_STORAGE_KEY = 'upsun_composable_cache';
  const CACHE_TTL = 5 * 60 * 1000;
  const API_URL = 'https://meta.upsun.com/images';
  const COMPOSABLE_API_URL = 'https://meta.upsun.com/composable';
  const DEBUG_PREFIX = '[DynamicCodeBlock cache]';
  const [versionData, setVersionData] = useState(null);
  const [versionError, setVersionError] = useState(false);
  const [composableData, setComposableData] = useState(null);
  const [composableError, setComposableError] = useState(false);
  useEffect(() => {
    const fetchData = async () => {
      let cachedData = null;
      let cachedEtag = null;
      if (typeof localStorage !== 'undefined') {
        try {
          const cached = localStorage.getItem(STORAGE_KEY);
          if (cached) {
            const parsed = JSON.parse(cached);
            cachedData = parsed?.data || null;
            cachedEtag = parsed?.etag || null;
            if (cachedData && Date.now() - parsed.timestamp < CACHE_TTL) {
              return cachedData;
            }
          }
        } catch (err) {
          console.error('Failed to load from cache:', err);
        }
      }
      const requestHeaders = cachedEtag ? {
        'If-None-Match': cachedEtag
      } : {};
      console.debug(`${DEBUG_PREFIX} revalidating`, {
        storageKey: STORAGE_KEY,
        hasCachedData: Boolean(cachedData),
        hasCachedEtag: Boolean(cachedEtag)
      });
      const response = await fetch(API_URL, {
        headers: requestHeaders
      });
      if (response.status === 304 && cachedData) {
        console.debug(`${DEBUG_PREFIX} revalidated (304)`, {
          storageKey: STORAGE_KEY
        });
        if (typeof localStorage !== 'undefined') {
          try {
            const etag = response.headers.get('etag') || cachedEtag;
            localStorage.setItem(STORAGE_KEY, JSON.stringify({
              data: cachedData,
              etag,
              timestamp: Date.now()
            }));
          } catch (err) {
            console.error('Failed to refresh cache metadata:', err);
          }
        }
        return cachedData;
      }
      if (!response.ok) throw new Error(`API request failed: ${response.statusText}`);
      const data = await response.json();
      const etag = response.headers.get('etag');
      console.debug(`${DEBUG_PREFIX} refreshed (200)`, {
        storageKey: STORAGE_KEY,
        etag
      });
      if (typeof localStorage !== 'undefined') {
        try {
          localStorage.setItem(STORAGE_KEY, JSON.stringify({
            data,
            etag,
            timestamp: Date.now()
          }));
        } catch (err) {
          console.error('Failed to cache data:', err);
        }
      }
      return data;
    };
    fetchData().then(data => setVersionData(data)).catch(err => console.error('Failed to fetch version data:', err));
  }, []);
  const findHighestVersion = versionsMap => {
    if (!versionsMap || Object.keys(versionsMap).length === 0) return null;
    const entries = Object.entries(versionsMap);
    const active = entries.filter(([, v]) => v.upsun && v.upsun.status === 'supported' || v.upsun && v.upsun.status === 'deprecated');
    const candidates = active.length > 0 ? active : entries;
    let [highestName] = candidates[0];
    for (let i = 1; i < candidates.length; i++) {
      const [currentName] = candidates[i];
      const cp = currentName.split('.').map(Number);
      const hp = highestName.split('.').map(Number);
      for (let j = 0; j < Math.max(cp.length, hp.length); j++) {
        if ((cp[j] || 0) > (hp[j] || 0)) {
          highestName = currentName;
          break;
        } else if ((cp[j] || 0) < (hp[j] || 0)) {
          break;
        }
      }
    }
    return highestName;
  };
  const getVersion = (lang, requestedVersion = 'latest') => {
    if (lang === 'composable') {
      if (!composableData || !composableData.versions || Object.keys(composableData.versions).length === 0) return null;
      if (requestedVersion && requestedVersion !== 'latest') {
        return (requestedVersion in composableData.versions) ? requestedVersion : null;
      }
      return findHighestVersion(composableData.versions);
    }
    if (!versionData) return null;
    const imageData = versionData[lang];
    if (!imageData || !imageData.versions || Object.keys(imageData.versions).length === 0) {
      return null;
    }
    if (requestedVersion && requestedVersion !== 'latest') {
      return (requestedVersion in imageData.versions) ? requestedVersion : null;
    }
    return findHighestVersion(imageData.versions);
  };
  let code = typeof children === 'string' ? children : String(children || '');
  const codeLines = code.split('\n');
  while (codeLines.length > 0 && codeLines[0].trim() === '') codeLines.shift();
  while (codeLines.length > 0 && codeLines[codeLines.length - 1].trim() === '') codeLines.pop();
  if (codeLines.length > 0) {
    const indents = codeLines.filter(line => line.trim().length > 0).map(line => line.match(/^[ \t]*/)[0].length);
    const minIndent = Math.min(...indents);
    code = codeLines.map(line => line.slice(minIndent)).join('\n');
  }
  code = code.replace(/\{\{version:(.*?)\}\}/g, (match, params) => {
    const parts = params.split(':');
    const lang = parts[0];
    const ver = parts[1] || 'latest';
    const isComposable = lang === 'composable';
    const hasError = isComposable ? composableError : versionError;
    const dataReady = isComposable ? composableData !== null : versionData !== null;
    if (hasError) return '(unavailable)';
    if (dataReady) {
      const resolvedVersion = getVersion(lang, ver);
      return resolvedVersion || match;
    }
    return '...';
  });
  const codeBlockProps = {
    language,
    ...filename && ({
      filename
    }),
    ...icon && ({
      icon
    }),
    ...lines !== undefined && ({
      lines
    }),
    ...wrap !== undefined && ({
      wrap
    }),
    ...expandable !== undefined && ({
      expandable
    }),
    ...highlight && ({
      highlight
    }),
    ...focus && ({
      focus
    })
  };
  return <CodeBlock {...codeBlockProps}>{code}</CodeBlock>;
};

export const VersionDeprecatedBlock = () => <>
    <h3 id="deprecated-versions">Deprecated versions</h3>
    <p>
    The following versions are <a href="/docs/glossary#deprecated-versions">deprecated</a>.
    They're available, but they don't receive security updates from upstream and aren't guaranteed to work.
    They'll be removed in the future – consider migrating to a <a href="#supported-versions">supported version</a>.
    </p>
  </>;

export const VariableBlock = ({name}) => {
  return <var spellCheck={false} title={`Replace '${name}' with your own data`}>{name}</var>;
};

Built for simplicity and performance, Mercure is widely used in the Symfony ecosystem and beyond for reactive UIs, real-time notifications, and live data streaming.

### Supported versions

You can select the major and minor version.

Patch versions are applied periodically for bug fixes and the like.
When you deploy your app, you always get the latest available patches.

* 0

<VersionDeprecatedBlock />

## Retired versions

The following versions have been retired and are no longer available.
If your project uses a retired version, you must update to a [supported version](#supported-versions).

## JWT Token Secret

The service generates the JSON Web Token (JWT) token secret. It's available in the `password` field of the Mercure relationship in the `PLATFORM_RELATIONSHIPS` environment variable.

## Relationship reference

For each service [defined via a relationship](#usage-example) to your application,
Upsun automatically generates corresponding environment variables within your application container,
in the `$<RELATIONSHIP-NAME>_<SERVICE-PROPERTY>` format.

Here is example information available through the [service environment variables](/docs/development/variables#service-environment-variables) themselves,
or through the [`PLATFORM_RELATIONSHIPS` environment variable](/docs/development/variables/use-variables#use-provided-variables).

<Tabs>
  <Tab title="Service environment variables">
    You can obtain the complete list of available service environment variables in your app container by running `upsun ssh env`.

    Note that the information about the relationship can change when an app is redeployed or restarted or the relationship is changed. So your apps should only rely on the [service environment variables](/docs/development/variables#service-environment-variables) directly rather than hard coding any values.

    <DynamicCodeBlock language="bash">
      {`
              MERCURE_PUBLIC=false
              MERCURE_SERVICE=mercure0
              MERCURE_HOSTNAME=sample-hostname.mercure.service.platformsh.site
              MERCURE_PORT=3000
              MERCURE_IP="123.456.78.90"
              MERCURE_CLUSTER=sample-cluster-id-12345
              MERCURE_TYPE=mercure:0
              MERCURE_QUERY={}
              MERCURE_INSTANCE_IPS=["123.456.789.001"]
              MERCURE_PATH=
              MERCURE_RELATIONSHIPS_ENV_VAR_EXTRA={}
              MERCURE_FRAGMENT=
              MERCURE_EPOCH=0
              MERCURE_HOST=mercure0.internal
              MERCURE_PASSWORD=ChangeMe
              MERCURE_HOST_MAPPED=false
              MERCURE_SCHEME=http
              MERCURE_REL=mercure
              MERCURE_USERNAME=
            `
          }
    </DynamicCodeBlock>
  </Tab>

  <Tab title="`PLATFORM_RELATIONSHIPS` environment variable">
    For some advanced use cases, you can use the [`PLATFORM_RELATIONSHIPS` environment variable](/docs/development/variables/use-variables#use-provided-variables).
    The structure of the `PLATFORM_RELATIONSHIPS` environment variable can be obtained by running `upsun relationships` in your terminal:

    <DynamicCodeBlock language="json">
      {`
              {
                "mercure": [
                  {
                    "username": null,
                    "fragment": null,
                    "ip": "123.456.78.90",
                    "cluster": "sample-cluster-id-12345",
                    "host": "mercure.internal",
                    "path": null,
                    "query": {},
                    "relationships_env_var_extra": {},
                    "port": 3000,
                    "host_mapped": false,
                    "password": "ChangeMe",
                    "service": "mercure",
                    "hostname": "sample-hostname.mercure.service.platformsh.site",
                    "epoch": 0,
                    "instance_ips": [
                      "123.456.789.001"
                    ],
                    "rel": "mercure",
                    "scheme": "http",
                    "type": "mercure:0",
                    "public": false
                  }
                ]
              }
            `
          }
    </DynamicCodeBlock>

    Here is an example of how to gather [`PLATFORM_RELATIONSHIPS` environment variable](/docs/development/variables/use-variables#use-provided-variables) information in a [`.environment` file](/docs/development/variables/set-variables#when-to-use-env-files):

    ```bash .environment theme={null}
    # Decode the built-in credentials object variable.
    export RELATIONSHIPS_JSON="$(echo "$PLATFORM_RELATIONSHIPS" | base64 --decode)"

    # Set environment variables for individual credentials.
    export APP_MERCURE_HOST="$(echo $RELATIONSHIPS_JSON | jq -r '.mercure[0].host')"
    ```
  </Tab>
</Tabs>

## Usage example

### 1. Configure the service

To define the service, use the `mercure` type:

<DynamicCodeBlock language="yaml" filename=".upsun/config.yaml">
  {`
      services:
         # The name of the service container. Must be unique within a project.
         <SERVICE_NAME>:
            type: mercure:0
            disk: 256
    `
  }
</DynamicCodeBlock>

Note that changing the name of the service replaces it with a brand new service and all existing data is lost. Back up your data before changing the service.

#### Configuration options

You can pass additional options under the `configuration` key:

<DynamicCodeBlock language="yaml" filename=".upsun/config.yaml">
  {`
      services:
         <SERVICE_NAME>:
            type: mercure:0
            disk: 256
            configuration:
              anonymous: true
              cors_origins:
                - "https://your-frontend.example.com"
    `
  }
</DynamicCodeBlock>

| Option         | Type            | Default | Description                                                                                                                                                                             |
| -------------- | --------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `anonymous`    | boolean         | `false` | Allows unauthenticated subscribers to connect without a JWT token.                                                                                                                      |
| `cors_origins` | list of strings | —       | Domains allowed to make cross-origin requests to the Mercure hub. Requires environment-specific values in your YAML — see the [routing step warning](#2-define-the-route) before using. |

### 2. Define the route

To access the service URL, add an entry to the `.routes` key as shown below, replacing `<SERVICE_NAME>` with the name of your service.

<Warning>
  By default, the Upsun Mercure image doesn't expose CORS headers.
  If your Mercure hub will be accessed from a browser (e.g. subscribing to Server-Sent Events via JavaScript),
  you **must** route it as a sub-path of your main domain rather than on a dedicated subdomain.
  A subdomain like `mercure.{default}` is treated as a different origin by browsers,
  and without CORS headers, requests will be blocked.

  If you can't use a sub-path route, you can configure [`cors_origins`](#configuration-options) as a last resort.
  Be aware that hardcoding domain names directly in your YAML config is an anti-pattern on Upsun:
  those values are environment-specific (production, staging, preview each have different domains),
  which means your config file no longer describes a single consistent state.
</Warning>

Use a **sub-path route** so the hub shares the same origin as your frontend (recommended for browser usage):

<DynamicCodeBlock language="yaml" filename=".upsun/config.yaml">
  {`
      routes:
        "https://{default}/":
          type: upstream
          upstream: "<APP_NAME>:http"
        "https://{default}/.well-known/mercure":
          type: upstream
          upstream: "<SERVICE_NAME>:mercure"
    `
  }
</DynamicCodeBlock>

Use a **subdomain route** if the Mercure hub is only consumed server-side (no browser clients — CORS headers aren't required):

<DynamicCodeBlock language="yaml" filename=".upsun/config.yaml">
  {`
      routes:
        "https://mercure.{default}/":
          type: upstream
          upstream: "<SERVICE_NAME>:mercure"
    `
  }
</DynamicCodeBlock>

### 3. Define the relationship

Define the relationship to the app as shown below:

<Tabs>
  <Tab title="Using default endpoints">
    <DynamicCodeBlock language="yaml" filename=".upsun/config.yaml">
      {`
              applications:
                # The name of the app container. Must be unique within a project.
                <APP_NAME>:
                  # Relationships enable access from this app to a given service.
                  # The example below shows simplified configuration leveraging a default service
                  # (identified from the relationship name) and a default endpoint.
                  # See the Application reference for all options for defining relationships and endpoints.
                  relationships:
                    <SERVICE_NAME>: "mercure:mercure"
            `
          }
    </DynamicCodeBlock>

    You can define `SERVICE_NAME` as you like, so long as it's unique between all defined services
    and matches in both the application and services configuration.

    The example above leverages [default endpoint](/docs/configure-apps/image-properties/relationships) configuration for relationships.
    That is, it uses default endpoints behind the scenes, providing a [relationship](/docs/configure-apps/image-properties/relationships)
    (the network address a service is accessible from) that is identical to the *name* of that service.

    Depending on your needs, instead of default endpoint configuration,
    you can use [explicit endpoint configuration](/docs/configure-apps/image-properties/relationships).

    With the above definition, the application container (`APP_NAME`) now has [access to the service](#use-in-app) via the relationship `SERVICE_NAME` and its corresponding [service environment variables](/docs/development/variables#service-environment-variables).
  </Tab>

  <Tab title="Using explicit endpoints">
    <DynamicCodeBlock language="yaml" filename=".upsun/config.yaml">
      {`
              applications:
                # The name of the app container. Must be unique within a project.
                <APP_NAME>:
                  # Relationships enable access from this app to a given service.
                  # The example below shows configuration with an explicitly set service name and endpoint.
                  # See the Application reference for all options for defining relationships and endpoints.
                  relationships:
                    <RELATIONSHIP_NAME>:
                      service: <SERVICE_NAME>
                      endpoint: mercure
            `
          }
    </DynamicCodeBlock>

    You can define `SERVICE_NAME` and `<RELATIONSHIP_NAME>` as you like, so long as it's unique between all defined services and relationships
    and matches in both the application and services configuration.

    The example above leverages [explicit endpoint](/docs/configure-apps/image-properties/relationships) configuration for relationships.

    Depending on your needs, instead of explicit endpoint configuration,
    you can use [default endpoint configuration](/docs/configure-apps/image-properties/relationships).

    With the above definition, the application container now has [access to the service](#use-in-app) via the relationship `<RELATIONSHIP_NAME>` and its corresponding [service environment variables](/docs/development/variables#service-environment-variables).
  </Tab>
</Tabs>

#### Example configuration

<Tabs>
  <Tab title="Using default endpoints">
    <DynamicCodeBlock language="yaml" filename=".upsun/config.yaml">
      {`
              applications:
                # The name of the app container. Must be unique within a project.
                myapp:
                  # Relationships enable access from this app to a given service.
                  # The example below shows simplified configuration leveraging a default service
                  # (identified from the relationship name) and a default endpoint.
                  # See the Application reference for all options for defining relationships and endpoints.
                  relationships:
                    mercure:

              services:
                # The name of the service container. Must be unique within a project.
                mercure:
                  type: mercure:{{version:mercure:latest}}`
          }
    </DynamicCodeBlock>
  </Tab>

  <Tab title="Using explicit endpoints">
    <DynamicCodeBlock language="yaml" filename=".upsun/config.yaml">
      {`
              applications:
                # The name of the app container. Must be unique within a project.
                # Relationships enable access from this app to a given service.
                # The example below shows configuration with an explicitly set service name and endpoint.
                # See the Application reference for all options for defining relationships and endpoints.
                relationships:
                  mercure:
                    mercure: "mercure:mercure"
                      
              services:
                # The name of the service container. Must be unique within a project.
                mercure:
                  type: mercure:{{version:mercure:latest}}`
          }
    </DynamicCodeBlock>
  </Tab>
</Tabs>

### Use in app

To use the configured service in your app, add a configuration file similar to the following to your project.

<Tabs>
  <Tab title="Using default endpoints">
    <DynamicCodeBlock language="yaml" filename=".upsun/config.yaml">
      {`
              applications:
                # The name of the app container. Must be unique within a project.
                myapp:
                  # The location of the application's code.
                  source:
                    root: "/"

                  [...]

                  # Relationships enable access from this app to a given service.
                  # The example below shows simplified configuration leveraging a default service
                  # (identified from the relationship name) and a default endpoint.
                  # See the Application reference for all options for defining relationships and endpoints.
                  relationships:
                    mercure:

              services:
                mercure:
                  type: mercure:{{version:mercure:latest}}`
          }
    </DynamicCodeBlock>
  </Tab>

  <Tab title="Using explicit endpoints">
    <DynamicCodeBlock language="yaml" filename=".upsun/config.yaml">
      {`
              applications:
                # The name of the app container. Must be unique within a project.
                myapp:
                  # The location of the application's code.
                  source:
                    root: "myapp"

                  [...]

                  # Relationships enable access from this app to a given service.
                  # The example below shows configuration with an explicitly set service name and endpoint.
                  # See the Application reference for all options for defining relationships and endpoints.
                  relationships:
                    mercure:
                      service: mercure
                      endpoint: mercure

              services:
                mercure:
                  type: mercure:{{version:mercure:latest}}`
          }
    </DynamicCodeBlock>
  </Tab>
</Tabs>

This configuration defines a single application (`myapp`), whose source code exists in the `<PROJECT_ROOT>/myapp` directory.<br />
`myapp` has access to the `mercure` service via a relationship whose name is [identical to the service name](#2-define-the-relationship)
(as per [default endpoint](/docs/configure-apps/image-properties/relationships) configuration for relationships).

From this, `myapp` can retrieve access credentials to the service through the [relationship environment variables](#relationship-reference).

```bash myapp/.environment theme={null}
# Set environment variables for common Mercure credentials.
# For more information, please visit https://developer.upsun.com/docs/development/variables#service-environment-variables.
export MERCURE_USER="${MERCURE_USERNAME}"
export MERCURE_HOST="${MERCURE_HOST}"
export MERCURE_QUERY="${MERCURE_QUERY}"
```

The `.environment` shown above in the `myapp` directory is automatically sourced by Upsun into the runtime environment, so that the variable `MERCURE_HOST` can be used within the application to connect to the service.

Note that `DATABASE_URL` and all Upsun [service environment variables](/docs/development/variables#service-environment-variables), such as `MERCURE_HOST`, are environment-dependent.
Unlike the build produced for a given commit,
they can’t be reused across environments and only allow your app to connect to a single service instance on a single environment.

A file very similar to this is generated automatically for your when using the `upsun project:init` command to [migrate a codebase to Upsun](/docs/get-started).
