Skip to content

fix: normalize set cookies domain host - SFS-3034 - #3190

Merged
eduardoformiga merged 2 commits into
mainfrom
fix/normalize-set-cookies-domain-host
Feb 2, 2026
Merged

eduardoformiga merged 2 commits into
mainfrom
fix/normalize-set-cookies-domain-host

Conversation

@eduardoformiga

@eduardoformiga eduardoformiga commented Jan 28, 2026 •

Copy link
Copy Markdown
Member

What's the purpose of this pull request?

  • This PR fixes a historical issue with setCookie across domains other than the production domain.
Screenshot 2026-01-28 at 17 56 17 Screenshot 2026-01-28 at 17 59 17
  • It also fixes the bug that keeps validateCartMutation in a loop on preview URLs due to setCookie issues.

Jan-28-2026 18-44-28

How does it work?

  • Introduced functions to normalize cookie domains based on the request host.
  • Added checks to ensure cookies are set with the correct domain for allowed hosts, including localhost and preview URLs.
  • Replaced the previous domain replacement logic with a more robust implementation to improve cookie handling in development and production environments.

How to test it?

Starters Deploy Preview

  • Double check if the set-cookie from the response header of validateCartMutation across the different URLs: localhost, preview (ending with vtex.app), and production are working as expected.
  • Also check that the validateCartMutation is not looping anymore.
Environment
localhost ✅ Screenshot 2026-01-28 at 18 57 58
preview ✅ Screenshot 2026-01-28 at 19 12 39
prod ✅ Screenshot 2026-01-28 at 19 23 27

Summary by CodeRabbit

  • Bug Fixes
    • Improved Set-Cookie domain handling: cookie domains are now normalized based on the request host to prevent mismatched cookie scopes when accessing the app from different hosts.
    • Domain normalization is applied consistently (no longer toggled by environment), reducing inconsistent cookie behavior across deployments.

✏️ Tip: You can customize this high-level summary in your review settings.

- Introduced functions to normalize cookie domains based on request host.
- Added checks to ensure cookies are set with the correct domain for allowed hosts.
- Replaced the previous domain replacement logic with a more robust implementation to improve cookie handling in development and production environments.
@eduardoformiga
eduardoformiga requested a review from a team as a code owner January 28, 2026 21:50
@eduardoformiga
eduardoformiga requested review from emersonlaurentino and renatomaurovtex and removed request for a team January 28, 2026 21:50
@coderabbitai

coderabbitai Bot commented Jan 28, 2026 •

Copy link
Copy Markdown
Contributor

Walkthrough

The GraphQL API endpoint's Set-Cookie handling was refactored to introduce host-based domain normalization. A validation pipeline (hostname extraction, eligibility check, allowed-suffix match) now drives unconditional normalization of Set-Cookie headers when conditions are met, replacing the previous environment-gated replacement.

Changes

Cohort / File(s) Summary
Cookie Domain Normalization
packages/core/src/pages/api/graphql.ts
Introduced host-based normalization for Set-Cookie headers: added ALLOWED_HOST_SUFFIXES and a domain-match pattern, plus helpers getRequestHostname, shouldReplaceCookieDomain, isAllowedHost, and normalizeSetCookieDomain. Replaced prior production-conditional domain replacement with this unified, condition-aware pipeline applied to all Set-Cookie headers during response construction.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Client as Client
  participant API as GraphQL API (packages/core/src/pages/api/graphql.ts)
  participant Upstream as Upstream Service/Origin

  Client->>API: HTTP request (Host header)
  API->>Upstream: Proxy / fetch GraphQL request
  Upstream-->>API: HTTP response (may include Set-Cookie headers)
  API->>API: getRequestHostname(host header)
  API->>API: shouldReplaceCookieDomain(cookie, hostname)
  API->>API: isAllowedHost(hostname, ALLOWED_HOST_SUFFIXES)
  API->>API: normalizeSetCookieDomain(if allowed & different)
  API-->>Client: HTTP response with normalized or original Set-Cookie headers
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🍪 A cookie drifts from host to host,
Checked for suffixes it must post,
If allowed and different, domains transform —
A tidy swap to keep things warm. ✨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'fix: normalize set cookies domain host' directly describes the main change: implementing cookie domain normalization based on the request host, which is the core objective of this PR.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/normalize-set-cookies-domain-host

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codesandbox-ci

codesandbox-ci Bot commented Jan 28, 2026 •

