# Server-side rendering

> For a site whose HTML comes from a server or a build - your server asks Taggor for the component already rendered and writes it into the first HTML, with a one-line helper, a switch to turn it off, and a fallback to the plain tag. Examples for Next.js, Astro, Express, React Router, SvelteKit, Nuxt, Flask and PHP.

> **The helper on npm**
>
> Outside the build sandbox, your code runs on our servers only when you enable server-side rendering, in an isolated
> environment. The `@taggor/server` helper is on npm; without Node, call the route over HTTP, as the PHP example does.

## Install the helper

This page describes `@taggor/server` 0.4. Install it from npm in the project of your server:

```sh
npm install @taggor/server
```

Every example below imports it. Without Node on the server, skip this step and call the route over HTTP, as
the PHP example does.

Without this, a Taggor component appears when the site's script arrives. With it, your **server** asks Taggor
for the component's HTML already rendered and writes it into the page. The visitor's browser shows the
component as soon as the HTML arrives, with much less layout shift when the script comes later, and the component
is in the HTML your server sends. When the script arrives, the component becomes interactive in place, with the
same elements, and is not drawn again.

It is for a site whose HTML is made by a server or a build step (Next.js, Astro, Express, Rails, Laravel,
Flask, WordPress). It is not for hand-edited static HTML or a closed site builder: there is no server of yours
to ask. The [snippet](https://taggor.dev/docs/snippet.md) alone stays the way to use Taggor, and server rendering adds to it; it
never replaces it.

## The two ways, side by side

The same component, the `faq-accordion` template, on a server-rendered page:

|                                         | Snippet only                                                         | Snippet and server rendering                                               |
| --------------------------------------- | -------------------------------------------------------------------- | -------------------------------------------------------------------------- |
| What the server sends                   | `<faq-accordion headline="Delivery"></faq-accordion>` (an empty tag) | the tag with its shadow root already filled: HTML and CSS of the component |
| What the visitor sees before any script | a gap, or your [fallback content](https://taggor.dev/docs/fallback.md)                   | the component, styled                                                      |
| When the Taggor script arrives          | the component is drawn, and the content below can jump               | the component becomes interactive in place                                 |
| What you add to your server             | nothing                                                              | one call per component (below)                                             |
| What you add to the browser             | nothing                                                              | nothing: the snippet is the same                                           |

In code, the only difference is one line on the server. Express stands for any server here. Snippet only,
the empty tag:

```js
const faq = taggor.element("faq-accordion", { headline: "Delivery" });
```

With server rendering, the tag with the component inside, or the empty tag if anything goes wrong:

```js
const faq = await taggor.render("faq-accordion", { headline: "Delivery" });
```

## How it works

1. Your server calls `taggor.render("faq-accordion", { headline: "Delivery" })`.
2. The helper asks Taggor for `GET <your snippet's origin>/r/<site key>/faq-accordion?headline=Delivery`, with
   your site's **server key** in the `Authorization` header, waiting at most 300 ms.
3. Taggor runs the **published** bundle of the component in an isolated Worker (no network, no access to any
   of Taggor's data) and answers with the tag, a `<template shadowrootmode="open">` holding the component's
   HTML and CSS, and the attribute `ssr="<version>"`.
4. You write that text into the page where the tag would go. The snippet stays exactly as it is.
5. In the browser, the runtime compares `ssr` with the version it is about to mount. If it is the same, it
   keeps the elements already on the screen; if not (the component was updated and your HTML sat in a cache),
   it throws the old ones away and draws the component from scratch.

Whatever goes wrong (Taggor slow or down, the feature off, a component that cannot render without a browser),
`render` returns the **empty tag**, which is what your page has today. It never throws because of the network.

Declarative Shadow DOM, the browser feature behind step 3, is supported from Chrome and Edge 111, Safari 16.4
and Firefox 123 (Baseline "newly available" since February 2024 and "widely available" since August 2026).
A browser without it keeps the template inert inside the tag and the runtime draws the component from scratch,
as it does without server rendering.

## The server key

The site key is public: it is in every page that loads your snippet. So that only your servers spend your
site's server renders (they count against your plan), each request also carries a **server key**, a secret
that only your servers know.

- **Create it** in the portal, on the site's **Install** tab, **SSR** (or with
  `POST /v1/sites/{site_id}/server-keys`). It is shown **once**; Taggor keeps only a hash of it.
- **Keep it on the server.** Put it in the server's environment as `TAGGOR_SERVER_KEY` (your host's secret
  settings, or a `.env` file that is not committed). Never put it in browser code, in the page, in a public
  environment variable (`NEXT_PUBLIC_…`, `VITE_…`, `PUBLIC_…`) or in your repository: anyone with it can spend
  your server renders. The key starts with `tgs_live_`, so secret scanners can recognize a leaked one; if that
  happens, revoke it.
- **Without a key there is no server rendering.** A site with no key, or a request with a missing or wrong key,
  gets no fragment, and the helper writes the empty tag: the page works as it does today. Creating the first
  key is how you turn server rendering on for a site.
- **Rotate without downtime.** A site can hold two keys at once. Create the new one, deploy it to your servers,
  then revoke the old one on the same tab (`DELETE /v1/sites/{site_id}/server-keys/{key_id}`). In the worst
  case Taggor stops accepting a revoked key after about three minutes: up to about two at the edge (the time the
  change takes to reach every location, plus the edge's own 60-second copy), plus up to a minute in the response cache of each helper instance (`cacheSeconds`, per process, so two servers each have
  their own). To cut the second part, create the new key, deploy it, revoke the old one and restart the
  servers, or set `cacheSeconds: 0`.
- The key never goes in a URL: the helper sends it as `Authorization: Bearer <key>`. Taggor does not answer
  this request to a browser on another site, so the key cannot be used from a page.

## The helper

```ts
import { createTaggorServer } from "@taggor/server";

export const taggor = createTaggorServer({
  origin: "https://<the origin your snippet is loaded from>", // the host of /s/<site key>.js
  siteKey: "<the site key>",
  serverKey: process.env.TAGGOR_SERVER_KEY, // the server key, from the server's environment
  ssr: process.env.TAGGOR_SSR !== "off", // the switch: false always returns the empty tag
});

const html = await taggor.render(
  "faq-accordion",
  { headline: "Delivery questions", multiple: true },
  { lang: "en" },
);
```

`@taggor/server` has no dependency and no framework: it is one function that returns a string.

**Options of `createTaggorServer`**

| Option         | Default  | What it does                                                                                                                                             |
| -------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `origin`       | required | The origin of your snippet (`https://…`, no path). `http://` is accepted only on a loopback host.                                                        |
| `siteKey`      | required | The site key of the snippet.                                                                                                                             |
| `serverKey`    | required | The site's server key, from the server's environment (`process.env.TAGGOR_SERVER_KEY`). Missing or malformed: `createTaggorServer` throws a `TypeError`. |
| `ssr`          | `true`   | `false` turns server rendering off: every `render` returns the empty tag and makes no request.                                                           |
| `timeoutMs`    | `300`    | How long one request may take before the empty tag is used.                                                                                              |
| `cacheSeconds` | `60`     | How long a response is reused in this process (`0` for never). A failure is remembered for 5 s, so an outage costs one slow request, not one per page.   |

**`render(tag, attributes?, options?)`** returns a promise of HTML. It throws a `TypeError` only for a tag,
attribute name or nonce that cannot be written in HTML (a mistake in your code), never for anything the network
or Taggor does. `element(tag, attributes?)` returns the empty tag with no request.

- **Attributes:** text as it is; a number becomes text; `true` becomes an empty attribute; a list or an object
  becomes JSON (how a page writes an `array` or `object` prop); `false`, `null` and `undefined` are left out.
  Only the props the component declares reach the HTML, plus `locale`, `lang`, `id` and `class`.
- **`lang`:** the page's language. Without it the component uses its own default language, and the browser
  corrects it if the visitor's is different.
- **`nonce`:** if your page has a CSP with a nonce on `style-src`, pass it: the helper adds it to the
  fragment's style elements.
- **`ssr: false`**, on the helper or on one `render`, turns it off with no request.

## The on and off switch

Turn it off in one place and the page behaves as if the helper were not there:

```sh
TAGGOR_SSR=off node server.js
```

(or `ssr: false` in `createTaggorServer`, or `{ ssr: false }` on one `render`). Nothing else changes: the
snippet still renders the component in the browser.

## Where to write the HTML

The result is HTML text, and each framework has its own way to write raw HTML. The snippet's script tag stays
in the page as usual. The examples use the `faq-accordion` template and a helper module `taggor` made as above,
with `serverKey: process.env.TAGGOR_SERVER_KEY`: in every framework below, set `TAGGOR_SERVER_KEY` in the
**server's** environment and keep that module on the server side.

### Next.js (App Router)

```tsx
// app/faq.tsx (a Server Component)
import { taggor } from "@/lib/taggor";

export async function Faq() {
  const html = await taggor.render("faq-accordion", { headline: "Delivery" }, { lang: "en" });
  return <div suppressHydrationWarning dangerouslySetInnerHTML={{ __html: html }} />;
}
```

`suppressHydrationWarning` is needed: the browser consumes the `<template>` when it creates the shadow root, so
the HTML inside the `<div>` is no longer equal to the text, and without the attribute React logs a hydration
error in development. React does not rewrite the content. Render the page on each request
(`export const dynamic = "force-dynamic"`), or the fragment is frozen at build time. On a client-side
navigation (`next/link`) React inserts the text with `innerHTML`, the browser does **not** create the shadow
root and the component is drawn in the browser, as without server rendering: the gain is in the page load.
Set `TAGGOR_SERVER_KEY` in `.env.local` or the host's environment, **never** as `NEXT_PUBLIC_TAGGOR_SERVER_KEY`
(that prefix copies it into the browser bundle), and import the helper only from Server Components.

### Astro

```astro
---
// src/pages/index.astro (output: "server")
import { taggor } from "../lib/taggor";
const faq = await taggor.render("faq-accordion", { headline: "Delivery" }, { lang: "en" });
---
<Fragment set:html={faq} />
```

Use `output: "server"` (or an on-demand page); on a static build the fragment is made once, at build time, and
goes stale after the component is updated. `TAGGOR_SERVER_KEY` stays a server variable (`process.env`, never a
`PUBLIC_` one), read only in the page's frontmatter.

### Express, or any server template

```js
app.get("/", async (_request, response) => {
  const faq = await taggor.render("faq-accordion", { headline: "Delivery" }, { lang: "en" });
  response.send(`<!doctype html><html lang="en"><body>${faq}
<script async src="https://<your snippet's origin>/s/<site key>.js"></script></body></html>`);
});
```

Start the server with the key in its environment: `TAGGOR_SERVER_KEY=… node server.js`, or your host's secret
settings.

### React Router (framework mode)

```tsx
// app/routes/home.tsx
import { taggor } from "../lib/taggor.server";

export async function loader() {
  return { faq: await taggor.render("faq-accordion", { headline: "Delivery" }, { lang: "en" }) };
}

export default function Home({ loaderData }: { loaderData: { faq: string } }) {
  return <div suppressHydrationWarning dangerouslySetInnerHTML={{ __html: loaderData.faq }} />;
}
```

Keep the helper in a `.server` module so the bundler never sends it (or the key it reads from
`process.env.TAGGOR_SERVER_KEY`) to the browser. Same `suppressHydrationWarning` as in Next.js, and the same
client-side navigation behavior.

### SvelteKit

```js
// src/routes/+page.server.js
import { taggor } from "../lib/server/taggor.js";

export async function load() {
  return { faq: await taggor.render("faq-accordion", { headline: "Delivery" }, { lang: "en" }) };
}
```

```svelte
<!-- src/routes/+page.svelte -->
<script>
  let { data } = $props();
</script>

{@html data.faq}
```

Keep the helper under `src/lib/server/`, which SvelteKit never sends to the browser, and read the key there
(`process.env.TAGGOR_SERVER_KEY`, or `TAGGOR_SERVER_KEY` from `$env/dynamic/private`), never from
`$env/static/public`.

### Nuxt (Vue)

`v-html` **does not work** here. When Vue hydrates it sets the element's `innerHTML` again, which removes the
shadow root (the browser prints "Found declarative shadowrootmode attribute on a template, but declarative
Shadow DOM is not being parsed") and the component is drawn in the browser from scratch. Write the fragment
into the HTML on the server, after Vue rendered it, so Vue never sees it:

```ts
// server/plugins/taggor.ts (a Nitro plugin; `taggor` is auto-imported from server/utils/taggor.ts)
export default defineNitroPlugin((nitro) => {
  nitro.hooks.hook("render:html", async (html) => {
    const slot = '<div data-taggor="faq-accordion"></div>';
    if (!html.body.some((part) => part.includes(slot))) return;
    const faq = await taggor.render("faq-accordion", { headline: "Delivery" }, { lang: "en" });
    html.body = html.body.map((part) =>
      part.replace(slot, () => `<div data-taggor="faq-accordion">${faq}</div>`),
    );
  });
});
```

```vue
<!-- app/app.vue -->
<template>
  <div data-taggor="faq-accordion" />
</template>
```

`server/utils/taggor.ts` runs only in Nitro; read the key there from `process.env.TAGGOR_SERVER_KEY` (or a
private `runtimeConfig` key), never from `runtimeConfig.public`.

### Python (Flask), without a JavaScript helper

Any language can ask for the fragment with one HTTP request. The rule is the helper's: the server key in an
`Authorization: Bearer` header (never in the URL), a short timeout; if the answer is `200` with
`content-type: text/html`, starts with `<tag` and ends with `</tag>`, write the body; in every other case
write the empty tag.

```python
import json
import os
from html import escape
from urllib.parse import urlencode
from urllib.request import Request, urlopen

ORIGIN = "https://<the origin your snippet is loaded from>"
SITE_KEY = "<the site key>"
SERVER_KEY = os.environ["TAGGOR_SERVER_KEY"]  # the server key, from the server's environment


def render(tag, attrs=None, lang=None, timeout=0.3):
    attrs = dict(attrs or {})
    if lang:
        attrs["lang"] = lang
    text = {}
    for name, value in attrs.items():
        if value is False or value is None:
            continue
        text[name] = "" if value is True else json.dumps(value, ensure_ascii=False) if isinstance(value, (list, dict)) else str(value)
    bare = "<%s%s></%s>" % (tag, "".join(' %s="%s"' % (n, escape(v)) for n, v in text.items()), tag)
    try:
        url = "%s/r/%s/%s?%s" % (ORIGIN, SITE_KEY, tag, urlencode(text))
        headers = {"Accept": "text/html", "Authorization": "Bearer " + SERVER_KEY}
        with urlopen(Request(url, headers=headers), timeout=timeout) as response:
            body = response.read(1_048_577).decode("utf-8")
            ok = response.status == 200 and response.headers.get_content_type() == "text/html"
    except Exception:  # Taggor slow or down: never break the page
        return bare
    return body if ok and body.startswith("<" + tag) and body.endswith("</%s>" % tag) else bare
```

In Flask, wrap the result in `markupsafe.Markup` so the template does not escape it:
`{{ faq }}` with `faq = Markup(render("faq-accordion", {"headline": "Delivery"}, lang="en"))`.

### PHP and WordPress

The same request, with a short timeout.

```php
function taggor_render(string $tag, array $attrs = [], string $lang = ''): string {
    if ($lang !== '') { $attrs['lang'] = $lang; }
    $text = [];
    foreach ($attrs as $name => $value) {
        if ($value === false || $value === null) { continue; }
        $text[$name] = $value === true ? '' : (is_array($value) ? json_encode($value, JSON_UNESCAPED_UNICODE) : (string) $value);
    }
    $bare = "<$tag";
    foreach ($text as $name => $value) { $bare .= ' ' . $name . '="' . htmlspecialchars($value, ENT_COMPAT) . '"'; }
    $bare .= "></$tag>";
    $url = 'https://<the origin your snippet is loaded from>/r/<the site key>/' . $tag . '?' . http_build_query($text);
    // The server key, from the server's environment (wp-config.php or the host's settings).
    $key = getenv('TAGGOR_SERVER_KEY');
    $context = stream_context_create(['http' => ['timeout' => 0.3,
        'header' => "Accept: text/html\r\nAuthorization: Bearer $key\r\n"]]);
    $body = @file_get_contents($url, false, $context);
    $ok = $body !== false && str_contains($http_response_header[0] ?? '', ' 200')
        && str_starts_with($body, "<$tag") && str_ends_with($body, "</$tag>");
    return $ok ? $body : $bare;
}

// WordPress: a shortcode that writes the component. The snippet stays in the theme as usual.
add_shortcode('taggor_faq', fn() => taggor_render('faq-accordion', ['headline' => 'Delivery'], get_locale() === 'pt_BR' ? 'pt-BR' : 'en'));
```

Use the shortcode `[taggor_faq]` in a post or a template. A page cache plugin stores the page with the
fragment in it, so a component update shows after that cache expires (see Limits).

## Limits

- **No personal data in attributes.** The attributes travel in the URL of the request to Taggor. Do not pass an
  email, a name, a document or anything about the logged-in visitor. For content that is per visitor, let the
  component render in the browser (`ssr: false`).
- **Fallback content.** A tag with a declarative shadow root hides whatever you put inside it. Use fallback
  content or server rendering in a place, not both.
- **Clock and state.** The server renders the component's first state. What depends on the time (a countdown)
  comes out with the time of the render and is corrected when the script arrives.
- **Component updates.** After a promote, the HTML in your caches (60 s in the helper, plus your page's cache)
  is still the previous version. The visitor sees it until the script arrives, and then the new one.
- **Client-side navigation.** A framework that inserts the HTML text in the browser after a client-side
  navigation gets no shadow root from the browser, so no server render: the component is drawn in the browser
  as it is without this feature. The gain is on the page load.
- **A prop called `ssr`.** A component that declares a prop with that name is not rendered on the server.
- **Form field components get no server render.** A component made with `useFormField` cannot be rendered on
  the server: the render is refused and the helper writes the bare tag, with its attributes. It works as it
  does today (the browser draws the field); you lose only the early render.
- **Fonts, images and SVGs work.** A component that imports a font, an image or an SVG renders on the server:
  the server only writes the file's public address (`<img src="https://…/a/<hash>.png">`, the same one the
  browser uses), it downloads nothing, and the browser fetches the file as it does without this feature.
- **What does not run on the server.** The render has no network and no page: `fetch`, `XMLHttpRequest`,
  `WebSocket` and `import()` of a URL do not work there (a call that is only started gets no answer, and the
  fragment comes out without that data), and `window`, `document` and `useFormField` make the render fail, so the
  helper writes the bare tag and the browser draws the component. Fetch data in the browser, after the script has
  taken over (`useEffect`, or `useTaggorData`).
- **The `style` attribute under a strict CSP.** The helper's nonce covers the fragment's style elements,
  not a `style` attribute. A component that sets the `style` prop renders an attribute that a `style-src`
  without `'unsafe-inline'` blocks: that element shows without that style until the script arrives, and then
  the style is applied through a route the policy allows. Styles written in the component's CSS are not
  affected. See [the CSP section](https://taggor.dev/docs/snippet.md#content-security-policy).
- **Server style elements stay.** After the runtime takes over, the component's shadow root still holds the
  style elements from the server next to the stylesheets the runtime adopts, with the same rules. Nothing
  changes on screen.
- **The leftover `<template>` is inert.** After a client-side navigation the tag may hold the `<template>`
  text unparsed; the browser never renders a template, and the component is drawn once, in the browser.
- **No state at the top level of the component's module.** A warm render Worker serves every request for that
  version, from every site that uses it, so a variable outside the component (a counter, a cache, the last value
  seen) leaks from one render to the next. Keep state inside the component.
- **Slots and stored data.** The server never sees the content you put inside the tag, so a slot comes out
  empty from the server and your content appears once the script has taken over. A component that reads
  stored data (`useTaggorData`) renders in its idle state on the server and loads the data in the browser.
- **Plan allowance and price.** Server renders count against a monthly allowance of your plan, and only requests
  with your server key can spend it. On Free, a render past the allowance is not served: the component is drawn in
  the browser as it is without this feature. On Pro and Agency, going over the allowance does not switch your components
  off: server renders that go past the allowance (a render served from the cache is not counted) are billed at the end
  of the month, and so is each component version rendered on the server in a day (no amount of those is included),
  with the exceptions listed in Limits and billing; an account that cannot be billed keeps the cut. The prices are on the pricing page and the rules (optional spending
  limit, minimum bill) in [Limits and billing](https://taggor.dev/docs/limits-and-billing.md).
- **A leaked server key** lets someone else spend that allowance, and on a paid plan run up server renders you are
  billed for, until you revoke it. Revoke it on the site's
  Install > SSR tab and deploy a new one; a key committed to a repository counts as leaked.

## What the content in the HTML does and does not mean

The component's content is in the first HTML your server sends, and a browser shows it **without running any
script**, even with JavaScript turned off. Whether another program that reads HTML extracts that
text depends on how it treats Declarative Shadow DOM. Among HTML libraries, cheerio, linkedom,
htmlparser2, html-to-text, BeautifulSoup with `html5lib`, `lxml.html` and html2text extract the text, some
extract part of it, and jsdom (so `@mozilla/readability`), turndown and BeautifulSoup's `get_text()` with
`html.parser` or `lxml` extract nothing, because they treat the template as inert. Without server rendering
none of them extracts anything from the component.

What this feature changes is **when the component's content appears** and how much the page moves around it: the
content is in the first HTML, so it appears with the page and not when the script arrives, and the layout shift
the component causes stays close to zero.

## Frameworks

With every framework below, the shadow root exists before the Taggor script runs, the same elements are still
there after the framework hydrates and after the runtime takes over, a click on the first question sets
`aria-expanded="true"`, and the console shows no hydration warning. The examples use the `faq-accordion`
template.

Without `suppressHydrationWarning`, Next.js logs a hydration error in the browser console in development; React
Router hydrates with the same React mechanism and needs the same attribute. The page still works.

| Framework                     | Version                              | Result                                                                                        |
| ----------------------------- | ------------------------------------ | --------------------------------------------------------------------------------------------- |
| Next.js (App Router)          | 16, React 19                         | Works with `suppressHydrationWarning`; without it React logs a hydration error in development |
| Astro                         | 7, Node adapter (`output: "server"`) | Works with `set:html`                                                                         |
| Express                       | 5                                    | Works                                                                                         |
| React Router (framework mode) | 8, React 19                          | Works with `suppressHydrationWarning`                                                         |
| SvelteKit                     | 3, `adapter-node`                    | Works with `{@html}`                                                                          |
| Nuxt                          | 4, Vue 3                             | `v-html` loses the shadow root; the Nitro `render:html` hook works                            |
| Flask (Python)                | 3                                    | Works, with the request written without a JavaScript helper                                   |

In Chromium, Firefox and WebKit the fragment is visible and styled before any script, the runtime keeps the
server's elements and discards a fragment of another version.

Components with slots (native and `useSlot`), with stored data (`useTaggorData`) and a CSP with a nonce work in
the same browsers, and so does Next.js 16 with React 19 on page load and on client-side navigation, with no
console error. The limits listed above apply: form fields get no server render, a `style` attribute waits for
the script under a strict CSP, and server style elements stay in the shadow root.
