Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deploy a static website to AWS S3 using nextjs

I am still new to React and I started writing a static website using Nextjs. But when I want to deploy to AWS S3 I have some problems. I used to use webpack only and when I type yarn build I get a dist file and it is easy for me to just upload the content inside the dist file to the S3 bucket.

However after using Nextjs for SSR I found that after I build the project I get a .next file with cache, server, and static subfiles as well as BUILD_ID, build-manifest.json, react-loadable-manifest.json,records.json. I have no clue what I should upload to S3 and what those files mean.

It may be a silly question but I have already spent more than a day trying to find the solution.

like image 912
jonny Avatar asked Oct 20 '19 03:10

jonny


People also ask

Is Nextjs good for static?

Next. js also became one of the most popular Static Site Generators. In other words, it's one of the best frameworks now for building superfast and SEO-friendly Jamstack websites.

Can I deploy Nextjs on AWS?

js can be deployed to any hosting provider that supports Node. js. For example, AWS EC2 or a DigitalOcean Droplet. Then, run next build to build your application.

Can static websites created with Amazon S3 can be interactive?

Amazon S3 does not support server-side scripting, but AWS has other resources for hosting dynamic websites. To learn more about website hosting on AWS, see Web Hosting . You can use the AWS Amplify Console to host a single-page web app.


2 Answers

You can change package.json as follows.

"build": "next build && next export",

Then, you can run "yarn build". It will generate top-level directory /out in your project. Upload all contents in the folder by using the command for convenience.

aws s3 sync ./out s3://your-s3-bucket-name

Make sure you have set your bucket to serve static website and have the following bucket policy.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PublicReadGetObject",
            "Effect": "Allow",
            "Principal": {
                "AWS": "*"
            },
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::your-bucket-name/*"
        },
    ]
}
like image 68
R.Cha Avatar answered Nov 10 '22 13:11

R.Cha


Original question is very old, if you arrived here using a search, and receive Error: Cannot export when target is not server - make sure you remove target target: 'serverless' from next.config.js

Otherwise, follow the answer above from @R.Cha https://stackoverflow.com/a/62465471/13749957 which summarizes the docs here and adds S3 specific steps - https://nextjs.org/docs/advanced-features/static-html-export

like image 31
Ramakay Avatar answered Nov 10 '22 11:11

Ramakay