Skip to content

fix(apps-vtex): build product URLs from the request origin, not publicUrl - #569

Merged
aline-pereira merged 1 commit into
mainfrom
fix/vtex-storefront-base-url
Sep 25, 2026
Merged

aline-pereira merged 1 commit into
mainfrom
fix/vtex-storefront-base-url

Conversation

@aline-pereira

@aline-pereira aline-pereira commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

O bug

Toda URL schema.org que um loader do apps-vtex emite — product.url, isVariantOf.url, url de variante, item de breadcrumb — vinha deste trecho, copiado literalmente em 11 lugares:

const baseUrl = config.publicUrl
  ? `https://${config.publicUrl}`
  : `https://${config.account}.vtexcommercestable.${config.domain ?? "com.br"}`;

Dois problemas numa linha só.

1. publicUrl costuma ser guardado como URL completa. Uma loja com publicUrl: "https://secure.example.com/" gerava https://https://secure.example.com/, e:

new URL("/camisa-paris/p", "https://https://secure.example.com/").href
// → "https://https/camisa-paris/p"

porque o parser lê host https. Toda URL de produto no JSON-LD, no payload de hidratação e nos eventos de analytics apontava pra um host que não existe.

Pego numa loja em produção — 241 ocorrências de https://https no HTML de uma única PLP:

{
  "@type": "Product",
  "@id": "https://https/camisa-paris-branca-0100441014/p?skuId=19789",
  "url":  "https://https/camisa-paris-branca-0100441014/p?skuId=19789"
}

2. Mesmo escrito certo, publicUrl é o host de checkout (secure.<brand>.com) — outro site, não a vitrine. O deco-cx/apps nunca usou ele aqui: vtex/loaders/intelligentSearch/productList.ts passa baseUrl: url, a URL da request sendo servida. As URLs canônicas de uma vitrine precisam nomear o host que o shopper realmente acessou.

O fix

storefrontBaseUrl(config?) em client.ts, com os 11 call-sites roteados por ele:

  1. origin de RequestContext.current?.request — o host da própria vitrine. Usa .current em vez de .request de propósito: workflow/products.ts roda fora de escopo de request e .request lançaria. Aqui ele cai pro passo seguinte.
  2. config.publicUrl, normalizado por URL tenha ou não esquema. É isso que mata a classe inteira do bug de esquema duplicado.
  3. https://${vtexHost(...)} — o host da conta, sempre bem formado.

Retorna origin sem barra final, então new URL(path, baseUrl) se comporta igual nos três ramos.

Call sites tocados (11)
  • loaders/intelligentSearch/productDetailsPage.ts
  • loaders/intelligentSearch/productList.ts
  • loaders/intelligentSearch/productListingPage.ts
  • loaders/intelligentSearch/suggestions.ts
  • loaders/legacy/relatedProductsLoader.ts
  • loaders/autocomplete.ts
  • loaders/productListFull.ts
  • loaders/workflow/products.ts
  • utils/enrichment.ts (×2)
  • utils/similars.ts

Compatibilidade

Quem não define publicUrl não muda de comportamento (ramo 3 é o mesmo de antes). Quem define passa a receber o host da request em vez do host de checkout — que é o comportamento do deco-cx/apps e o que a loja precisa pra SEO. Fora de escopo de request (workflows), o publicUrl normalizado continua valendo.

Gate Evidence

Gate Resultado
apps-vtex test ✅ 28 arquivos, 292 testes — 7 novos em utils/__tests__/storefrontBaseUrl.test.ts
apps-vtex typecheck ✅ limpo
repo typecheck ✅ sem regressão — os erros restantes são de blocks-cli e já estão em main
lint (biome) a config pede espaços e o repo inteiro usa tabs; main já tem 545 erros dessa classe e não há gate de lint no CI. Os arquivos aqui seguem os vizinhos (tabs).

O teste cobre o caso exato da regressão:

it("never returns the double-scheme origin a full publicUrl used to produce", () => {
  configureVtex({ account: "examplestore", publicUrl: "https://secure.example.com/" });
  expect(storefrontBaseUrl()).toBe("https://secure.example.com");
});

mais: origin da request tem precedência, publicUrl sem esquema, fallback de host da conta, domain configurado, publicUrl impossível de parsear, e ausência de barra final.

🤖 Generated with Claude Code


Summary by cubic

Fixes every schema.org product, variant, and breadcrumb URL emitted by apps-vtex loaders pointing at a non-existent host. Building the base URL from config.publicUrl produced https://https/<slug>/p when the config was stored as a full URL, and even when well-formed, publicUrl is the checkout host, not the storefront.

Bug Fixes

  • Routes all 11 call sites through a new storefrontBaseUrl() helper in client.ts.
  • Prefers the origin of the request being served so canonical URLs name the host the shopper actually reached, matching deco-cx/apps.
  • Falls back to publicUrl normalized through URL whether or not it carries a scheme, then to the account's VTEX host — stores without publicUrl keep their previous behavior.
  • Uses RequestContext.current rather than .request so workflow loaders outside a request scope fall through safely.

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

