Custom s3 base URLs for Vite compiled asset in Laravel App

1.3k Views Asked by At

I'm using Laravel 9 application. Laravel latest version has replaced webpack to vite. I was able to successfully run the app into my local environment but, while deploying the compiled assets to the AWS S3 I'm getting CORS error in the browser console.

Steps I did after running in local environment.

added ASSET_URL=https://****.s3.ap-south-1.amazonaws.com in my .env file

run npm run build

run aws s3 sync public/ s3://****/ --delete --exclude index.php --acl public-read

I can see that my .css and other files are loaded perfectly, but I'm getting CORS error only in the compiled js file.

enter image description here

I also added policy in my s3 bucket:

{
    "Version": "2012-10-17",
    "Id": "Policy1617109982386",
    "Statement": [
        {
            "Sid": "Stmt1617109981105",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::****/*"
        }
    ]
}

But this isn't helping me out.

My Vite config file looks like:

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '@vitejs/plugin-vue';

export default defineConfig({
    plugins: [
        laravel({
            input: 'resources/js/app.js',
            refresh: true,
        }),
        vue({
            template: {
                transformAssetUrls: {
                    base: null,
                    includeAbsolute: false,
                },
            },
        }),
    ],
});

I also tried declaring cors in vite.config.js file:

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '@vitejs/plugin-vue';

export default defineConfig({
    plugins: [
        laravel({
            input: 'resources/js/app.js',
            refresh: true,
        }),
        vue({
            template: {
                transformAssetUrls: {
                    base: null,
                    includeAbsolute: false,
                },
            },
        }),
    ],
    server: {
        cors: true
    }
});

I'm unable to find any solution. Help me out.

Thanks.

1

There are 1 best solutions below

0
On

Hey Have a look at setting CORS in the s3 bucket.

https://docs.aws.amazon.com/AmazonS3/latest/userguide/ManageCorsUsing.html