# Add adaptive copy to a page

```bash
npm install @sparkletree/core @sparkletree/react
npx @sparkletree/cli init --origin https://yoursite.com
npx @sparkletree/cli doctor --url https://yoursite.com
```

SparkleTree adapts the words in your page. Point at copy you already have, a
button label, a form heading, a paragraph, and it returns a version written
for the visiting context: time of day, device, language, referring site, plus
anything you declare yourself. You write the copy that ships with your app.
SparkleTree replaces it when an adapted version is available and leaves yours
alone when it is not. The same provider also plays whole campaign creative,
a hero or a CTA, managed from your dashboard.

It changes text and a few theme colours. It does not change your markup, your
layout, or your CSS, it ships no stylesheet, and it renders no iframe. If every
request fails, your page still shows the copy you wrote.

No account yet? `npx @sparkletree/cli dev` runs a local mock of the
SparkleTree edge, and the [runnable examples](https://docs.sparkletree.io/developers/sdk/examples.md)
stream from it with no configuration at all. See
[Test without an account](https://docs.sparkletree.io/developers/sdk/testing.md). Sign up at
[app.sparkletree.io](https://app.sparkletree.io) when you want real copy.

## Install the packages

```bash
npm install @sparkletree/core @sparkletree/react
```

React 18 or later, Node 18 or later, ESM only.

## Set up the project with `init`

```bash
npx @sparkletree/cli init --origin https://yoursite.com
```

In a terminal, `init` does what the dashboard steps below would otherwise
ask of you:

1. It signs you in through the browser when you are not signed in yet: open
   the address it prints, check the code, approve.
2. It registers `https://yoursite.com` as a site of your workspace, so a live
   key works there. Repeat `--origin` for more sites, your staging host and
   `http://localhost:3000` included. Registering needs the admin role.
3. It picks the campaign: the only one your workspace can serve, or the one
   you choose when there are several (`--campaign <id>` chooses up front).
4. It writes four lines into `.env.local` and keeps every other line of the
   file as it was:

```bash
# SparkleTree (written by sparkletree init)
NEXT_PUBLIC_SPARKLETREE_KEY=st_pk_test_…
NEXT_PUBLIC_SPARKLETREE_API_BASE=https://p.qrtree.ai
NEXT_PUBLIC_SPARKLETREE_ORG_ID=6f1c2a4e-…
NEXT_PUBLIC_SPARKLETREE_CAMPAIGN_ID=9b8e7d6c-…
```

The prefix follows your framework, read from `package.json`: `NEXT_PUBLIC_`
for Next.js, `VITE_` for Vite, `PUBLIC_` for Astro and SvelteKit, none for
Remix and for a project without a framework. `--framework` sets it. The key is the test key, for a page on localhost; the
result also prints the same lines with the live key, for your production
environment. Both keys are public. The sign-in token is secret and is never
written into your project.

`init` checks everything that can stop it before it registers a site or
writes a file. When `.env.local` is not covered by `.gitignore` it says so;
`--yes` adds the line. `--dry-run` shows what it would do and changes
nothing.

### From an agent or a script

`init --json`, or `init` without a terminal, never opens a browser sign-in
and never asks a question. Sign in first, once, in a terminal, or set
`SPARKLETREE_TOKEN`:

```bash
npx @sparkletree/cli login
npx @sparkletree/cli init --json --framework next --origin https://yoursite.com --campaign 9b8e7d6c-5a4f-4e3d-8c2b-1a0f9e8d7c6b
```

Stdout then holds one JSON document. Without a sign-in it is
`{"ok":false,"error":"not_signed_in",…}` at once. With several campaigns and
no `--campaign` it is `{"ok":false,"error":"choose_campaign","campaigns":[…]}`:
run it again with one of those ids. Every failure carries a `reason` and a
`remedy`, and the exit code is `0` on success, `1` on an error and `2` on
wrong usage. The full output is in [the CLI reference](https://docs.sparkletree.io/developers/sdk/cli.md#init).

## Wrap the part of your app that uses SparkleTree

One provider per page view. In Next.js, put it in your root layout.

```tsx
import { SparkletreeProvider } from "@sparkletree/react";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <SparkletreeProvider
          publishableKey={process.env.NEXT_PUBLIC_SPARKLETREE_KEY!}
          apiBase={process.env.NEXT_PUBLIC_SPARKLETREE_API_BASE}
          organizationId={process.env.NEXT_PUBLIC_SPARKLETREE_ORG_ID}
        >
          {children}
        </SparkletreeProvider>
      </body>
    </html>
  );
}
```

The key alone is enough: it carries your workspace id and API base, and the
provider reads them from it. `apiBase` and `organizationId` are optional;
when set, they override what the key says.

Or let the CLI write the provider: `npx @sparkletree/cli add provider` copies
one into `components/sparkletree/provider.tsx`, written for the framework in
your `package.json` (`--framework` sets it), that reads the names `init`
wrote:

| Framework | The provider reads |
|---|---|
| Next.js | `process.env.NEXT_PUBLIC_SPARKLETREE_KEY` |
| Vite | `import.meta.env.VITE_SPARKLETREE_KEY` |
| Astro | `import.meta.env.PUBLIC_SPARKLETREE_KEY` |
| SvelteKit | `env.PUBLIC_SPARKLETREE_KEY` from `$env/dynamic/public` (SvelteKit's `import.meta.env` carries only `VITE_` names) |
| Remix, none | Nothing: there is no public env convention, so the provider takes `publishableKey` as a prop. In Remix, read `SPARKLETREE_KEY` from `process.env` in your root loader and pass it down. `init` prints the same note. |

It reads `…_API_BASE` and `…_ORG_ID` the same way and passes them when they
are set, so a project set up before `init` wrote the key keeps working with
those two alone. Each variable is read by its full name, because Next.js and
Vite put a public value into the browser bundle only where the code spells
it out. A missing variable stops the page at load with an error that names
it and says that `npx @sparkletree/cli init` writes it.

In a single-page app, call `pageVariants.reset()` (exported from
`@sparkletree/react`) when your router changes route. A route change is a
new page view, and the per-page-view experiment pinning needs to know.

The publishable key is a signed credential minted in the dashboard. Every
stream request must carry it. A test key (`st_pk_test_`) works from a page
on localhost (`http://localhost`, `127.0.0.1`, `[::1]`, any port) and from a
server; from any other site the site must be registered to your
organization, test key or live key (`st_pk_live_`). From localhost a
fragments group shows copy that is already written and its fallbacks
otherwise: the hosted edge writes no new fragment copy for a loopback
origin (see [Test keys are for development](https://docs.sparkletree.io/developers/sdk/origins-and-privacy.md#test-keys-are-for-development)). Treat it like any client-side key: it is visible in page
source, so protection comes from the origin registry and rate limits; rotate
it from the dashboard if it leaks.

Self-hosting the API? Pass `apiBase` and `organizationId` explicitly alongside
the key (explicit props win for addressing; the key is still sent).
[Signed minting](https://docs.sparkletree.io/developers/sdk/signed-minting.md) explains why that is
required rather than preferred.

## Adapt copy you already have

Name a piece of your own copy, say what it says today, and render the result.
There is nothing to create in a dashboard first. The keys and fallback
strings you write are the request:

```tsx
import { useFragments, FragmentText } from "@sparkletree/react";

function SignupButton() {
  const f = useFragments({
    context: { page: "pricing", intent: "signup" },
    fields: { cta: { kind: "cta", fallback: "Start your free trial" } },
  });
  return (
    <button onClick={() => startCheckout()}>
      <FragmentText field={f.cta} />
    </button>
  );
}
```

One `useFragments` call can carry a whole form's worth of fields, written
together so they agree with each other. See
[Fragments](https://docs.sparkletree.io/developers/sdk/fragments.md) for groups, kinds and swap rules.

## Play a campaign: render a hero and a button

Campaign islands play whole creative managed from your dashboard. This is
where the campaign id `init` wrote comes in:

```tsx
import { Hero, Cta } from "@sparkletree/react";

const campaignId = process.env.NEXT_PUBLIC_SPARKLETREE_CAMPAIGN_ID!;

export function Landing() {
  return (
    <>
      <Hero
        campaignId={campaignId}
        fallback={{
          headline: "Software that meets the moment",
          body: "Adaptive creative for the whole funnel.",
        }}
      />
      <Cta campaignId={campaignId} fallback={{ cta: "Start free" }} href="/signup" />
    </>
  );
}
```

That is the whole integration. `fallback` is the only required prop besides the
campaign id. `npx @sparkletree/cli add hero cta` copies the same two
components into your repo instead, if you want to own their markup; see
[the CLI](https://docs.sparkletree.io/developers/sdk/cli.md#add).

## Check the setup

```bash
npx @sparkletree/cli doctor --url https://yoursite.com
```

`doctor` checks the installed packages, the key in your env file, that the
edge accepts the key from your site, that the campaign can be served, and,
with `--url`, your page's Content Security Policy. Every problem comes with
the fix. See [Check your setup](https://docs.sparkletree.io/developers/sdk/setup-checks.md).

## Write the fallback as copy you would ship on its own

The text in `fallback` is what a visitor reads whenever the adapted version is
late, missing, or never coming: a slow network, a paused campaign, our service
down. Until then the block holds rather than flashing copy the stream is about
to replace. Your fallback is there but invisible, occupying its exact space, so
nothing moves whichever way the wait ends. There is no skeleton and no
spinner. See [What your visitors see](https://docs.sparkletree.io/developers/sdk/what-visitors-see.md).

Write it as the only version of the copy. For some visitors it is.

## Check the failure path before the happy path

Run the mock edge with a failure:

```bash
npx @sparkletree/cli dev --failure offline
```

Put the env lines it prints in your development env file (for example
`.env.development.local`), restart your dev server and load the page. You
should see your fallback copy, fully readable, with no adapted provenance
stamped and no layout shift. That is the behaviour that runs during an
incident, so it is the one worth verifying first. Every failure the mock can
act out is in [Test without an account](https://docs.sparkletree.io/developers/sdk/testing.md).

## Style it with your own CSS

The npm components ship no stylesheet. They render class hooks and CSS custom
properties for campaign colours: `.st-hero`, `.st-hero-headline`, `.st-cta`,
`.st-stream-text`. Style them like any other element in your
design system.

## Without the CLI: the dashboard

Everything `init` does can be done by hand:

| You need | Where it comes from |
|---|---|
| A publishable key (`st_pk_live_…` / `st_pk_test_…`) | Settings > Embedding in your dashboard. It encodes your workspace id and API address. |
| A campaign id | Campaign islands only. The campaign lives in your dashboard; a surface id (a named screen or placement that decides what plays there) works instead. Fragments need no dashboard object at all. |
| Your site's origin, registered | Settings > Embedding > Origins. Requests from an unregistered origin fail CORS. See [Origins, CSP and privacy](https://docs.sparkletree.io/developers/sdk/origins-and-privacy.md). |

Put the key in `NEXT_PUBLIC_SPARKLETREE_KEY` (or your framework's name for
it) and pass it to the provider as above.

## Before you ship

Two steps stand between "works on my machine" and production:

- **Register your production origin and use the live key there.**
  `npx @sparkletree/cli init --origin https://yoursite.com` registers it and
  prints the lines for production. Every request from an unregistered origin
  fails CORS. See [Origins, CSP and privacy](https://docs.sparkletree.io/developers/sdk/origins-and-privacy.md).
- **Wire signed minting.** Reading copy is free and unauthenticated; *writing*
  new copy spends your credits, and workspaces created after 2026-08-09
  refuse unsigned mints by default. Without a token endpoint your fragments
  serve fallbacks forever, silently in production and with a console warning
  in dev. [Signed minting](https://docs.sparkletree.io/developers/sdk/signed-minting.md) is a ~20-line
  backend route.

## Where to go from here

- [Fragments](https://docs.sparkletree.io/developers/sdk/fragments.md): adaptive copy for anything you can name, under keys you choose.
- [What your visitors see](https://docs.sparkletree.io/developers/sdk/what-visitors-see.md): the behaviour rules that change what you write.
- [Provider, components and useIsland](https://docs.sparkletree.io/developers/sdk/components.md): every prop.
- [The CLI](https://docs.sparkletree.io/developers/sdk/cli.md): every command, with its JSON output.
- [When things go wrong](https://docs.sparkletree.io/developers/sdk/when-things-break.md): slow networks, paused campaigns, outages.
