# Site code

Add analytics, tag managers and other code to every published page, safely, and check it against your site's Content Security Policy.

Site code is the code every published page carries: an analytics tag, a tag manager,
a chat widget, a verification `<meta>` tag, structured data. It is kept in one place
for the whole site, in its head and at the end of its body, and it never runs inside
the admin.

> [!WARNING]
> Site code is experimental: the route, `<SiteCode>`, the CSP helpers and the
> Settings editor may change before it is stable.

## Add it in Settings

In the page builder, open **Settings**, then **Site settings**, and find **Code**. The section says what each place
holds in plain words ("A script from [www\.googletagmanager.com](http://www.googletagmanager.com), an inline script") and
who changed it last. **Add code** or **Edit code** opens the code itself, one box for
the head and one for the end of the body.

**Save code** checks the code on the server before anything is saved:

* What can't be stored is listed under the place it is in, with the reason, and
  nothing is saved. Your text stays as you typed it.
* What your site's security policy would block is listed with the directive that
  blocks it and the policy that does. The section shows what to add to your policy,
  with a **Copy** button. **Save anyway** is enabled once you tick that you understand
  the blocked code won't run until the policy allows it.
* Before saving, the section also shows what won't be kept (an HTML comment, say)
  and what a Report-Only policy would report. With no policy known, it says so
  rather than reading as a pass.

The check reads the policy your home page is sent with, as a visitor gets it, from the
address the admin is open on: `<SiteCode>` renders in the same app as the admin, so
that is where your pages are served. It is checked as well as the policy you declare
(below), which is the one to rely on if a proxy sends a different policy on another
domain. Leaving Settings with unsaved code asks first.

## Who can add it

Anyone who may change the site's settings (the **Manage page builder site settings**
permission) may add site code. Code here runs on every page, with the access of
whoever views it, signed-in staff included. Only add code from sources you trust, and
never put a secret in it: it is printed into every page's HTML.

* A save is a signed-in person's alone. An API key can read site code but never save
  it, so a leaked key can't put a script on every page.
* Every save writes an audit row with the code's hashes, sizes and counts, and the
  origins it loads scripts from. The code itself is kept in the site code Single's
  versions, not in the audit log.

## What it may hold

Code is checked on the server when it is saved, and anything off the list is refused
with a reason, never quietly removed, so what is stored is what you wrote:

| Where                | Elements                                                                                   |
| -------------------- | ------------------------------------------------------------------------------------------ |
| Head and end of body | `<script>` (code, a module or JSON-LD), `<style>`                                          |
| Head only            | `<meta>` (no `http-equiv`), `<link>` (hints, stylesheets, icons, the manifest, alternates) |
| End of body only     | `<noscript>` holding one `<img>` or `<iframe>`, the pixel tag managers use                 |

Event handler attributes (`onload=`), a `nonce`, `<base>`, `<iframe>` outside
`<noscript>`, and any URL that isn't `https:` or a path on your site are refused,
including URLs a stylesheet loads. So are a referrer `<meta>` tag and a link whose
`referrerpolicy` sends a page's full address (`unsafe-url`,
`no-referrer-when-downgrade`): they would tell other sites the address of every
page, the admin's included. Each place holds up to 50,000 characters and 40
elements.

## Page code

People who may change the site's settings can also add code to **one page**, from the
**Code** tab in that page's **Page settings**. It is checked exactly as site code is, with
the same rules and the same Content Security Policy check, and kept in the page's own
document (`settings.code`): it is saved in the page's
draft, goes live when the page is published, is kept in the page's history, and comes
back when an older version is restored. Where the page's Page Builder field is kept per
language, each language keeps code of its own, and a translated page draws its own. Only a page's own Page Builder field, at the top
of the page, keeps code: a field inside a group, a list or a field group offers no Code tab,
and the server refuses code there, as it does on a collection template, a saved section or a component.

The server judges it again on every write that changes it, however the write was made:
it refuses the change from anyone without the **Manage page builder site settings**
permission and from any API key, refuses what the rules can't store, and keeps code the
site's declared policy would block only where the author acknowledged exactly those
findings. Each committed change writes an audit row with the page, the field, and the
code's hashes, sizes and counts, never the code.

Duplicating a page keeps its page code, for someone without the permission and for an API
key, when the code is a byte-for-byte copy of what the source holds in a version the person
copying could read. Code the source doesn't hold, or one changed on the way, is still
refused to them.

The permission guards **changing** page code, not reading it. Anyone who may edit the page
can read its code: the draft's, the published version's and every version in its history,
through the API and in the document the builder loads, even though the builder only shows
the **Code** tab to people with the permission. The published code is also printed into the
page's HTML for every visitor. So never put a secret in page code, or in site code: an API
token, a private key or a password belongs in your server's environment, read by your own
server code, never in code a browser runs.

Published pages carry it with no change of your own where the route spreads
`pageBuilderContent()` into `createPublicContentPage` or `createContentPage`: the route draws
the page's head code before the page and its end-of-body code after it, from the page's own
document. It runs after the site's code in each place: the site's head, then the page's head,
then the site's end of body, then the page's end of body. Nothing runs under draft mode, as
for site code. A route of your own can draw it with `<PageCode slot="head" document={...} />`
from `@nextlyhq/plugin-page-builder/site`. On a site with a nonce-only policy, give the route's
`pageBuilderContent({ nonce: () => ... })` the request's nonce, as you give it to
`<SiteCode nonce={nonce} />`; both places of the page's code carry it. Reading the nonce makes
every page the route serves request-time, so with Cache Components the route must render under a
`<Suspense>` boundary, as any route reading the request does. A site whose policy allows the
loaders by hash leaves `nonce` out, and its pages stay prerendered.

A page whose code starts scripts or styles is loaded, and left, as a whole document. Reached
from another page by a link the site follows without a full load, it loads again so its code
starts; left that way, the next page loads in full, so none of its scripts or styles stay
behind on other pages.

The page's head code is started by the same loader as site code. Its end-of-body code is
started by a loader of its own, which waits until the site's code has started. A site whose
Content Security Policy allows loaders by hash allows that loader's hash too, and the Code
tab's check names it.

The builder's canvas never runs page code.

## Put it on your pages

Render `<SiteCode>` in your **public site's** layout, once for each place. Never put
it in a root layout the admin shares: put it in the layout of the route group your
site's pages live in.

```tsx title="app/(frontend)/layout.tsx"
import { SiteCode } from "@nextlyhq/plugin-page-builder/site";
import type { ReactNode } from "react";

export default function SiteLayout({ children }: { children: ReactNode }) {
  return (
    <>
      <SiteCode slot="head" />
      {children}
      <SiteCode slot="body" />
    </>
  );
}
```

`<SiteCode>` is a server component. It reads the stored code through Nextly's cache,
so pages stay static and a save refreshes every page.

### With Cache Components

Nextly runs with Cache Components on, and an app made by `create-nextly-app` has it.
There, `<SiteCode>` reads through your app's own `"use cache"` function, kept in
`src/nextly/cached-read.ts`: an app made by `create-nextly-app` has the file and imports
it from its root layout. Add both if your app doesn't have them:

