Home > Mobile >  Building and serving React/Nextjs from AWS S3
Building and serving React/Nextjs from AWS S3

Time:10-01

I am building a React/Nextjs app and plan on pushing it to AWS S3 and serving it from AWS CloudFront (using the S3 bucket as a distribution origin). I will be using Route53 and DNS configurations to map my domain (say, https://myapp.example.com) to the CF distribution. But I can take care of that.

In the documentation I see that I can build and run Nextjs apps in "production mode" via:

npm run build
npm run start

However here, I want to take everything that is generated by npm run build (possibly the contents of the .next/ directory??) and upload that output to my S3 bucket.

And obviously I'm hoping that will be sufficient so that when a user goes to my domain, and they get pointed to the CF distribution (and subsequently the S3 bucket backing that distribution) they download the fully built transpiled app and it loads & runs in their browser.

How can I accomplish this? What needs to be stored on S3? And are there any special configurations that need to be supplied so that it runs in the browser as soon as they fetch the built/transpiled app from S3?

CodePudding user response:

You will need a reverse proxy service that match request url with you website url and then return the response. Read about Nginx or similar aws related services.

If you only run build and start npm command you will need to have a node server. You can export and this will be a complete static website, can run without node.

CodePudding user response:

First, you need to run an extra command to generate the static files from next, after building.

next export

This command will create a directory out. The contents of this directory should be uploaded to your S3 bucket.

Then, you need to enable "Static website hosting" on your S3 bucket through AWS console (enable it via bucket properties). For index and error documents add index.html (or whatever your main html file is).

You also need to allow access to the S3 files using the following permissions

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::[your-bucket-name]/*"
        }
    ]
}
  • Related