Skip to content

fix: auto-forward cookies in vtexFetchWithCookies - #3

Merged
JonasJesus42 merged 1 commit into
mainfrom
fix/vtex-cookie-forwarding
Mar 16, 2026
Merged

JonasJesus42 merged 1 commit into
mainfrom
fix/vtex-cookie-forwarding

Conversation

@JonasJesus42

@JonasJesus42 JonasJesus42 commented Mar 16, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Add setRequestCookieProvider / setResponseCookieForwarder to the VTEX client — framework-agnostic provider hooks that make cookie propagation automatic for all checkout, session, and auth actions
  • vtexFetchWithCookies now auto-injects browser cookies into VTEX API requests (when no explicit cookieHeader is passed) and auto-forwards VTEX Set-Cookie headers back to the browser response
  • Fixes logged-in users seeing anonymous/empty carts because VtexIdclientAutCookie and session cookies were not being forwarded through TanStack Start server functions

Problem

All VTEX checkout actions (getOrCreateCart, addItemsToCart, etc.) accept an optional cookieHeader parameter, but every site's invoke.ts server functions were calling them without cookies. The VTEX API couldn't identify logged-in users, resulting in:

  • Logged-in users getting anonymous carts
  • VTEX creating new orderForms instead of returning the user's existing one
  • Set-Cookie headers from VTEX responses being silently discarded (return result.data ignoring result.setCookies)

Solution

Instead of requiring every site to manually extract and forward cookies in each server function, the fix is at the library level:

  1. setRequestCookieProvider(fn) — sites/frameworks register a function that returns the current request's Cookie header. vtexFetchWithCookies calls this automatically.
  2. setResponseCookieForwarder(fn) — sites/frameworks register a callback to forward Set-Cookie headers. vtexFetchWithCookies calls this automatically after every response.

The @decocms/start framework adapter wires these once at startup:

setRequestCookieProvider(() => getRequestHeader("cookie") ?? undefined);
setResponseCookieForwarder((cookies) => setResponseHeader("set-cookie", cookies));

No per-site changes needed. Explicit cookieHeader parameters still work as overrides.

Safety — no cross-user cookie leaking

  • vtexFetchWithCookies is not cached (it bypasses fetchWithCache / SWR)
  • The provider function is called fresh on every request — no stale cookie reuse
  • Each server function handler runs in its own request context

Test plan

  • Verify logged-in user sees their cart items after page reload
  • Verify adding items to cart works for authenticated users
  • Verify Set-Cookie headers from VTEX reach the browser (check response headers)
  • Verify anonymous users still get a new cart correctly
  • Verify no cross-user cart leaking under concurrent requests

🤖 Generated with Claude Code


Summary by cubic

Automatically propagate cookies in VTEX requests and responses to preserve user sessions and carts. vtexFetchWithCookies now injects request cookies and forwards VTEX Set-Cookie headers; adapters can wire this once at startup with no per-route changes.

  • New Features
    • setRequestCookieProvider(fn) — supplies the current request’s Cookie header when no cookieHeader is provided.
    • setResponseCookieForwarder(fn) — forwards VTEX Set-Cookie headers back to the browser.

Written for commit b89ac17. Summary will update on new commits.

Server functions calling VTEX checkout/session/auth actions were not
forwarding browser cookies (VtexIdclientAutCookie, session tokens) to
the VTEX API, causing logged-in users to get anonymous carts. The
Set-Cookie headers from VTEX responses were also being discarded,
preventing session cookies from reaching the browser.

Add two provider hooks to the VTEX client:
- setRequestCookieProvider: auto-injects request cookies into
  vtexFetchWithCookies when no explicit cookie header is set
- setResponseCookieForwarder: auto-forwards VTEX Set-Cookie headers
  back to the browser response

Framework adapters (e.g. @decocms/start) register these providers once
at startup, making cookie propagation transparent for all sites without
requiring changes to individual server functions.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
JonasJesus42 added a commit to decocms/blocks that referenced this pull request Mar 16, 2026
Exports initVtexCookieProviders() from @decocms/start/sdk that wires
TanStack Start request/response headers to the VTEX client cookie
providers (setRequestCookieProvider / setResponseCookieForwarder from
@decocms/apps/vtex).

Sites call this once in setup.ts after setVtexFetch() to enable
transparent cookie propagation for all VTEX checkout, session, and
auth actions -- no per-server-function changes needed.

Depends on: decocms/apps-start#3