Copy link
Copy Markdown

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@packages/core/src/pages/api/graphql.ts`:
- Around line 58-84: normalizeSetCookieDomain can trigger a 500 if
getRequestHostname (which uses new URL internally) throws for empty/malformed
Host; wrap the host extraction in a try/catch or otherwise validate the host and
on error or invalid host simply return the original setCookie to skip
normalization. Specifically, in normalizeSetCookieDomain (and/or in
getRequestHostname) guard the call to getRequestHostname({ request }) so that
any exception results in returning setCookie unchanged, and only proceed to call
isAllowedHost and shouldReplaceCookieDomain when host is a well-formed,
non-empty string.

Comment thread packages/core/src/pages/api/graphql.ts Resolved
@eduardoformiga eduardoformiga changed the title fix: normalize set cookies domain host fix: normalize set cookies domain host - SFS-3034 Jan 28, 2026
Comment thread packages/core/src/pages/api/graphql.ts Outdated
MATCH_DOMAIN_REGEXP,
`; domain=${faststoreAPIHostname}`
)
const getRequestHostname = ({ request }: { request: NextApiRequest }) =>

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

pq não usar o $request.headers.host diretamente sem montar e desconstruir uma url?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Usamos new URL(...).hostname para normalizar o host e remover porta/ruído. request.headers.host pode vir como localhost:3000 ou incluir porta no caso de testes que alteram o apontamento do localhost no arquivo de hosts, e o cookie Domain não aceita porta. A extração via URL garante um hostname consistente e evita comparar example.com:3000 com example.com.


const DEFAULT_MAX_AGE = 5 * 60 // 5 minutes
const DEFAULT_STALE_WHILE_REVALIDATE = 60 * 60 // 1 hour
const ALLOWED_HOST_SUFFIXES = ['localhost', '.vtex.app', '.localhost']

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

pra que serve exatamenta a allow list? como fica o cenário do dominio de produção do cliente?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

- Enhanced the `getRequestHostname` function to handle missing or malformed host headers gracefully.
- Added error handling to ensure the function returns null when the host is invalid, improving robustness in cookie domain normalization.
@eduardoformiga
eduardoformiga merged commit 645c91d into main Feb 2, 2026
6 checks passed
@eduardoformiga
eduardoformiga deleted the fix/normalize-set-cookies-domain-host branch February 2, 2026 19:01
thiagopereira-vtex pushed a commit that referenced this pull request Mar 10, 2026
## What's the purpose of this pull request?

- This PR fixes a historical issue with setCookie across domains other
than the production domain.

<img width="500" alt="Screenshot 2026-01-28 at 17 56 17"
src="https://github.com/user-attachments/assets/677f9f03-d4fd-41cc-96d2-922c16cb358f"
/>

<img width="300" alt="Screenshot 2026-01-28 at 17 59 17"
src="https://github.com/user-attachments/assets/d958548c-8f15-41c6-8451-bf5789544ef0"
/>


- It also fixes the bug that keeps `validateCartMutation` in a loop on
preview URLs due to setCookie issues.

![Jan-28-2026
18-44-28](https://github.com/user-attachments/assets/fa89d90b-2362-40ac-b430-03c1c259d95e)

## How does it work?

- Introduced functions to normalize cookie domains based on the request
host.
- Added checks to ensure cookies are set with the correct domain for
allowed hosts, including localhost and preview URLs.
- Replaced the previous domain replacement logic with a more robust
implementation to improve cookie handling in development and production
environments.
## How to test it?

### Starters Deploy Preview

- Double check if the `set-cookie` from the response header of
`validateCartMutation` across the different URLs: localhost, preview
(ending with `vtex.app`), and production are working as expected.
- Also check that the `validateCartMutation` is not looping anymore.

| Environment |  |
|--------|--------|
| localhost ✅ | <img width="761" height="72" alt="Screenshot 2026-01-28
at 18 57 58"
src="https://github.com/user-attachments/assets/3cbe66af-40b8-4e6e-8de0-051514b0bcfc"
/> |
| [preview](https://sfj-827e0df--b2bfaststoredev.preview.vtex.app/) ✅ |
<img width="917" height="71" alt="Screenshot 2026-01-28 at 19 12 39"
src="https://github.com/user-attachments/assets/784c42ee-b618-412f-8220-5063886ef166"
/> |
| [prod](https://b2bfaststore.vtexfaststore.com/) ✅ | <img width="890"
height="47" alt="Screenshot 2026-01-28 at 19 23 27"
src="https://github.com/user-attachments/assets/4b445d96-0839-47cc-88df-d73281b3b180"
/>|



<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Bug Fixes**
* Improved Set-Cookie domain handling: cookie domains are now normalized
based on the request host to prevent mismatched cookie scopes when
accessing the app from different hosts.
* Domain normalization is applied consistently (no longer toggled by
environment), reducing inconsistent cookie behavior across deployments.

<sub>✏️ Tip: You can customize this high-level summary in your review
settings.</sub>
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
lokinmodar pushed a commit to lokinmodar/faststore that referenced this pull request Nov 20, 2026
…ts (SFS-3034)

## Root Cause
Two factors combined to create an infinite loop in preview environments (*.preview.vtex.app):

1. Cookie domain normalization in BFF ignored `x-forwarded-host` header: In preview infrastructure, the public hostname is delivered in `x-forwarded-host`, not `request.headers.host`. The cookie normalization logic failed silently, returning cookies with the wrong domain. Browsers rejected them due to domain mismatch (RFC 6265), leaving no session cookie.

2. Fallback to `order?.orderNumber` was removed in PR vtex#3178: Without a cookie, the resolver had no fallback and passed `id: undefined` to create a new orderForm on every request. Each response provided a new orderFormId, triggering an infinite validation loop (~94 requests in 26s).

## Fixes

1. **Header priority fix** (`@faststore/core`): Check `x-forwarded-host` before `request.headers.host` when normalizing cookie domains. This ensures preview environments (where the public hostname is in `x-forwarded-host`) correctly rewrite cookie domains.

2. **Defensive fallback** (`@faststore/api`): Reintroduce fallback to `order?.orderNumber` when `orderFormIdFromCookie` is absent. This protects against cookie delivery issues and provides resilience in environments with cookie restrictions.

## Impact
- Fixes infinite loop in preview/QA environments
- No impact on production (custom domains continue to work)
- Minimal risk: both changes restore defensive patterns that existed in v3.93.x

## References
- Regression introduced by: PR vtex#3178 (Jan 21, 2026)
- Incomplete fix attempt: PR vtex#3190 (Feb 2, 2026 - didn't handle x-forwarded-host)
- Related issue: vtex#3188 (prematurely closed)
- Customer ticket: #1467584 / SO-686
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants