Skip to content

fix: resolve erro fetch in request subacconts#1593

Open
ApMatheus wants to merge 2 commits into
deco-cx:mainfrom
ApMatheus:fix/subaccounvtex
Open

fix: resolve erro fetch in request subacconts#1593
ApMatheus wants to merge 2 commits into
deco-cx:mainfrom
ApMatheus:fix/subaccounvtex

Conversation

@ApMatheus

@ApMatheus ApMatheus commented May 20, 2026

Copy link
Copy Markdown
Contributor

Fix: Sales Channel não respeitado no Intelligent Search

Problema

Produtos de todas as políticas comerciais estavam sendo retornados, ignorando a configuração salesChannel: "4".

Causa Raiz

No arquivo newapps-deco/apps/vtex/mod.ts (linha ~150), o cliente HTTP vcsDeprecated estava configurado com:

const vcsDeprecated = createHttpClient<VTEXCommerceStable>({
  base: publicUrl, // ❌ https://secure.lojaspaqueta.com.br
  processHeaders: removeDirtyCookies,
  fetcher: fetchSafe,
});

O domínio secure.lojaspaqueta.com.br possui um binding no License Manager da VTEX que não respeita corretamente o filtro de sales channel, retornando produtos de múltiplas políticas comerciais.

Solução

Alterado para usar o domínio vtexcommercestable, que respeita corretamente a política comercial:

const vcsDeprecated = createHttpClient<VTEXCommerceStable>({
  base: `https://${account}.vtexcommercestable.com.br`, // ✅ grupooscar.vtexcommercestable.com.br
  processHeaders: removeDirtyCookies,
  fetcher: fetchSafe,
});

Impacto

  • ✅ Intelligent Search agora respeita salesChannel: "4"
  • ✅ Apenas produtos associados à política comercial 4 são retornados
  • ✅ Compatível com a implementação original em ../apps/vtex/

Arquivo Modificado

  • /Users/matheus/Documents/Trabalho/newapps-deco/apps/vtex/mod.ts (linha ~150)

Fix: Null Script Error no Proxy Handler

Arquivo: /Users/matheus/Documents/Trabalho/newapps-deco/apps/website/handlers/proxy.ts

Problema

TypeError: Cannot read properties of null (reading 'src')
    at proxy.ts:181:44

O proxy handler quebrava quando includeScriptsToHead.includes ou includeScriptsToBody.includes continham valores null/undefined.

Causa

O loader analytics/loaders/DecoAnalyticsScript.ts configurado em .deco/blocks/site.json retorna null em determinadas situações, causando erro ao tentar acessar script.src.

Solução

Adicionada validação para ignorar scripts nulos antes de acessar propriedades:

// Antes (linha 179-184)
for (const script of (includeScriptsToHead?.includes ?? [])) {
  scriptsInsert += typeof script.src === "string"
    ? script.src
    : script.src(req);
}

// Depois
for (const script of (includeScriptsToHead?.includes ?? [])) {
  if (!script || !script.src) continue; // ✅ Validação adicionada
  scriptsInsert += typeof script.src === "string"
    ? script.src
    : script.src(req);
}

Aplicado em:

  • includeScriptsToHead (linha ~179)
  • includeScriptsToBody (linha ~203)

Resultado

Proxy agora ignora scripts inválidos em vez de quebrar a aplicação.


Summary by cubic

Fixes VTEX subaccount fetch/auth issues by routing clients through vtexcommercestable (with subaccount support) and ensures Intelligent Search respects the configured sales channel; also guards against null scripts in the proxy.

  • Bug Fixes
    • Route VTEX clients via https://${account}.vtexcommercestable.com.br and set io GraphQL to https://${subAccount || account}.vtexcommercestable.com.br/api/io/_v/private/graphql/v1 so subaccount requests work and Intelligent Search respects salesChannel.
    • Fix auth and checkout cookies: auto-detect the correct VtexIdclientAutCookie (account or subaccount) in parseCookie, and add parseCookieWithoutAuth to safely read __ofid and send only the checkout cookie in cart/simulation requests.
    • Ignore null/undefined scripts in includeScriptsToHead and includeScriptsToBody to avoid "Cannot read properties of null (reading 'src')" errors.

Written for commit b8e322f. Summary will update on new commits. Review in cubic

Summary by CodeRabbit

  • New Features

    • Added optional "Store Name" configuration for account selection.
  • Bug Fixes

    • Corrected service endpoints to use stable account-based URLs.
    • Improved HTML proxy script injection to skip incomplete script entries and avoid errors.
    • Updated cookie parsing and checkout cookie handling to better support unauthenticated order/checkout flows across cart, profile, session, wishlist, and related actions.

Review Change Stack

@github-actions