Review in cubic

…cUrl

Every schema.org URL an apps-vtex loader emits — `product.url`,
`isVariantOf.url`, variant `url`, breadcrumb `item` — was built from:

    const baseUrl = config.publicUrl
      ? `https://${config.publicUrl}`
      : `https://${config.account}.vtexcommercestable.${config.domain ?? "com.br"}`;

copied verbatim into 11 places. Two problems in one line.

1. `publicUrl` is commonly stored as a full URL. A storefront configured with
   `publicUrl: "https://secure.example.com/"` produced
   `https://https://secure.example.com/`, and

       new URL("/camisa-paris/p", "https://https://secure.example.com/").href
       → "https://https/camisa-paris/p"

   because the URL parser reads host `https`. Every product URL in the
   JSON-LD, the hydration payload and the analytics events pointed at a host
   that does not exist. Caught on a live storefront: 241 occurrences of
   `https://https` in the HTML of a single PLP.

2. Even spelled correctly, `publicUrl` is the VTEX *checkout* host
   (`secure.<brand>.com`) — a different site from the storefront. deco-cx/apps
   never used it here: `vtex/loaders/intelligentSearch/productList.ts` passes
   `baseUrl: url`, the URL of the request being served. A storefront's
   canonical URLs have to name the host the shopper actually reached.

Adds `storefrontBaseUrl(config?)` to `client.ts` and routes all 11 call sites
through it:

  1. `RequestContext.current?.request` origin — the storefront's own host.
     Uses `.current` rather than `.request` so workflow loaders, which run
     outside a request scope, fall through instead of throwing.
  2. `config.publicUrl`, normalised through `URL` whether or not it carries a
     scheme. This is what kills the whole double-scheme class of bug.
  3. `https://${vtexHost(...)}` — the account host, always well-formed.

Returns an origin with no trailing slash, so `new URL(path, baseUrl)` behaves
identically on every branch.

Gate Evidence
  apps-vtex test       ✅ 28 files, 292 tests (7 new)
  apps-vtex typecheck  ✅ clean
  repo typecheck       ✅ sem regressão — os erros restantes são de blocks-cli,
                       pré-existentes em main
  lint (biome)         a config pede espaços e o repo inteiro usa tabs; main já
                       está com 545 erros dessa classe e não há gate de lint no
                       CI. Os arquivos novos seguem os vizinhos (tabs).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@aline-pereira
aline-pereira requested a review from a team September 25, 2026 12:37
@JonasJesus42

Copy link
Copy Markdown
Contributor

Já aprovei — o https://https/ é bug inequívoco, normalizar via URL mata a classe inteira, e consolidar os 11 call-sites duplicados numa função é ganho puro. Tratar RequestContext.current?.request em vez de .request, por causa do workflow/products.ts rodar fora de escopo de request, está bem pensado.

Registrando um risco pra não passar batido no merge, já que o PR muda a natureza do dado e não só o valor.

A saída de section passa a depender do host, e os caches de section são cegos a host.

layoutLoaderCacheKey  = `${component}::${device}`     sectionLoaders.ts:344-346
resolvedLayoutCache   = `${blockKey}::${device}`      resolve.ts:1183-1185

Nenhuma das duas chaves inclui host. Antes isso era seguro justamente porque publicUrl era constante: a saída do transform não dependia de quem pediu. Com a origin da request, um Header com vitrine (layout-cached) populado pelo host A passa a servir URLs do host A pro host B durante todo o TTL.

Não é hipotético no momento: a Oficina está no ar em oficina-tanstack.deco-cx.workers.dev em paralelo com o domínio de produção — é exatamente a topologia que dispara isso. Apex vs www cai no mesmo caso.

Segundo ponto, de comportamento. Havendo request em escopo, publicUrl é ignorado por completo. Um site alcançável por host de preview/staging passa a emitir JSON-LD e canonical nomeando esse host. Pra URL canônica isso costuma ser o oposto do desejado — canonical existe pra apontar pro host oficial independente de por onde o shopper entrou. O argumento do PR (o deco-cx/apps lia da request) vale pros links navegacionais; pro canônico o trade-off é diferente.

Três saídas, na minha ordem de preferência:

  1. Incluir host nas chaves dos caches de section — resolve a contaminação e mantém o comportamento por-host que o PR quer.
  2. Separar os dois usos: origin da request pro que é navegacional, host canônico configurado pro canonical e pro JSON-LD.
  3. No mínimo, documentar a limitação e não registrar como layout/cacheable nenhuma section que embuta URL de produto.

Nada disso precisa entrar neste PR — o fix que ele faz é claramente melhor que o status quo. Mas vale abrir o follow-up antes que alguém cacheie uma vitrine no Header e passe uma tarde caçando URL de preview em JSON-LD de produção.

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.

2 participants