DEV Community

Adam Gaskins
Adam Gaskins

Posted on

Laravel Vite - Upgrading Dependencies Leads to CORS Error

I'm in the middle of a major site upgrade at work. Bootstrap 4 to 5, Vue 2 to 3, the whole shebang. We've been using Laravel Herd, which has been great so far. But after running npm audit fix --force, none of the Javascript assets would load on my dev site. My console was full of CORS errors:

Access to script at 'https://mysite.test:5173/@vite/client' from origin 'https://mysite.test' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

When I ran npm run build the site would load fine, only npm run dev was causing the CORS errors.

I dug a little bit into the packages that had been updated, and came across this changelog in the Vite package:

  • fix!: default server.cors: false to disallow fetching from untrusted origins

The default for the cors option was changed to false. Since Herd serves the site from port 80, but serves the assets through vite at, in my case, port 5173, without the CORs header, this is now being blocked.

I solved this by adding the following to my vite.config.js. The snippet is modified from the link above to add the .test domain I'm using:

export default defineConfig({
    server: {
        cors: {
            origin: /^https?:\/\/(?:(?:[^:]+\.)?localhost|mysite\.test|127\.0\.0\.1|\[::1\])(?::\d+)?$/,
        },
    },

    /* ... */

})
Enter fullscreen mode Exit fullscreen mode

Hopefully this can prevent someone else from wasting the same time I did!

Top comments (1)

Collapse
 
haizk profile image
Hezkiel Bram Setiawan

thank you