Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix nextjs cloudfront static assets respond with 403?

I am trying to deploy my website to aws with cloudfront and route53. The site is deployed and running on https://higgle.io However the assets are not loading, for the images are throwing 403. How do I fix it? I am using serverless serverless-next.js. And I was following one of their blog post to set it up. So far I added which has serverless.yml on the route level.

higgle:
 component: serverless-next.js

and my next.config.js looks like

module.exports = {
  target: 'serverless',
  webpack: (config) => {
    config.module.rules.push({
      test: /\.svg$/,
      use: ['@svgr/webpack'],
    });
    return config
  }
}

While the folder structrs looks like

-root
  -.next
  -pages
    -_document.js
    -index.js
  -public
    -static
      -favicon.ico
  -next.config.js
  -package.json
  -serverless.yml

Any idea how to fix this? Thanks

like image 662
Subhendu Kundu Avatar asked Feb 20 '20 06:02

Subhendu Kundu


1 Answers

S3 is returning a 403 because your items are private.

  1. Change your S3 items to public. Check that they are accessible via your S3 static hosting address.
  2. Step 1 will fix any static resources. If you are running a single page application, you will also need to return your index page when a 404 is returned by S3. In CloudFront, go to error pages, create a custom error response, choose 404 response, choose the option to customize the response, make the response code 200 and the response page path your index page.

Your bucket policy should be:

{
"Version": "2012-10-17",
"Id": "Policy1517754859350",
"Statement": [
    {
        "Sid": "Stmt1517754856505",
        "Effect": "Allow",
        "Principal": "*",
        "Action": "s3:GetObject",
        "Resource": "arn:aws:s3:::YOUR-BUCKET-NAME/*"
    }
]

}

like image 123
F_SO_K Avatar answered Nov 15 '22 00:11

F_SO_K