Co-Authored-By: Claude Opus 4.6 <[email protected]>

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found across 1 file

@JonasJesus42
JonasJesus42 merged commit 078d456 into main Mar 16, 2026
1 check passed
@github-actions

Copy link
Copy Markdown

🎉 This PR is included in version 0.21.4 🎉

The release is available on:

Your semantic-release bot 📦🚀

JonasJesus42 added a commit that referenced this pull request Jun 2, 2026
…eno prod)

Adds 21 unit tests across 3 files covering the surfaces this PR ports.
Tests pin behavior the Fresh/Deno production code (deco-cx/apps/magento)
established, so future refactors of the apps-start port can refactor
freely without drifting from prod.

magento/__tests__/client.test.ts (12 tests):
  configureMagento / getMagentoConfig:
    - throws before configure (no implicit defaults)
    - returns the configured value after configure
  magentoFetch — same-origin:
    - attaches Authorization + x-origin-header + forced Referer
    - resolves relative path against baseUrl
    - authenticated:false drops Bearer (still attaches origin/referer)
    - preserves caller-supplied Referer (no force-overwrite)
  magentoFetch — cross-origin guard:
    - strips Bearer (regression for cubic finding #1)
    - strips x-origin-header (regression for cubic finding #2)
    - strips forced Referer (regression for cubic finding #2)
    - forwards caller-supplied headers through
    - same-origin absolute URL still gets identity headers

magento/__tests__/features.test.ts (2 tests):
  - returns the configured features object
  - returns {} when features omitted

magento/__tests__/cart.test.ts (7 tests):
  - returns null when no cookie (matches prod's `if (!cartId) return null`)
  - reads dataservices_cart_id cookie (JSON-quoted form)
  - reads dataservices_cart_id cookie (raw form, no quotes)
  - props.cartId override beats the cookie
  - URL-encodes cartId — regression for cubic finding #3 (path injection)
  - 404 returns null (expired cookie)
  - non-404 errors throw
  - cart fetch attaches Bearer + x-origin-header (same-origin)

Drive-by fix: cart loader was hitting /:site/V1/carts/:cartId, but Magento
exposes the cart endpoint at /rest/:site/V1/carts/:cartId — the /rest/
prefix is mandatory and matches the legacy clientAdmin's typed key
`GET /rest/:site/V1/carts/:cartId`. Tests pin the corrected path.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
JonasJesus42 added a commit that referenced this pull request Jun 2, 2026
…61)

* feat(magento): initial scaffold port from deco-cx/apps to apps-start

Starts the Magento app port to @decocms/apps following the same shape as
vtex/ and shopify/. This first commit lands the configure surface and 2
reference loaders (features, cart) — enough to unblock real consumer
sites; the remaining ~20 loaders/actions are itemized in
magento/README.md and will follow in separate commits.

Contents:
- magento/client.ts — configureMagento({ baseUrl, apiKey, storeId, ... })
  with module-global state, mirroring configureVtex. magentoFetch()
  helper attaches Bearer auth + Referer + optional x-origin-header on
  every call. initMagentoFromBlocks(blocks) resolves the CMS block's
  `__resolveType: "website/loaders/secret.ts"` references via env vars,
  same fallback granadobr-tanstack already uses in production.
- magento/types.ts — MagentoCart + MagentoCartItem shapes used by the
  ported loaders.
- magento/loaders/features.ts — returns the resolved Features block
  from the config. The simplest loader, used as the smoke test.
- magento/loaders/cart.ts — fetches the customer's active cart by
  reading `dataservices_cart_id` cookie via @decocms/start/sdk/cookie
  and calling the Magento admin REST endpoint. Returns null for
  anonymous sessions (expected) and on 404 (expired cookie).
- magento/middleware.ts — passthrough today; the legacy
  changeCardIdAfterCheckout reconciliation flow is deferred to a
  follow-up PR.
- magento/index.ts — re-export entry, parallel to vtex/index.ts.
- package.json — adds @decocms/apps/magento/* exports.

Motivation:
deco-sites/granadobr-tanstack (Granado, Brazilian cosmetics) just
migrated from Fresh/Deno to TanStack Start. Its parity audit reported
a HIGH severity finding:

  invoke(magento/loaders/features) failed: handler not found

…because no @decocms/apps/magento/* resolver existed. The site is
working around it with an in-site adapter that re-uses the legacy
mod.ts shape; this PR begins the upstream fix so the next Magento
storefront doesn't need to repeat the work.

Companion issue: #60

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(magento): address 3 cubic-dev-ai review findings (all P1)

1. package.json: `magento/` was in `exports` but not `files`. npm publish
   excludes any path not listed under `files`, so the entire magento
   folder would be missing from the published tarball — every consumer
   site would get module-resolution errors. Added `magento/` to the
   array alongside commerce/shopify/vtex/etc.

2. magento/loaders/cart.ts: cartId comes from a request cookie
   (`dataservices_cart_id`) and was spliced into the admin REST path
   unencoded. Wrapped both `site` and `cartId` in encodeURIComponent so
   user input can't break out of the path segment to tack on query or
   fragment parts that would hit a different endpoint with the
   privileged Bearer token attached.

3. magento/client.ts: magentoFetch() accepted any `path` value, including
   absolute URLs to arbitrary hosts. The auth headers (Bearer, Referer,
   x-origin-header) were attached unconditionally, so a caller passing
   `https://attacker.example/...` would leak the Magento admin token.
   Now constructs a URL up front, compares its origin against the
   configured baseUrl, and force-disables `authenticated` when the
   request is cross-origin. Genuine third-party calls remain possible
   via the explicit `authenticated: false` opt-out.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(magento): biome formatting + add magento/** to lint includes

Biome's includes array was missing magento/**, so the new package was
skipped by lint entirely. Added it to the includes alongside the other
apps. Also ran biome --write to convert space indentation to tab (project
convention) across the 5 magento source files.

Note: the test job also surfaces pre-existing lint errors in vtex/__tests__/
client-set-cookie-forward.test.ts and website/components/__tests__/
OneDollarStats.test.ts. Those are unrelated to this PR — they were already
failing on main before any magento file was added. Splitting that into a
separate PR.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(magento): strip ALL Magento-identity headers in cross-origin requests

Cubic's second pass caught that the previous fix only suppressed the
Bearer token but still leaked `x-origin-header` (an opaque secret) and
a forced `Referer` pointing at the Magento storefront URL whenever a
caller passed an absolute non-Magento URL.

Now `buildHeaders` takes an explicit `attachMagentoIdentity` flag.
`magentoFetch` sets it to `target.origin === baseUrl.origin`, so a
cross-origin call gets only whatever headers the caller passed in their
`opts.headers` — no Magento-side credentials, no origin-header secret,
no forced Referer.

Callers wanting a genuinely cross-origin GET should still flip
`authenticated: false` at the call site for intent, but security no
longer relies on that single flag being correct.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* test(magento): pin behavior parity with deco-cx/apps/magento (Fresh/Deno prod)

Adds 21 unit tests across 3 files covering the surfaces this PR ports.
Tests pin behavior the Fresh/Deno production code (deco-cx/apps/magento)
established, so future refactors of the apps-start port can refactor
freely without drifting from prod.

magento/__tests__/client.test.ts (12 tests):
  configureMagento / getMagentoConfig:
    - throws before configure (no implicit defaults)
    - returns the configured value after configure
  magentoFetch — same-origin:
    - attaches Authorization + x-origin-header + forced Referer
    - resolves relative path against baseUrl
    - authenticated:false drops Bearer (still attaches origin/referer)
    - preserves caller-supplied Referer (no force-overwrite)
  magentoFetch — cross-origin guard:
    - strips Bearer (regression for cubic finding #1)
    - strips x-origin-header (regression for cubic finding #2)
    - strips forced Referer (regression for cubic finding #2)
    - forwards caller-supplied headers through
    - same-origin absolute URL still gets identity headers

magento/__tests__/features.test.ts (2 tests):
  - returns the configured features object
  - returns {} when features omitted

magento/__tests__/cart.test.ts (7 tests):
  - returns null when no cookie (matches prod's `if (!cartId) return null`)
  - reads dataservices_cart_id cookie (JSON-quoted form)
  - reads dataservices_cart_id cookie (raw form, no quotes)
  - props.cartId override beats the cookie
  - URL-encodes cartId — regression for cubic finding #3 (path injection)
  - 404 returns null (expired cookie)
  - non-404 errors throw
  - cart fetch attaches Bearer + x-origin-header (same-origin)

Drive-by fix: cart loader was hitting /:site/V1/carts/:cartId, but Magento
exposes the cart endpoint at /rest/:site/V1/carts/:cartId — the /rest/
prefix is mandatory and matches the legacy clientAdmin's typed key
`GET /rest/:site/V1/carts/:cartId`. Tests pin the corrected path.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant