Search code examples
javascripttypescriptvitesveltecloudflare

JS Syntax Error after deploying to CloudFlare


I have a static website built using Svelte (4.2.10) + Vite (5.1.1) + TypeScript (5.2.2).

When I run the developmental frontend by running vite locally, it runs fine and renders without any problem. When I build the website using vite build and use miniserve to serve the dist static directory, it also renders completely fine.

However, when I deploy the website on Cloudflare and open the deployed website, the browser complains about a SyntaxError and does not render.

I have created a minimal reproducible example at https://gitlab.com/hykilpikonna/vite-reproducible-bug. The only dependency required to reproduce this behaviour seems to be core-js. The bugged version can be accessed at https://test0213.hydev.org/ - this page should show "1,2,3,4,5" but instead shows a SyntaxError in the console.

Some properties of this bug:

  • It cannot be reproduced when I deploy to Cloudflare pages without a domain (i.e. https://vite-reproducible-bug.pages.dev/ works as intended)
  • It cannot be reproduced when deployed locally using Nginx.
  • It does not immediately show up. It only appears after refreshing the page when the developer console is open. However, after the bug shows up, refreshing the page doesn't fix it.
  • I have tried different browsers and clean profiles, which all showed this behaviour, so it couldn't be caused by my browser extensions.

Steps to replicate this bug from scratch:

  1. Create a vite svelte project using npm create vite@latest
  2. Install core-js, import and use it in your code
  3. Deploy it to CloudFlare pages (I used GitHub and GitLab integrations)
  4. Set a CloudFlare domain URL for the CloudFlare pages.

enter image description here

enter image description here


Solution

  • Cloudflare auto-minification is turning 1 .toString into 1.toString, breaking the syntax. This has been a known bug since at least 2022. Given that you’re already minifying your assets as is best practice, you should turn off the redundant layer; it’ll only slow down and break things.

    The setting can be found in your Cloudflare dashboard at Websites > [your website] > Speed > Optimization > Content Optimization > Auto Minify > JavaScript.

    Or you can create a Page Rule (on Cloudflare: Rules > Page Rules) to disable Auto Minify for a specific URL or page. Remember to purge the cache to see the change immediately.