1. Create `src/nextly/cached-read.ts` with the file the caching guide gives under
   [Cache Components](https://nextlyhq.com/docs/guides/isr-caching.md#cache-components).
2. Import it from the layout that renders `<SiteCode>`. That one import registers the
   cached read, and how Nextly starts when a read finds it not started, on every page
   that layout serves, before `<SiteCode>` reads. Both matter during `next build`,
   where nothing else starts Nextly for a page such as `/_not-found` that only the
   root layout renders. Nothing starts as the file loads, so a page that starts
   Nextly with options of its own still does:

```tsx title="app/(frontend)/layout.tsx"
import "@/nextly/cached-read";
import { SiteCode } from "@nextlyhq/plugin-page-builder/site";
```

Use a relative path where your app has no `@/` alias.

Without the function, the read would fall back to `unstable_cache`, whose first read
is a database query that can still be running when Next.js finishes prerendering a
page, so a build would fail some of the time. `<SiteCode>` refuses that read instead:
the build stops with an error naming the file and the line to add. With Cache
Components off, nothing changes, and the file is not needed. A `read` you pass to
`<SiteCode>` yourself is used as given.

### It keeps itself out of the admin

The admin, the editor's canvas and the preview pane are all served from your site's
origin, so code running in any of them could read and drive the admin. `<SiteCode>`
guards against this even when it is mounted in the wrong place:

* It renders nothing in draft mode, which the preview pane uses.
* Scripts, styles and stylesheet links are written to the page as data, not as
  elements. A small loader builds them only on a page that isn't framed by your own
  site (the canvas and the preview are), isn't under `/admin`, and isn't the canvas.
  Pass `skip` to name more paths, as the app names them (a base path is added for you):
  `<SiteCode slot="head" skip={["/admin", "/studio"]} />`. A path either place skips is
  skipped in both, even when that place holds no code.
* Meta tags, link hints, icons, structured data and the no-script pixel run nothing,
  so they are written as they are, where crawlers and pages without scripting see
  them.

Because the loader starts scripts as the page finishes parsing, they run in order
but after the page's own markup. Two things follow:

* A script that writes into the page as it loads (`document.write`) doesn't work as
  site code.
* The loader waits for an external script before starting the next entry, and the
  head's code finishes so before the end of the body's starts. It doesn't wait for a
  stylesheet. A script that reads the styles a stylesheet in site code sets
  should wait for that stylesheet's `load` event, or come from your own code.

## Your Content Security Policy

Nextly doesn't set a policy on your site's pages: your proxy or headers do. Declare
the same policy to the plugin, and site code is checked against it before it is
saved:

```ts title="nextly.config.ts"
import { pageBuilder } from "@nextlyhq/plugin-page-builder";

export const pageBuilderPlugin = pageBuilder({
  siteCode: {
    // The policy your proxy sends. A function is read on each check.
    csp: "default-src 'self'; script-src 'self' 'unsafe-inline' https://www.googletagmanager.com",
  },
});
```

A check reports each entry the policy would block, and which directive blocks it.
Code that a policy would block is saved only once you have seen exactly those
findings and confirmed. With no policy declared, the check says that nothing was
checked.

How each kind of policy takes site code:

* **No policy:** nothing to do.
* **`'unsafe-inline'` with host lists:** add the hosts the check names. Inline code
  and the loader already run.
* **A nonce:** pass the nonce to `<SiteCode nonce={nonce} />` and set
  `siteCode: { siteNonce: true }`. The loader carries the nonce and gives it to
  everything it builds. Reading the nonce makes the page dynamic, as a nonce-based
  policy already does.
* **Hashes:** add the hash of each inline script and style, and the loader's own
  hash, which never changes. The check names every one it is missing.
* **`'strict-dynamic'`:** allow the loader, by its hash or the nonce. Every script it
  builds then runs, inline or loaded, so they need no hashes or hosts of their own.

`mergeSiteCodeIntoCsp` adds what site code needs to a policy and nothing more. It
adds only what the policy blocks now. It never adds a hash where the policy relies on
`'unsafe-inline'`, since a hash would cancel it. It puts additions for scripts and
styles in `script-src-elem` and `style-src-elem`, so workers and style attributes
gain nothing. Browsers from before those directives (Chrome 75, Firefox 108,
Safari 15.4) read only `script-src` and `style-src`, and don't see the additions.

```ts
import {
  mergeSiteCodeIntoCsp,
  sanitiseSiteCode,
  siteCodeFacts,
} from "@nextlyhq/plugin-page-builder";

const { entries } = sanitiseSiteCode(
  '<script async src="https://www.googletagmanager.com/gtag/js?id=G-1"></script>',
  "head"
);
const facts = await siteCodeFacts(entries, "https://example.com");
const policy = mergeSiteCodeIntoCsp("script-src 'self' 'sha256-abc'", facts);
```

What a running script loads afterwards (its own requests, the images it adds) can't
be seen before it runs, so the check doesn't cover it.

Site code doesn't support Trusted Types yet. Under a policy with
`require-trusted-types-for 'script'`, the loader can't build scripts, so none
runs; the check reports this on the first script. Styles still apply.
