ES Module Import Map Breaking Due to Automatic Link Header Generation
Hey,
so in the docs there is a section saying that:
Warning Automatic Link header generation should not have any negative performance impact on your website. If you need to disable this feature, contact us by letting us know about your circumstance in our Discord server ↗.So let me share the issue I just managed to figure out and resolve. Problem: After migrating from GitHub Pages to Cloudflare Pages, our Symfony AssetMapper application started throwing Uncaught TypeError: Failed to resolve module specifier 'htmx.org' errors in the browser console. This was happening only after second page refresh after deployment and only on Cloudflare Pages, local version worked just fine (the code is exactly the same) Root Cause: Cloudflare Pages has an automatic Link header generation feature that converts HTML <link rel="modulepreload"> tags into HTTP Link headers. This happens independently of the Early Hints setting (Early Hints was turned OFF in our settings, but Link headers were still being generated). Here's what was happening: 1. Cloudflare Pages scanned our HTML and found ~46 <link rel="modulepreload"> tags 2. These were automatically converted into a massive HTTP Link header like: link: </assets/app-HASH.js>; rel="modulepreload", </assets/bootstrap-HASH.js>; rel="modulepreload", ... 3. The browser receives this HTTP header before parsing the HTML 4. Browser immediately starts downloading and executing app.js 5. app.js contains import 'htmx.org' (a bare specifier) 6. The <script type="importmap"> hasn't been parsed yet (it's in the HTML body) 7. Browser can't resolve 'htmx.org' because the import map isn't loaded → error Why it worked elsewhere: - GitHub Pages: Doesn't have automatic Link header generation - Local dev: PHP dev server doesn't send Link headers - Safari (sometimes): Different timing/handling of modulepreload vs Chrome Solution: Create a _headers file in your public/ directory with: The ! Link directive tells Cloudflare Pages to disable automatic Link header generation. Important Note: This automatic Link header generation happens even when Early Hints is turned OFF in Cloudflare Pages settings. It appears to be a separate feature that processes HTML <link> tags during the build/deploy process. Documentation: https://developers.cloudflare.com/pages/configuration/early-hints/#disable-automatic-link-header-generation-automatic-link-header Suggestion for Cloudflare: Maybe the automatic Link header generation should be smarter about ES Module import maps, or this behavior could be more clearly documented as separate from the Early Hints feature toggle.
0 Replies