Skip to content

Instantly share code, notes, and snippets.

@simonyeldon
Created September 11, 2023 13:40
Show Gist options
  • Save simonyeldon/807d3bc33958ff623f99752d3a8746b5 to your computer and use it in GitHub Desktop.
Save simonyeldon/807d3bc33958ff623f99752d3a8746b5 to your computer and use it in GitHub Desktop.
Run a NextJS app in a Lambda, with Terraform
resource "aws_lambda_function" "nextjs_lambda" {  
  filename         = var.standalone_zip
  function_name    = "nextjs-lambda"
  role             = aws_iam_role.nextjs_lambda_role.arn
  handler          = "run.sh"
  runtime          = "nodejs16.x"
  architectures    = ["x86_64"]
  source_code_hash = filebase64sha256(var.standalone_zip)
  layers = [
    "arn:aws:lambda:${var.aws_region}:753240598075:layer:LambdaAdapterLayerX86:16"
  ]
  environment {
    variables = { 
      AWS_LAMBDA_EXEC_WRAPPER = "/opt/bootstrap"
      NODE_ENV                = "production"
      PORT                    = "3000"
      RUST_LOG                = "info"
    }
  }
}

resource "aws_lambda_function_url" "nextjs_lambda" {
  function_name      = aws_lambda_function.nextjs_lambda.function_name
  authorization_type = "NONE"
  cors {
    allow_credentials = true
    allow_origins     = ["*"]
    allow_methods     = ["*"]
    allow_headers     = ["date", "keep-alive"]
    expose_headers    = ["keep-alive", "date"]
    max_age           = 86400
  }
}

resource "aws_s3_bucket" "nextjs_bucket" {
  bucket = "nextjs-web-static-bucket"
}

resource "aws_s3_bucket_website_configuration" "nextjs_bucket" {
  bucket = aws_s3_bucket.nextjs_bucket.id

  index_document {
    suffix = "index.html"
  }

  error_document {
    key = "error.html"
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment