Automate Static NextJs application Deployments

AWS
React
Web Dev
CD

Fri Dec 30 2022

You can easily deploy your exported NextJs application, or any static website, to AWS S3 by making use of AWS CLI and bash to create a script to help automate these changes. 

This post assumes that the infrastructure for your website is already set up to use AWS S3 and therefore an AWS S3 Bucket has already been configured to statically serve assets for your website. Furthermore, this post also assumes you have installed AWS CLI and have exported the keys into your terminal so that you have valid AWS credentials to use the CLI.

If you don't have AWS CLI installed you can follow this guide to install it, additionally, if you haven't statically served your website you can follow this guide to do that.

This post assumes that you will use it with NextJs although you can use this set up with any statically served website. As long as there are html files then it will work well in a statically served S3 bucket. In fact, developright.co.uk also makes use of a statically served S3 bucket but Cloudfront is used to cache the pages.

 

Creating the bash script

Create a bash file named deploy-to-s3.sh, and paste the following code snippet in. The snippet takes two arguments: the first being the source and the second being the destination. Those arguments are then used with the aws s3 sync command that pushes the source folder contents to the destination. The destination in this case would be the S3 URL.

#!/bin/bash
FOLDER_SRC=$1
S3_DEST=$2

aws s3 sync --delete $FOLDER_SRC $S3_DEST

Ensure that the shell file is executable by using the following command. This changes the permissions with the file so that it is executable and can be run by a terminal.

chmod +x deploy-to-s3.sh

Using the executable file you have created by calling the file and supplying the source and destination arguments. You will need to know the bucket name and prefix the name with s3:// when supplying it as the destination argument.

The following is the example command I run to deploy the website for developright.co.uk

./scripts/deploy-to-s3.sh /Users/example/developright/out s3://www.developright.co.uk

From the above example, you can see that the source argument is the full path to the asset folder that is generated in NextJs when you run next export. If you aren't using NextJs you will just point this to the folder that contains your static files. 

The following snippet is a break down of the command

./scripts/deploy-to-s3.sh $STATIC_ASSET_FOLDER s3://$S3_NAME
# STATIC_ASSET_FOLDER to be replaced with the full path to the folder
# that contains the static assets for your website.
# (Run next export with NextJs to create a out folder)
# S3_NAME to be replaced with the name of the S3 bucket that has been created 

You should now see that the files are automatically synced to the S3 when you run the command. This means you do not have to manually upload the assets to S3.