This is not a tutorial about how to host your Next.js site on Amplify, because their tutorial is pretty good: Hosting - Next.js on Amplify. However I had to do some additional things to make it work.
At the time of writing you can only host static
Next.js sites on AWS Amplify.
There are 2 approaches:
- CLI workflow - you manually
publish
changes to your live site - Git-based workflow -
pushes
to your github repository initialize a build and deploy
Updating the Node.js version of the build env
As I picked the Git-based workflow and pushed my code to Github - the build failed - turns out the version of Node.js used in the build environment was too old to be compatible for building tailwindcss v2. After my build failed I added an nvm install 14
step to the preBuild
.
frontend:
phases:
preBuild:
commands: ['nvm install 14', 'npm ci']
This fixed my issue and the next time I initiated the build it succeeded.
Redirect paths that can't be found
If I tried to go directly to a path on my site, that does not exist it returned unstyled XML content. This makes sense, because we're serving a static site that consists of html pages, we have to set a behavior for when the requested route doesn't exist.
The way to fix it is to add a custom redirect and redirect paths under a folder that can't be found to a custom 404 page.
Add a Redirect in your Amplify Rewrites and redirects configuration
- from
source address
/<*> totarget address
/404.html withType
404 (Rewrite).
That was enough to get my website up and running.
Amplify invalidates cache instantly on deploys
The Amplify console offers instant cache invalidation by setting the header cache-control: max-age=0
, which means that the browser asks the CDN if the files cached in the browser match the latest available version.
If the files match what's on the CDN - the browser serves the assets from its own cache. Otherwise the new assets are fetched from the origin (S3 Bucket).
If you want to cache more aggressively you could enable performance mode on a per branch basis. Performance mode optimizes for faster hosting performance by keeping content cached at the edge for longer, but code changes can take up to 10 minutes
to roll out.
Export after build and set the artifacts baseDirectory to out in the build commands
Two additional things to know about, that are specified in the Amplify docs are:
- Set your
build
script in package.json to export after build
{
"build": "next build && next export"
}
- Set your artifacts
baseDirectory
to out in your build commands
artifacts:
baseDirectory: out
This post was originally published at bobbyhadz.com on November 29, 2020. You can also find me on github and twitter.
Discussion (0)