Copy link
Copy Markdown
Contributor

Tagging Options

Should a new tag be published when this PR is merged?

  • 👍 for Patch 0.151.2 update
  • 🎉 for Minor 0.152.0 update
  • 🚀 for Major 1.0.0 update

@coderabbitai

coderabbitai Bot commented May 20, 2026

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Widespread VTEX cookie parsing refactor: parseCookie no longer accepts account, a new parseCookieWithoutAuth was added and propagated to cart actions; VTEX app Props and stable-domain endpoints were updated; proxy handler received defensive guards for script injection.

Changes

VTEX cookie & endpoint updates

Layer / File(s) Summary
Cookie helpers and discovery rewrite
vtex/utils/vtexId.ts, vtex/utils/orderForm.ts
Adds parseCookieWithoutAuth(headers) and rewrites parseCookie(headers) to discover VTEX auth cookie names and return { cookie, payload } without account argument.
ParseCookie header-only updates
vtex/actions/*, vtex/loaders/*
Numerous action and loader call sites updated to call parseCookie(req.headers) (removed ctx.account) so cookie/payload derive from headers only.
Cart/order-form actions use parseCookieWithoutAuth
vtex/actions/cart/*
Cart-related actions switched to parseCookieWithoutAuth(req.headers) to extract orderFormId and cookie without including auth cookies (attachments, simulation, coupons, gifts, updates).
VTEX mod: Props and stable endpoints
vtex/mod.ts
Props gains optional subAccount and drops setRefreshToken; VTEX factory now builds VCS/IO endpoints from fixed account/subAccount-based stable domains instead of publicUrl.

Website proxy handler fixes

Layer / File(s) Summary
Script injection defensive guards
website/handlers/proxy.ts
Added guards in both <head> and <body> injection loops to skip script entries that are missing or lack a src attribute.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • deco-cx/apps#1586: Changes to VTEX cookie helpers and related parsing utilities that overlap with the new parseCookie/parseAuthCookie logic.

Suggested reviewers

  • guitavano

🐰 I hopped through cookies and endpoints wide,
Tuned routes and parsers with a careful stride.
Cart crumbs now read only what they should,
Scripts skip the blanks — the page stays good.
A tiny rabbit cheer for changes applied!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Title check ❓ Inconclusive The title 'fix: resolve erro fetch in request subacconts' is partially related to the PR changes but is vague, contains a typo ('erro' should be 'error', 'subacconts' should be 'subaccounts'), and does not clearly highlight the main fixes. Improve the title to be clearer and more specific, such as: 'fix: route VTEX clients via vtexcommercestable and add null script guards' or 'fix: respect sales channel and null script handling in VTEX and proxy'.
✅ Passed checks (4 passed)
Check name Status Explanation
Description check ✅ Passed The PR description is comprehensive and detailed, covering both fixes with clear problem statements, root causes, and solutions. However, it does not follow the repository's template structure (missing explicit 'What is this Contribution About?', 'Issue Link', and 'Loom Video' sections).
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@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 2 files

Re-trigger cubic

@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: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@vtex/mod.ts`:
- Line 155: The object property "endpoint" in vtex/mod.ts has an extra space
after the colon ("endpoint:  `https://...`"); remove the double space so it
reads "endpoint: `https://...`" (i.e., ensure a single space after the colon in
the endpoint property/template-string) to fix the formatting failure.
- Around line 48-52: The JSDoc block above the subAccount property is
mis-indented and failing Deno fmt; fix by aligning the comment markers and
content to standard JSDoc formatting so the opening /**, each line with a single
leading space and the closing */ align with the property declaration; update the
comment that documents subAccount (symbol: subAccount) to use consistent
indentation and spacing for title/description lines so the formatter passes.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 80e1142b-b191-45b0-b9b2-4235f8d04de6

📥 Commits

Reviewing files that changed from the base of the PR and between 1b5e32f and b8e322f.

