JavaScript that fetches a JSON file works perfectly on the live site, but breaks with CORS errors the moment the exact same code runs anywhere else – a staging copy, a different domain, a local test.
Client-Side fetch() Calls Should Use Relative Paths, Not Hardcoded Production URLs
Field Note #279
⚡ Quick Fix (TL;DR)
The Culprit: The fetch() call had the production domain hardcoded directly into the URL. When that same script runs on a different domain, the browser now treats it as a cross-origin request to a totally different server, triggering CORS restrictions that were never a problem when the code and the data happened to share the same origin.
The Fix: Use a relative path instead of a hardcoded absolute URL. A relative path always resolves against whatever domain is actually serving the page, so the exact same code works correctly on production, staging, or anywhere else with zero changes.
// Breaks the moment this runs on any domain other than the one hardcoded:
fetch('https://example.com/data.json')
// Always resolves against whatever domain is actually serving the page:
fetch('/data.json')Rather not untangle this yourself? Our Done-For-You team handles exactly this kind of thing, start to finish.
See DFY options → Was this helpful? Thanks for the feedback!
Tagged in :