Skip to content

Nexode-Consulting/terraform-aws-nextjs-serverless

Repository files navigation

Terraform Next.js module for AWS

Zero-Config Terraform Module to deploy Next.js Apps on AWS using Serverless solutions

Usage

Dependencies

  • Node: 16+
  • Terraform: 1.6.3+
  • bash
  • zip

Prepare

Add the following dependencies & script to your package.json file

package.json

{
  "scripts": {
    "build-serverless-next": "build-serverless-next",
    ...
  },
  "dependencies": {
    "build-serverless-next": "latest",
    "next": "^13",
    ...
  },
  ...
}

Add the output: "standalone" option to the next.config.js file

next.config.js

const nextConfig = {
  ...
  "output": "standalone",
  ...
}

module.exports = nextConfig

Create Terraform deployment

Check it on Terraform Registry for more details.

Ensure that the deployment name is unique since its used for creating s3 buckets.

main.tf

provider "aws" {
  region = "eu-central-1" #customize your region
}

provider "aws" {
  alias  = "global_region"
  region = "us-east-1" #must be us-east-1
}

module "next_serverless" {
  source  = "Nexode-Consulting/nextjs-serverless/aws"

  deployment_name = "nextjs-serverless" #needs to be unique since it will create s3 buckets
  region          = "eu-central-1" #customize your region
  base_dir        = "./" #The base directory of the next.js app
}

output "next_serverless" {
  value = module.next_serverless
}

Deployment

Build the Next.js Code and deploy

npm i build-serverless-next
npm run build-serverless-next

terraform init
terraform apply

Architecture

Module

Module

Distribution

Distribution

Cache

Cache

Examples

  • Next.js v13 Complete example with SSR, API, static pages, image optimization & custom domain

Known Issues

  • The build-serverless-next package's version must match the next_serverless module's version
  • The app/ folder must be in the root directory (ex. not in the src/ directory)
  • When destroying the next_serverless module, Lambda@Edge function need at least 15mins to be destroy, since they're replicated functions
  • Using the <img> tag or background-image css property might face issues rendering images, please use the build-in <Image /> component. Meanwhile, please move all images, icons, etc... in the public folder.
  • In some rare cases, some modules can not be imported by next_lambda (for unknown reasons). To solve this issue use build-serverless-next --copyAllPackages to copy all the packages or build-serverless-next --packages-to-copy=package_1,package_2,package_3 to copy specific packages only

Contributing

Feel free to improve this module.
Our contributing guidelines will help you get started.

About

This module is maintained by Nexode Consulting.
We help companies develop and operate enterprise-grade software with startup momentum.

License

Apache-2.0 - see LICENSE for details.