How to use the Webflow custom code API to push scripts to specific pages

How to use the Webflow custom code API to push scripts to specific pages

Register a script once and apply it to chosen Webflow pages from code. A safe read-merge-write pattern, tested TypeScript and fixes for common API errors.

How to use the Webflow custom code API to push scripts to specific pages

Ismail Ajagbe
Technical Author
View author profile
Ismail Ajagbe
Technical Author
View author profile
Table of contents

Register a tracking script once, then apply it to the exact landing pages that need it from code, without wiping the scripts already there.

Pushing a campaign pixel to many landing pages by hand in the Designer takes time, and you repeat the work for every new tag. The Webflow Data API lets you register a script once and apply it to the pages you choose from code.

The risk sits in how the page endpoint writes. It replaces the whole list of scripts on every request, so a careless call removes scripts that another app or teammate added.

I build a read-merge-write function that reads the page first, then writes back the full list with your script merged in. A publish at the end makes the change live.

Access works differently from most Webflow API calls. These endpoints need an OAuth token from a Webflow App, and a site token cannot reach them. Setup starts with that token.

What do you need to apply custom code via the Webflow Data API?

You need an OAuth token from a Webflow App. You also need the site and page IDs you're targeting and the script itself.

Each requirement has a constraint worth settling before you write code.

A Webflow App with OAuth (not a site token)

Site tokens can't reach the custom code endpoints. The custom_code:read and custom_code:write scopes are available only to a Webflow Data Client App, which authenticates through OAuth.

Webflow's own custom code tutorial requests sites:read, sites:write, pages:read, pages:write, custom_code:read and custom_code:write. Together, these scopes cover listing pages and applying scripts, and they let you publish the site afterward.

Once your App completes the OAuth flow, set the access token and site ID as environment variables in the terminal you'll run the scripts from:

export WEBFLOW_OAUTH_TOKEN="your-oauth-access-token"
export WEBFLOW_SITE_ID="your-site-id"

The scripts below run on Node.js 20 or later with tsx (a TypeScript runner for Node.js), and they use the built-in fetch API, so they need no Webflow package. If you prefer Webflow's SDK, the webflow-api package wraps the same endpoints.

Adding the request helper

Every script imports one small helper that adds the token to each request and retries once on a 429:

// webflow.ts
const API = process.env.WEBFLOW_API_BASE ?? "https://api.webflow.com/v2";
const token = process.env.WEBFLOW_OAUTH_TOKEN;
if (!token) {
  throw new Error("Set WEBFLOW_OAUTH_TOKEN to your Webflow App's OAuth access token.");
}

export type Location = "header" | "footer";
export type AppliedScript = {
  id: string;
  version: string;
  location: Location;
  attributes?: Record<string, string>;
};

// One request helper: adds auth, retries once on 429, and throws on any other error
export async function wf<T>(path: string, init: RequestInit = {}): Promise<T> {
  for (let attempt = 0; attempt < 2; attempt++) {
    const res = await fetch(`${API}${path}`, {
      ...init,
      headers: {
        Authorization: `Bearer ${token}`,
        "Content-Type": "application/json",
        ...init.headers,
      },
    });
    if (res.status === 429 && attempt === 0) {
      const wait = Number(res.headers.get("Retry-After") ?? "60");
      await new Promise((r) => setTimeout(r, wait * 1000));
      continue;
    }
    if (!res.ok) {
      throw new Error(`${init.method ?? "GET"} ${path} failed: ${res.status} ${await res.text()}`);
    }
    return (await res.json()) as T;
  }
  throw new Error(`${path} still rate limited after one retry`);
}

The helper also throws on every other error, so a failed read can never become an empty list that a later write saves over the page's real scripts.

Your site ID and the page IDs you want to target

Your site ID comes back from the List Sites endpoint, and page IDs come from the List Pages endpoint for that site.

Save this as list-pages.ts to print every page's slug and ID:

// list-pages.ts
import { wf } from "./webflow";

const siteId = process.env.WEBFLOW_SITE_ID!;
const { pages } = await wf<{ pages: { id: string; slug: string; title: string }[] }>(
  `/sites/${siteId}/pages?limit=100`,
);
for (const page of pages) {
  console.log(`${page.slug}\t${page.id}\t${page.title}`);
}

Running npx tsx list-pages.ts prints the list. The endpoint returns up to 100 pages per request, so a large site needs a second call with an offset. You should now have the page IDs for the pages that need the script.

The script content or hosted URL

Inline scripts hold the JavaScript itself, without script tags, and Webflow hosts it for you. The API reference caps inline source at 2,000 characters.

Anything longer belongs on your own server or CDN as a hosted script. Hosted registration needs the file's public URL and a Subresource Integrity hash of its contents.

Generate the hash from the live file:

curl -s https://cdn.example.com/analytics.js | openssl dgst -sha384 -binary | openssl enc -base64 -A

Prefix the output with sha384- and use it as the integrityHash value. The browser compares that hash with the file it downloads, so any later change to the file needs a new hash and a new registered version.

5 steps to apply a script to a Webflow page via the Data API

The workflow has two phases: register a script once at the site level, then apply it to each page that needs it.

The examples use an inline script, applied first to one page and then to many.

1. Register your script with the site

Registration stores the script and its version on the site. You'll reference it by ID and version on every page afterward.

The registration request for an inline script goes in register-inline.ts:

// register-inline.ts
import { wf } from "./webflow";

const siteId = process.env.WEBFLOW_SITE_ID!;
const script = await wf<{ id: string; version: string }>(
  `/sites/${siteId}/registered_scripts/inline`,
  {
    method: "POST",
    body: JSON.stringify({
      displayName: "PricingLogger",
      version: "1.0.0",
      sourceCode: `console.log("Pricing page script loaded");`,
      canCopy: false,
    }),
  },
);
console.log(`Registered ${script.id} at version ${script.version}`);

Run it with npx tsx register-inline.ts and keep the ID it prints. Webflow derives that ID from the display name, which must be 1 to 50 alphanumeric characters.

Registration takes no location, so you choose header or footer each time you apply the script to a page. The canCopy value decides whether Webflow copies the script when someone duplicates or transfers the site.

Registering a hosted script instead

Hosted registration replaces sourceCode with hostedLocation and integrityHash.

Save this as register-hosted.ts, with your own URL and hash:

// register-hosted.ts
import { wf } from "./webflow";

const siteId = process.env.WEBFLOW_SITE_ID!;
const script = await wf<{ id: string; version: string }>(
  `/sites/${siteId}/registered_scripts/hosted`,
  {
    method: "POST",
    body: JSON.stringify({
      displayName: "CampaignAnalytics",
      version: "1.0.0",
      hostedLocation: "https://cdn.example.com/analytics.js",
      integrityHash: "sha384-REPLACE_WITH_YOUR_HASH",
      canCopy: false,
    }),
  },
);
console.log(`Registered ${script.id} at version ${script.version}`);

The run prints the hosted script's ID and version, just like the inline version. From here, both kinds of script work the same way.

2. Confirm the scripts registered on the site

A quick list of the site's registered scripts confirms the registration and shows the exact ID and version strings to use.

The listing script is list-registered.ts:

// list-registered.ts
import { wf } from "./webflow";

const siteId = process.env.WEBFLOW_SITE_ID!;
const { registeredScripts = [] } = await wf<{
  registeredScripts?: { id: string; version: string; displayName: string }[];
}>(`/sites/${siteId}/registered_scripts`);
for (const s of registeredScripts) {
  console.log(`${s.id}\t${s.version}\t${s.displayName}`);
}

Run npx tsx list-registered.ts to see them. A site can hold up to 800 registered scripts, so this list is also where you audit old versions before you reach the cap.

3. Read the page's current scripts before you change them

The page endpoint replaces the whole list of scripts on every write. Webflow removes any script you leave out of the request from the page, including scripts another app or teammate added.

The read before each write is therefore the most important call in the workflow. The applyToPage function in the next step always reads the page first, and the helper's error handling stops the run if that read fails.

Each item in a page's list carries an id, a version and a location, plus optional attributes. A write has to send the id, version and location back for every script you keep.

4. Merge your script into the list and write it back

The applyToPage function reads the page, replaces any older version of your script, keeps everything else and writes the full list back.

Put the function in apply-script.ts:

// apply-script.ts
import { wf, type AppliedScript } from "./webflow";

// Read the page's scripts, swap in the new one, and write the full list back
export async function applyToPage(pageId: string, script: AppliedScript) {
  const { scripts = [] } = await wf<{ scripts?: AppliedScript[] }>(
    `/pages/${pageId}/custom_code`,
  );
  const current = scripts.find((s) => s.id === script.id);
  if (current?.version === script.version && current.location === script.location) {
    return "unchanged";
  }
  const next = [...scripts.filter((s) => s.id !== script.id), script];
  await wf(`/pages/${pageId}/custom_code`, {
    method: "PUT",
    body: JSON.stringify({ scripts: next }),
  });
  return current ? "updated" : "added";
}

const [pageId, id, version, location = "footer"] = process.argv.slice(2);
if (pageId && id && version) {
  const result = await applyToPage(pageId, { id, version, location: location as "header" | "footer" });
  console.log(`${pageId}: ${result}`);
}

Run it with the page ID, the script ID, the version and the location, for example npx tsx apply-script.ts <page-id> <script-id> 1.0.0 footer. It prints added, updated or unchanged, and the page's other scripts stay in place.

The optional attributes object becomes HTML attributes on the rendered script tag. To render data-page="pricing" on the tag, set { "data-page": "pricing" } as the attributes of the script object you give applyToPage.

Applying the script across many pages

The same function handles bulk updates. Each page costs two requests, one read and one write, so the loop waits between pages.

The loop goes in bulk-apply.ts:

// bulk-apply.ts
import { applyToPage } from "./apply-script";

// Each page costs two requests, so 2 seconds per page keeps you at 60 requests a minute
const DELAY_MS = Number(process.env.DELAY_MS ?? "2000");
const pageIds = (process.env.PAGE_IDS ?? "").split(",").filter(Boolean);
const script = {
  id: process.env.SCRIPT_ID!, // the id that register-inline.ts printed
  version: process.env.SCRIPT_VERSION ?? "1.0.0",
  location: "footer" as const,
};

const failed: string[] = [];
for (const pageId of pageIds) {
  try {
    console.log(`${pageId}: ${await applyToPage(pageId, script)}`);
  } catch (err) {
    failed.push(pageId);
    console.error(`${pageId}: ${(err as Error).message}`);
  }
  await new Promise((r) => setTimeout(r, DELAY_MS));
}
console.log(`Done. ${pageIds.length - failed.length} succeeded, ${failed.length} failed.`);
if (failed.length) process.exitCode = 1;

Run it with SCRIPT_ID=<script-id> PAGE_IDS=<id1>,<id2> npx tsx bulk-apply.ts. Webflow's limit is 60 requests per minute on Starter and Basic sites and 120 on CMS-capable paid plans, as the rate limits reference lists. The 2-second default suits the lower limit, and you can set DELAY_MS to 1000 on a 120-request plan.

The loop reports every failure and exits with an error code, so any scheduler that watches exit codes flags a partial run. You should now see each page listed as added, updated or unchanged.

5. Publish the site to make the change live

Applying a script changes the site's staged custom code. Visitors see it only after you publish the site.

Publishing pushes every staged change on the site live, including changes unrelated to your script. Webflow's custom code guide recommends prompting the site owner to publish when they're ready, rather than publishing on their behalf.

If your App does publish, the Publish Site endpoint needs the sites:write scope and accepts one successful publish per minute. The request body must include customDomains or publishToWebflowSubdomain. Passing a page ID publishes that page alone and keeps other staged changes back.

Check the published page's source afterward to confirm the script tag appears in the head or before the closing body tag.

What causes Webflow custom code API calls to fail?

Most failures trace back to the token or to an incomplete write, and a missing publish can hide a write that succeeded. Each cause produces a different symptom.

Start with the symptom you see.

Every custom code request fails: site token used instead of OAuth

Cause: The request carries a site token from Site settings > Apps & integrations > API access. Site tokens don't cover the custom code endpoints.

Fix: Use the OAuth access token from your Webflow App, with the custom_code scopes granted during authorization. If the token is right and requests still fail, check that you authorized the App on the site you're targeting.

Scripts disappear from a page after a write

Cause: The write sent a list that didn't include the page's existing scripts. The endpoint treats the list you send as the complete set.

Fix: Route every change through a read-merge-write function such as applyToPage, and never build the list from scratch. If scripts are already gone, re-apply each one with its registered ID and version, which list-registered.ts prints.

A write returns 400 or 409

Cause: A 400 usually means an item is incomplete, for example a missing version, or it points at a script that isn't registered. A 409 on the page endpoint means the site has reached its 800 registered scripts.

Fix: For a 400, compare each item with list-registered.ts output and send id, version and location for every script. For a 409, reuse a version that's already registered instead of registering another.

The script is applied but doesn't appear on the live site

Cause: You haven't published the site since you applied the script. Applied scripts stay staged until a publish.

Fix: Publish the site from Webflow, or through the Publish Site endpoint if your App owns publishing. Then view the page source on the live domain and search for the script.

Build your site's automation layer

The same read-merge-write pattern works at the site level, where the site custom code endpoint applies a script to every page at once. Site-level scripts suit analytics and consent tools, and page-level scripts suit campaign pixels on a single landing page.

For one-off changes, the Webflow MCP server lets an AI agent read and write site and page custom code or manage registered scripts. Our Cookiebot setup guide shows a script that must load first in the head. The CMS API guide covers the content side of the same Data API.

Frequently asked questions

Token type and script limits raise the most questions, so they're answered here.

Can I use a site token for the Custom Code API?

No. Site tokens can't reach the custom code endpoints. You need an OAuth access token from a Webflow Data Client App with the custom_code:read and custom_code:write scopes.

What happens if I send an empty scripts list to a page?

The page loses all of its applied scripts. Whatever list you send becomes the page's full set, so an empty list clears the page once the site is published.

Is there a rate limit on Custom Code API calls?

Yes. The limit is 60 requests per minute on Starter and Basic sites and 120 on CMS-capable paid plans, per API key. A 429 response includes a Retry-After header, which the webflow.ts helper honors once before failing.

Can I update a registered script's source code after registration?

No. Register the new code as a new version, then apply that version to each page. The read-merge-write function replaces the old version on the page with the new one.

How do I remove a script from one page without clearing all scripts?

Read the page's scripts, filter out the one you want to remove and write the rest back. The other scripts stay in place, and the change goes live with the next publish.


Last Updated
November 20, 2026
Category

Related articles

How to prevent page scroll when a modal is open in Webflow + the iOS Safari fix
How to prevent page scroll when a modal is open in Webflow + the iOS Safari fix

How to prevent page scroll when a modal is open in Webflow + the iOS Safari fix

How to prevent page scroll when a modal is open in Webflow + the iOS Safari fix

Guides
By
Ismail Ajagbe
,
,
Read article
How to add styled tooltips to Webflow without using jQuery
How to add styled tooltips to Webflow without using jQuery

How to add styled tooltips to Webflow without using jQuery

How to add styled tooltips to Webflow without using jQuery

Development
By
Colin Lateano
,
,
Read article
How to add a Calendly popup modal to Webflow and keep visitors on-site
How to add a Calendly popup modal to Webflow and keep visitors on-site

How to add a Calendly popup modal to Webflow and keep visitors on-site

How to add a Calendly popup modal to Webflow and keep visitors on-site

Development
By
Colin Lateano
,
,
Read article
How to add a GDPR-compliant cookie consent banner to Webflow using Cookiebot
How to add a GDPR-compliant cookie consent banner to Webflow using Cookiebot

How to add a GDPR-compliant cookie consent banner to Webflow using Cookiebot

How to add a GDPR-compliant cookie consent banner to Webflow using Cookiebot

Guides
By
Ismail Ajagbe
,
,
Read article

verifone logomonday.com logospotify logoted logogreenhouse logoclear logocheckout.com logoreddit logothe new york times logoideo logoupwork logodiscord logo
verifone logomonday.com logospotify logoted logogreenhouse logoclear logocheckout.com logoreddit logothe new york times logoideo logoupwork logodiscord logo

Get started for free

Try Webflow for as long as you like with our free Starter plan. Purchase a paid Site plan to publish, host, and unlock additional features.

Get started — it’s free
Watch demo

Try Webflow for as long as you like with our free Starter plan. Purchase a paid Site plan to publish, host, and unlock additional features.