Fix “http://[::1]:5173” CORS policy: No ‘Access-Control-Allow-Origin’

Posted on

How to solve http://[::1]:5173 problem Laravel on Server

This issue occurs because Laravel application on the server is still trying to access the Vite development server running at http://[::1]:5173 (localhost), while it should be using assets already built for production.

Cause:

  • Vite is still in development mode on the server
  • Assets have not been built for production
  • Environment variables are not configured correctly

Example:

homestay.com/:1 Access to script at 'http://[::1]:5173/@vite/client' from origin 'http://homestay.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.Understand this error
homestay.com/:51  GET http://[::1]:5173/@vite/client net::ERR_FAILED 200 (OK)Understand this error
homestay.com/:1 Access to script at 'http://[::1]:5173/resources/js/app.tsx' from origin 'http://homestay.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.Understand this error
homestay.com/:51  GET http://[::1]:5173/resources/js/app.tsx net::ERR_FAILED 200 (OK)Understand this error
homestay.com/:1 Access to script at 'http://[::1]:5173/resources/js/pages/welcome.tsx' from origin 'http://homestay.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.Understand this error
homestay.com/:51  GET http://[::1]:5173/resources/js/pages/welcome.tsx net::ERR_FAILED 200 (OK)Understand this error
homestay.com/:1 Access to script at 'http://[::1]:5173/@react-refresh' from origin 'http://homestay.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.Understand this error
homestay.com/:46  GET http://[::1]:5173/@react-refresh net::ERR_FAILED 200 (OK)

Solution

1. .env file

    make sure the .env file on the server does not use APP_DEBUG=true. If you want to build npm locally for production, in .env change APP_ENV=local to APP_ENV=production

      APP_DEBUG=false
      APP_ENV=production

      2. vite.config.ts

      If using Vite in production, add the “server” configuration inside “defineConfig({}); in the vite.config.js file:

       server: {
              host: '0.0.0.0', // if you need access from outside
              cors: true,
          },

      3. Build Asset

      Then, Build assets for production

      npm run build
      # or
      yarn build

      4. Push to server

      Make sure the public/build folder exists and contains the assets that have been built, then push public/build to the server.

      5. Clear cache (optional)

      If the error persists, try clearing the cache:

      php artisan config:clear
      php artisan cache:clear
      php artisan view:clear