Search code examples
corsnetlifyastrojsstatic-site-generation

Static Astro site CORS error after deploying to Netlify


I've created a static website using Astro on a private GitHub repository. I was able to connect it to Netlify. Everything is fine and I also get builds deployed; But when I load the main page (index.html at, let's say, https://example.com/) I get CORS error (I guess regarding to assets loading from Cloudflare CDN):

Access to script at 'https://d33wubrfki0l68.cloudfront.net/js/0f2b5ea850b0bc00d0d93eb733c74d30fdfc396f/assets/hoisted.e9f943e8.js' from origin "my domain" has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I've tried adding a netlify.toml file at the root of my project (next to other configuration files) with the following content:

[[headers]]
  for = "/*"
  [headers.values]
    Access-Control-Allow-Origin = "*"

I've also tried adding a _headers file to the public directory (which gets built right next to the index.html file) with the following content:

/* 
  Access-Control-Allow-Origin: *

Neither have solved the problem and I get the same error. BTW, it's only on this page, because I have another page called terminal (https://example.com/terminal) which uses lot's of JavaScript and everything works fine.

Anyway, I had to deploy my website manually instead of having the project connected to the GitHub repository and couldn't leverage Netlify's asset handling (compared to what I get right now) or automatic builds.

What should I do?

Even if I were just able to tell Netlify not to put these scripts on the CDN at the first place, that would solve the problem; since deploying the dist folder manually solves the issue, and I don't really need the CDN because my website is doing pretty well regarding GTMetrix stats


Solution

  • It turns out all I had to do was to add this piece of code to the Astro configuration file (astro.config.mjs in my case):

    import { defineConfig } from 'astro/config';
    // other imports
    
    export default defineConfig({
        // other configs
    
        vite: {
           build: {
              rollupOptions: {
                 output: {
                    entryFileNames: '[name]-[hash].js',
                 },
              },
           },
        },
    });
    

    Which tells Astro to bundle all client-side js files and add them to the root of the build directory (dist in my case) instead of a subfolder like assets or whatever.