📒 Files selected for processing (45)
  • vtex/actions/address/create.ts
  • vtex/actions/address/delete.ts
  • vtex/actions/address/update.ts
  • vtex/actions/authentication/logout.ts
  • vtex/actions/cart/addItems.ts
  • vtex/actions/cart/addOfferings.ts
  • vtex/actions/cart/clearOrderformMessages.ts
  • vtex/actions/cart/getInstallment.ts
  • vtex/actions/cart/removeItemAttachment.ts
  • vtex/actions/cart/removeItems.ts
  • vtex/actions/cart/removeOffering.ts
  • vtex/actions/cart/simulation.ts
  • vtex/actions/cart/updateAttachment.ts
  • vtex/actions/cart/updateCoupons.ts
  • vtex/actions/cart/updateGifts.ts
  • vtex/actions/cart/updateItemAttachment.ts
  • vtex/actions/cart/updateItemPrice.ts
  • vtex/actions/cart/updateItems.ts
  • vtex/actions/cart/updateProfile.ts
  • vtex/actions/cart/updateUser.ts
  • vtex/actions/masterdata/createDocument.ts
  • vtex/actions/masterdata/updateDocument.ts
  • vtex/actions/newsletter/updateNewsletterOptIn.ts
  • vtex/actions/orders/cancel.ts
  • vtex/actions/payment/deletePaymentToken.ts
  • vtex/actions/profile/updateProfile.ts
  • vtex/actions/session/deleteSession.ts
  • vtex/actions/session/editSession.ts
  • vtex/actions/wishlist/addItem.ts
  • vtex/actions/wishlist/removeItem.ts
  • vtex/loaders/address/getUserAddresses.ts
  • vtex/loaders/masterdata/searchDocuments.ts
  • vtex/loaders/orders/getById.ts
  • vtex/loaders/orders/list.ts
  • vtex/loaders/payment/paymentSystems.ts
  • vtex/loaders/payment/userPayments.ts
  • vtex/loaders/profile/getCurrentProfile.ts
  • vtex/loaders/profile/getProfileByEmail.ts
  • vtex/loaders/promotion/getPromotionById.ts
  • vtex/loaders/session/getUserSessions.ts
  • vtex/loaders/user.ts
  • vtex/loaders/wishlist.ts
  • vtex/mod.ts
  • vtex/utils/orderForm.ts
  • vtex/utils/vtexId.ts

Comment thread vtex/mod.ts
Comment on lines +48 to +52
/**
* @title Store Name
* @description VTEX Store name For more info, read here: https://help.vtex.com/en/tutorial/account-details-page--2vhUVOKfCaswqLguT2F9xq#stores
*/
subAccount?: string;

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Formatting issues causing pipeline failure.

The JSDoc block has inconsistent indentation - the /** and content are misaligned. This is causing the Deno fmt check to fail.

🔧 Proposed fix
-    /**
-   * `@title` Store Name
-   * `@description` VTEX Store name For more info, read here: https://help.vtex.com/en/tutorial/account-details-page--2vhUVOKfCaswqLguT2F9xq#stores
-   */
-    subAccount?: string;
+  /**
+   * `@title` Store Name
+   * `@description` VTEX Store name For more info, read here: https://help.vtex.com/en/tutorial/account-details-page--2vhUVOKfCaswqLguT2F9xq#stores
+   */
+  subAccount?: string;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
/**
* @title Store Name
* @description VTEX Store name For more info, read here: https://help.vtex.com/en/tutorial/account-details-page--2vhUVOKfCaswqLguT2F9xq#stores
*/
subAccount?: string;
/**
* `@title` Store Name
* `@description` VTEX Store name For more info, read here: https://help.vtex.com/en/tutorial/account-details-page--2vhUVOKfCaswqLguT2F9xq#stores
*/
subAccount?: string;
🧰 Tools
🪛 GitHub Actions: ci / Bundle & Check Apps (ubuntu-latest)

[error] 48-164: deno fmt --check failed. Found 1 not formatted file. Run 'deno fmt' (or 'deno fmt --write') to apply formatting.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@vtex/mod.ts` around lines 48 - 52, The JSDoc block above the subAccount
property is mis-indented and failing Deno fmt; fix by aligning the comment
markers and content to standard JSDoc formatting so the opening /**, each line
with a single leading space and the closing */ align with the property
declaration; update the comment that documents subAccount (symbol: subAccount)
to use consistent indentation and spacing for title/description lines so the
formatter passes.

Comment thread vtex/mod.ts
: `${publicUrl}/api/io/_v/private/graphql/v1`;
const io = createGraphqlClient({
endpoint: ioUrl,
endpoint: `https://${subAccount || account}.vtexcommercestable.com.br/api/io/_v/private/graphql/v1`,

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Extra whitespace causing fmt failure.

There's a double space after endpoint: that should be a single space.

🔧 Proposed fix
-    endpoint:  `https://${subAccount || account}.vtexcommercestable.com.br/api/io/_v/private/graphql/v1`,
+    endpoint: `https://${subAccount || account}.vtexcommercestable.com.br/api/io/_v/private/graphql/v1`,
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
endpoint: `https://${subAccount || account}.vtexcommercestable.com.br/api/io/_v/private/graphql/v1`,
endpoint: `https://${subAccount || account}.vtexcommercestable.com.br/api/io/_v/private/graphql/v1`,
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@vtex/mod.ts` at line 155, The object property "endpoint" in vtex/mod.ts has
an extra space after the colon ("endpoint:  `https://...`"); remove the double
space so it reads "endpoint: `https://...`" (i.e., ensure a single space after
the colon in the endpoint property/template-string) to fix the formatting
failure.

@ApMatheus

Copy link
Copy Markdown
Contributor Author

Problema

Em cenários VTEX multistore/subaccount, o cookie de autenticação pode vir em dois formatos:

  • VtexIdclientAutCookie (loja padrão)
  • VtexIdclientAutCookie_<nomeDaConta> (subaccount)

O parseCookie em vtexId.ts fazia uma busca por nome exato — checava apenas VtexIdclientAutCookie e VtexIdclientAutCookie_${account}. Qualquer variação no sufixo (nome do subaccount, domínio customizado, capitalização) fazia o cookie não ser encontrado, fazendo o usuário aparecer como não autenticado mesmo estando logado.

Além disso, todas as actions de carrinho estavam encaminhando o header cookie completo da requisição para a VTEX, o que incluía o token de autenticação do usuário — desnecessário para operações de checkout e um risco de exposição evitável.

Alterações

vtex/utils/vtexId.ts

parseCookie não recebe mais o parâmetro account. Agora percorre todos os cookies e encontra o primeiro que começa com VtexIdclientAutCookie, ordenado por comprimento para que o nome base tenha prioridade sobre variantes com sufixo.

// antes
parseCookie(headers, account) → busca exata por VtexIdclientAutCookie_${account}

// depois
parseCookie(headers) → encontra qualquer cookie que começa com "VtexIdclientAutCookie"

console.logs de debug removidos de parseAuthCookie.

vtex/utils/orderForm.ts

Adicionada parseCookieWithoutAuth — uma variante do parseCookie que retorna { orderFormId, cookie } contendo apenas o cookie de checkout (checkout.vtex.com), sem o token de autenticação.

vtex/actions/cart/* (16 arquivos)

Todas as actions de carrinho passaram a usar parseCookieWithoutAuth no lugar de passar o header cookie cru para a VTEX. Isso consolida o padrão de duas linhas em uma:

// antes
const { orderFormId } = parseCookie(req.headers);
const cookie = req.headers.get("cookie") ?? "";

// depois
const { orderFormId, cookie } = parseCookieWithoutAuth(req.headers);

Todos os loaders e actions que usavam parseCookie de vtexId.ts (~25 arquivos)

Todos os call sites atualizados para a nova assinatura:

// antes
parseCookie(req.headers, ctx.account)

// depois
parseCookie(req.headers)

Afetados: user, wishlist, cart, orders, address, profile, masterdata, session, payment, promotion, newsletter, authentication.

vtex/mod.ts

  • Prop setRefreshToken removida (não era utilizada)
  • Cliente vcs passou a usar https://${account}.vtexcommercestable.com.br (URL estável) em vez de publicUrl, evitando conflitos com domínios de proxy customizados

Testes

  • Autenticação funciona na loja padrão (VtexIdclientAutCookie)
  • Autenticação funciona em subaccount (VtexIdclientAutCookie_<nome>)
  • Adicionar, remover e atualizar itens no carrinho funcionam corretamente
  • Nenhum token de auth é enviado nos headers das operações de carrinho
  • Wishlist, pedidos, endereços e perfil carregam corretamente para usuários autenticados

@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.

1 issue found across 45 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="vtex/mod.ts">

<violation number="1" location="vtex/mod.ts:155">
P2: Double space after `endpoint:` is causing the `deno fmt` check to fail. Should be a single space.</violation>
</file>

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread vtex/mod.ts
: `${publicUrl}/api/io/_v/private/graphql/v1`;
const io = createGraphqlClient({
endpoint: ioUrl,
endpoint: `https://${subAccount || account}.vtexcommercestable.com.br/api/io/_v/private/graphql/v1`,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: Double space after endpoint: is causing the deno fmt check to fail. Should be a single space.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At vtex/mod.ts, line 155:

<comment>Double space after `endpoint:` is causing the `deno fmt` check to fail. Should be a single space.</comment>

<file context>
@@ -152,16 +151,13 @@ export default function VTEX(
-    : `${publicUrl}/api/io/_v/private/graphql/v1`;
   const io = createGraphqlClient({
-    endpoint: ioUrl,
+    endpoint:  `https://${subAccount || account}.vtexcommercestable.com.br/api/io/_v/private/graphql/v1`,
     processHeaders: removeDirtyCookies,
     fetcher: fetchSafe,
</file context>
Suggested change
endpoint: `https://${subAccount || account}.vtexcommercestable.com.br/api/io/_v/private/graphql/v1`,
endpoint: `https://${subAccount || account}.vtexcommercestable.com.br/api/io/_v/private/graphql/v1`,

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.

1 participant