Files
webstudio/docs/university/foundations/variables.md
T
Oleg Isonen 7cab28b633 fix: Allow Form Resources to reach sibling API hosts (#6623)
A Form on `site.example.com` can now send a Resource request to
`api.example.com`. Cloudflare fetches use public routing, while requests
back into the same app are stopped even when they arrive through a
different hostname.

## Checklist

- [x] Enable public `fetch()` routing in the self-hosted Cloudflare
Worker and Pages templates.
- [x] Narrow Cloudflare Form Resource hostname checks to site hostnames,
including published aliases; keep the Node transport policy intact.
- [x] Explain the routing and recursion boundary in code comments.
- [x] Add focused regression tests and verify they fail before the fix
and pass afterward.
- [x] Reject Cloudflare Resource requests that re-enter the app through
an alias, and verify both Worker and Pages paths.
- [x] Run relevant package tests, typechecks, lint, and fixture builds.
- [x] Review the authoritative `docs/` content. No user guidance
currently describes this hostname policy, so no docs change is needed.

The `global_fetch_strictly_public` flag affects all Cloudflare `fetch()`
calls in the generated app. It routes same-zone requests through the
public front door. The known site hostnames are blocked before fetch; a
reserved request marker carrying the originating project ID stops direct
reentry through any additional self-hosted alias while allowing other
projects. The marker is set on every redirect hop.

Verification: SDK suite (914 tests), CLI prebuild suite (143 tests), SDK
and CLI typechecks, published types, lint, package boundaries,
formatting, full fixture pipeline, and both Cloudflare fixture
typechecks/builds passed. The new marker test failed before the fix and
passed afterward. Local Pages returned 508 for a marked request and 200
for an ordinary request. Local Worker returned 508 for a marked request;
an ordinary local request hit a fixture-only `assets/process` module
error. The optional local fixture-size check lacked the unrelated React
Router Netlify built client artifact; the prior PR CI fixture-size check
passed.

Staging test: moved from #6621 to `frm.staging`. The Builder deployed at
https://frm.staging.webstudio.is/ and the Cloudflare template artifact
build and validation passed.

- [x] Publish the test site from staging and verify a Resource call to a
sibling API hostname, plus recursive-call protection.

Live staging verification: Published `ee-trpc-test-ivan.wstd.work` from
Builder commit `35d22fc8a`. A temporary Resource to `api.wstd.work`
produced that host's HTTP 401 response in published page data,
confirming the request reached the sibling host. A marked request
initially returned 200 because the SaaS publish Worker uses a separate
entrypoint. The matching guard is in webstudio-is/webstudio-saas#673;
deploying that branch made the marked request return 508 while an
ordinary request returned 200. The temporary Resource and binding were
removed and the clean build was republished with the SaaS fix.

## Resource response limit follow-up

- [x] Enforce 1 MiB (1,048,576 decoded bytes) for all HTTP Resource
responses, including page Resources, dependencies, Form actions, and
cache hits; reject before cache writes.
- [x] Cancel oversized responses and report `RESPONSE_TOO_LARGE` without
retrying. Show: “Resource response exceeds 1 MiB. Request fewer fields
or use pagination.”
- [x] Verify exact boundaries, streamed overflow, compressed responses,
cache behavior, and Form/loader error propagation with regression tests.
- [x] Update Resource and Form documentation to explain the limit and
recovery.
- [x] Monitor CI after pushing the verified implementation. All checks
passed for `f59b770d45112581514eaa8bc42f57b7f27d290b`, including all ten
browser E2E jobs, visual regression, Linux/Windows fixtures, and staging
builds/deployments.

Verified locally: all 926 SDK tests, SDK typecheck and published types,
lint, package boundaries, Form browser boundary, formatting, full
fixture pipeline, and Cloudflare React Router fixture typecheck/build
passed. All 12 new tests and the updated transport test failed against
the previous implementation; disabling only the retry guard also
reproduced a duplicate attempt. A local Cloudflare runtime test with
gzip accepted exactly 1 MiB of decoded data and rejected one byte over.
The full fixture sync pulled an unrelated saved-project text change; the
original fixture source was restored and regenerated, leaving no fixture
diff.

The response limit is enforced before JSON parsing and before Resource
cache writes, and checked again when loading cache hits. Oversized
responses return `RESPONSE_TOO_LARGE` with `retryable: false`; the graph
honors that flag. System and Email Resources retain their own limits.
The implementation adds 59 net non-test code lines plus 5 documentation
lines, below the 70–100 estimate. Browser E2E passed in CI. Agent
evaluations were not run; they require separate permission and were not
needed for this transport change.


## Simplification follow-up

- [x] Reuse Content Engine's bounded byte reader for Resource bodies and
Form uploads; remove duplicate accumulation and cancellation loops
(estimate: about 40 fewer production lines).
- [x] Preserve response limits, request limits, cancellation, error
messages, and retry behavior; run existing SDK and Content Engine
coverage plus package/build checks.
- [x] Review documentation impact; behavior and approved copy should
remain unchanged.
- [x] Push the simplification and verify CI. All checks passed for
`755ec4210a7858fe298ad4d3a725a0167fb5bb26`, including all ten browser
E2E jobs and staging deployment checks.

The simplification removes 37 net non-test lines, reducing the
response-limit implementation from 59 added lines to 22. Content Engine
now exposes its existing byte-stream module directly and accepts a
caller-provided limit error. Resource bodies and Form uploads reuse that
reader. Native Response construction also replaces redundant
status/header copying. All existing tests remain.

Verification: 926 SDK tests and 655 Content Engine tests passed, along
with both packages' typechecks/builds, published types, lint, package
boundaries, Form browser boundary, formatting, the full fixture
pipeline, and a Cloudflare fixture build. Local Cloudflare runtime
checks passed for gzip at/over the limit and empty 204/205/304
responses. The generated fixture vendor change is limited to the shared
reader's optional error argument. Documentation and approved copy remain
accurate and unchanged.

## Response handling cleanup

- [x] Share bounded response reconstruction between protected fetches
and the cache; remove stale encoding/length headers after decoding
(estimate: 5–10 fewer non-test lines).
- [x] Reproduce the protected-response header bug, then verify the fix,
limits, empty responses, and existing SDK coverage.
- [x] Review documentation and comments for accurate scope; preserve
approved user-facing copy.
- [x] Run relevant checks, regenerate fixtures, push, and monitor CI.

The shared response reader fixes stale compression and length headers in
protected fetches and removes four net production lines (slightly below
the 5–10 estimate). All 927 SDK tests, types, published types, lint,
package boundaries, and Form browser boundary passed. The new regression
test failed on the old code and passed after the fix. Cloudflare runtime
checks passed for decoded bodies and empty 204/205/304 responses. The
existing Resource/Form documentation remains accurate; approved copy is
unchanged.

The reentry marker now carries the originating project ID. A different
project can serve the request; the same project rejects direct reentry
through any hostname. This is cooperative loop detection, not a sandbox
for arbitrary code.

- [x] Reproduce and fix overflow and redirect hangs when a response has
an unread clone; preserve stream cancellation and error handling for all
shared-reader callers.

The clone regressions failed before the fixes and passed afterward.
Cancellation still starts immediately and releases the reader lock, but
no longer waits for an unread tee branch. Both overflow rejection and
redirect following are covered. All 929 SDK tests and 655 Content Engine
tests passed, along with both typechecks and lint. A local Cloudflare
runtime also rejected a cloned oversized response promptly. Combined
with response reconstruction reuse, this cleanup removes five net
production lines. Fixture regeneration changes only the bundled
cancellation logic.

Final verification for `7761f67d6d1e0a853a6ef239f482ebaf9d70c1ae`: all
CI checks passed, including all ten browser E2E shards, visual
regression, package/Builder/CLI tests, size checks, Linux and Windows
fixtures, and staging deployment workflows. Full fixture regeneration
and the Cloudflare fixture build also passed locally. No agent
evaluations were run; they require separate permission and were not
needed for these fixes.

## Scope reentry protection to the project

- [x] Replace the global marker with the originating project ID and
compare it with generated project metadata before handling requests,
including cached requests.
- [x] Cover unrelated sites, same-project aliases, and redirects with
regression tests; demonstrate failure before the fix.
- [x] Review documentation and clarify that this is cooperative loop
detection, not a sandbox for untrusted code.
- [x] Regenerate fixtures, run relevant checks, push, and monitor CI.
Estimate: 20–30 implementation lines across both repositories, plus
generated metadata and tests.

Implementation: reuse the project ID already exported by the generated
home-page module; no new metadata file or package. The generated
Cloudflare Resource adapter passes the same ID to the SDK factory, which
now requires it. Guards compare that ID before rendering or cache
lookup. SDK and generated-adapter regression tests cover another project
returning 200 and an unknown same-project alias returning 508. Hosted
Worker tests verify the guard runs before the cache and permits another
project's cached response. The original guard and a blanket-guard
mutation fail the regressions. A local Cloudflare runtime reproduced the
expected 200/508 behavior. No user-facing copy or documentation changes
are needed; code comments state the cooperative boundary. The fix adds
19 implementation lines across both repos, below the 20–30 estimate,
plus tests/configuration and regenerated fixtures. Existing deployments
require republishing with the updated sender and guard to use
project-specific markers.

Final project-specific reentry verification: 930 SDK tests, 143 CLI
prebuild tests, and 41 hosted-template tests passed. SDK/CLI types,
published SDK types, lint, package boundaries, full fixture
regeneration, both Cloudflare fixture builds, and the Pages function
bundle passed. The actual Pages function returned 200 for another
project's marker and 508 for its own marker through an unknown alias in
a local Cloudflare runtime. All CI checks passed for Builder
`433f9a359d469ca3669e383c4516c3e805ea22a1`, including all ten E2E shards
and staging workflows; companion SaaS
`3e28e7e33813dd968f33caac35dbbba52a3847d3` checks and preview deployment
also passed. Agent evaluations were not run because they require
separate approval; no evaluation changes were needed.
2026-10-30 22:42:27 +01:00

13 KiB
Raw Blame History

description
description
Define values and resources for use throughout your site.

🔡 Variables

{% hint style="info" %} Hint: CSS variables are different than data variables. They enable the reuse of values in the Style Panel. {% endhint %}

Define variables on an instance in the Navigator, such as Global root, Body, or Heading. Find them in Settings > Variables.

Form settings panel showing properties, action resources, and static and dynamic variables

Variable scope

Variables are available within the instance they are defined on and any of its children. They are not available in the parent.

If you define a variable on Global root, it is available on all pages and can be used within Slots.

{% hint style="info" %} To access variables in the Page Settings, the variable must be defined on the Body of the page. {% endhint %}

Create and edit a variable

Select an instance in the Navigator, then use Add variable in Settings > Variables. In the New variable dialog, enter a Name and choose a Type. The name field suggests names already used in expressions but not yet created. Names must be unique on the same instance. You can reuse an ancestor's variable name, but a warning shows that the new variable shadows it.

Choose String, Number, Boolean, JSON, REST resource, GraphQL resource, Assets resource, Email resource, Sitemap resource, or Current date resource. Resource types may require a plan with dynamic data access. The editor changes with the type, and the right side of the dialog previews the value or resource data. You can resize or maximize the dialog.

Changes save when you close the dialog or move away from it. A new variable closes after it is created. Correct an invalid name before closing; other field errors are shown in their editors. For an existing variable, the menu offers Copy and, where allowed, Delete. Copying a resource includes its configuration, so you can paste it onto another instance or into another project. Resource editors also provide Refresh resource data and a Refresh menu action.

Global variables

Variables defined on Global root are accessible across all pages. Use them for shared contact information, site settings, or resource configurations needed in Slots.

Setting up global variables

  1. In the Navigator, select Global root above Body.
  2. In Settings > Variables, select Add variable.
  3. Enter a name and choose a type in the New variable dialog.

Use cases

{% embed url="https://www.youtube.com/watch?v=jRzMROoKwsQ" %}

  • Contact email: Define once and bind it to contact information across pages.
  • Simple CMS: Use a JSON variable on Global root for data displayed in Slots.
  • Shared resource: Define a resource once for use across pages.

Variables

System

The System variable is available by default. Forms also add variables automatically for submission data and state.

System variable contains the following:

  • Params – Key/value pairs that are defined in Dynamic Page URLs.
  • Search – Key/value pairs of query parameters that may exist in the URL.
  • Origin – The URL of the current site. It will display whatever the actual URL is, so in the builder, it will be the internal wstd.io domain, but on the published site, it will be the current origin, likely a custom domain.
  • Pathname – The current page's path (e.g., /blog/my-post). Useful for conditional logic based on the current URL.

String

A String variable holds text data, which can be used for titles, descriptions, and labels. Enter the text in Value; the preview updates as you edit.

Number

A Number variable stores numeric values, including integers and decimals. Enter a number in Value; the editor reports an empty or invalid number.

Boolean

A Boolean variable represents a true or false value. Set Value with the switch, for example to control visibility.

JSON

A JSON variable allows for structured data. Enter its value in the expression editor; syntax errors are marked there, and the evaluated value appears in the preview. It can provide items to a Collection, such as a dynamic gallery.

Resource

Choose REST resource to fetch data from an HTTP API. For a GraphQL API, use the GraphQL resource editor.

There are several fields available to configure the fetch request.

{% hint style="info" %} Shortcut: The URL field supports pasting in a cURL command. Doing so will automatically populate the various fields within the Resource. Many API docs will provide you with a cURL command, so look out for it to save time. {% endhint %}

  • URL – Where the resource is located.
  • Method – GET, POST, PUT, or DELETE. Refer to the third-party API docs to find the suitable method.
  • Search params – Key/value pairs used for providing additional parameters as part of the URL. Values can be bound to other variables.
  • Cache max age – Define your own cache lifetime.
  • Headers – Key/value pairs such Content-Type application/json. Refer to Request Headers for more info.
  • Format and body – For requests other than GET, choose auto, application/json, or multipart/form-data and configure the body. A Form action also shows these fields even when GET is selected because Form submissions use POST.

The preview can load the request and show its response, request details, and error diagnostics. Use Refresh resource data after changing inputs or to request fresh data.

{% include "../../.gitbook/includes/the-requests-including-any....md" %}

Submit a form to a resource

A new Form includes two email resources. To add another destination, create a REST, GraphQL, or email resource in Variables on the Form or an ancestor. Then select the Form and use Properties & Attributes > Action to add the resource. Resources defined on the Form can bind to its formData and safe browserInfo values; ancestor resources cannot bind to those values. HTTP destinations always send POST requests when the Form is submitted, regardless of their configured method for ordinary data loading.

The Form also exposes formState, formProgress, results, and errors in Variables. Use formProgress to show submission activity and whole-request upload bytes, formState for the outcome, and results and errors for action responses. See the Form guide for their contents and submission behavior.

For a Form-scoped HTTP resource, leave the body unset to forward every named Form field. Format defaults to auto: text-only Form data is JSON; a body containing uploaded files becomes multipart. Choose application/json or multipart/form-data when the receiving API requires that format. JSON rejects uploaded files instead of dropping them. Multipart sends repeated values under the same field name and includes uploaded files with their filenames and bytes. Use the Form upload guide for file inputs and the combined request limit.

Response

Once the Resource fetches data, you'll use the Expression editor to bind data from the response to your website. See Binding for more information.

HTTP Resource responses are limited to 1 MiB (1,048,576 bytes) after decompression. This applies to REST and GraphQL Resources in the Builder and published sites, including Form actions, dependencies, and cached responses. Responses over the limit fail; Webstudio does not truncate them. Request fewer fields or use the API's pagination options to reduce each response.

This is a response limit, separate from Form upload limits. It does not limit images or other files loaded directly by the browser, and it does not replace the separate limits for Assets and Email Resources.

Dependent resources

Bind a Resource request field to another Resource variable when one request needs data from an earlier response. For example, bind an author ID from one Resource into the URL or search parameters of a second Resource that loads the author's posts.

Webstudio fetches the dependency first and evaluates the dependent request after the dependency data is available. A Resource cannot depend on itself or on another Resource that already depends on it. Collection item and component parameter variables are not available in Resource request fields.

When a Form uses a Resource action, Webstudio fetches that action's dependencies when the form is submitted, not when the page loads.

Form actions bypass Webstudio's resource cache so each submission sends a new request. Their dependencies still use the configured cache lifetime.

Caching

You may be wondering whether every visit to your blog results in an API call to your CMS or if the content is cached in Webstudio.

When you configure a Resource, the data is fetched using Cloudflare Workers, which has a built-in caching system.

By default, several factors determine what gets cached and for how long, but one of the primary factors is what the origin system instructs the requesting entity to cache. In other words, the headless CMS tells Cloudflare Workers what can be cached, if anything, and for how long.

If you set a custom Cache max age value, it will define your cache lifetime instead of relying on API response headers.

GraphQL

Choose GraphQL resource to fetch data from a GraphQL API. Its editor sends a POST request and provides fields for the GraphQL operation.

There are several fields available to configure the fetch request.

  • URL – Where the resource is located.
  • Query – A GraphQL query.
  • GraphQL variables – An object passed into the query. You can bind it to other variables; for example, use { slug: system.params.slug } on a Dynamic Page. The editor requires a valid object. See System.
  • Cache max age and Headers – Configure caching and request headers.

The URL accepts a URL or cURL command. Use Load data or Refresh resource data to inspect the response and request.

{% include "../../.gitbook/includes/the-requests-including-any....md" %}

Assets resource

Choose Assets resource to query project assets. Its query editor supports filters, sorting, pagination, and file content. Invalid query settings are shown in the editor. See Content Engine for a complete article workflow.

Sitemap resource

Choose Sitemap resource to load the site's static pages. Use it to combine static and dynamic data in a custom sitemap. See the XML Node component.

Current date resource

Choose Current date resource to get the current date normalized to midnight UTC. Format it with the Time component.

These resource editors provide Load data and Refresh resource data to update the preview. Sitemap and current date resources need only a name; the Assets resource uses a query editor.

Email resource

Choose Email resource to send a plain-text email when a Form is submitted. Choose Project recipients (or owner), Custom recipients, or, for a resource within a Form, Visitor email field. The visitor option selects a named email input on that Form. Configure Reply to, Subject, Body, and Attach submitted files. Custom recipients, Reply to, Subject, and Body can use bindings. The editor validates recipient and sender addresses and expressions.

The Request preview shows the email request without sending it. Submit the Form in Preview to see the email service response. See the Form guide for delivery behavior and limits.

  • Expression editor – Bind variables to components and create expressions
  • CMS – Use Resources to fetch content from external systems
  • Collection – Iterate over JSON or Resource data
  • CSS variables – Define reusable style values (different from data variables)
  • Slot – Access global variables in reusable components