Repository navigation
fix(apps-vtex): build product URLs from the request origin, not publicUrl - #569
Conversation
…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]>
|
Já aprovei — o 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. Nenhuma das duas chaves inclui host. Antes isso era seguro justamente porque Não é hipotético no momento: a Oficina está no ar em Segundo ponto, de comportamento. Havendo request em escopo, Três saídas, na minha ordem de preferência:
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. |
O bug
Toda URL schema.org que um loader do
apps-vtexemite —product.url,isVariantOf.url,urlde variante,itemde breadcrumb — vinha deste trecho, copiado literalmente em 11 lugares:Dois problemas numa linha só.
1.
publicUrlcostuma ser guardado como URL completa. Uma loja compublicUrl: "https://secure.example.com/"geravahttps://https://secure.example.com/, e: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://httpsno 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. Odeco-cx/appsnunca usou ele aqui:vtex/loaders/intelligentSearch/productList.tspassabaseUrl: 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?)emclient.ts, com os 11 call-sites roteados por ele:RequestContext.current?.request— o host da própria vitrine. Usa.currentem vez de.requestde propósito:workflow/products.tsroda fora de escopo de request e.requestlançaria. Aqui ele cai pro passo seguinte.config.publicUrl, normalizado porURLtenha ou não esquema. É isso que mata a classe inteira do bug de esquema duplicado.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.tsloaders/intelligentSearch/productList.tsloaders/intelligentSearch/productListingPage.tsloaders/intelligentSearch/suggestions.tsloaders/legacy/relatedProductsLoader.tsloaders/autocomplete.tsloaders/productListFull.tsloaders/workflow/products.tsutils/enrichment.ts(×2)utils/similars.tsCompatibilidade
Quem não define
publicUrlnã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 dodeco-cx/appse o que a loja precisa pra SEO. Fora de escopo de request (workflows), opublicUrlnormalizado continua valendo.Gate Evidence
apps-vtex testutils/__tests__/storefrontBaseUrl.test.tsapps-vtex typechecktypecheckblocks-clie já estão emmainlint(biome)mainjá 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:
mais: origin da request tem precedência,
publicUrlsem esquema, fallback de host da conta,domainconfigurado,publicUrlimpossí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-vtexloaders pointing at a non-existent host. Building the base URL fromconfig.publicUrlproducedhttps://https/<slug>/pwhen the config was stored as a full URL, and even when well-formed,publicUrlis the checkout host, not the storefront.Bug Fixes
storefrontBaseUrl()helper inclient.ts.deco-cx/apps.publicUrlnormalized throughURLwhether or not it carries a scheme, then to the account's VTEX host — stores withoutpublicUrlkeep their previous behavior.RequestContext.currentrather than.requestso workflow loaders outside a request scope fall through safely.Written for commit e5d23fc. Summary will update on new commits.