Deploying a NextJS site using cdk

Mar 30, 2021

Setup

Ensure aws-cdk is installed.

npm install -g aws-cdk

Then bootstrap the CDK project by creating a folder where we will keep our deployment code:

mkdir deploy && cd deploy

Finally initialize the CDK application:

cdk init --language=typescript

Open up lib/deploy-stack.ts. It'll look something like this:

import * as cdk from '@aws-cdk/core';

export class DeletemeStack extends cdk.Stack {
  constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    // The code that defines your stack goes here
  }
}

Install the required dependencies

npm install @aws-cdk/aws-s3 @aws-cdk/aws-s3-deployment

Create a bucket to store our site in

We need a place to host our website. We'll use a s3 bucket for that. Note that since the bucket will be serving a website, we need to allow publicReadAccess and additionally set an index document.

const websiteBucket = new s3.Bucket(this, 'WebsiteBucket', {
    publicReadAccess: true,
    websiteIndexDocument: 'index.html'
  });

I am only going to deploy a static version of my site, however, by default NextJS builds a version of the site to be served up using Node. We can get it to create a static version of the site using: next export which will create an out folder containing the static versio of our site. I'll adjust the build in package.json to do this by default when we build:

  "scripts": {
    ...
    "build": "next build && next export",
    ...
  },

We could manually copy the out folder to the bucket created above, but CDK has a construct to do this for us called BucketDeployment in the @aws-cdk/aws-s3-deployment package:

new s3Deployment.BucketDeployment(this, 'DeployWebsite', {
    destinationBucket: websiteBucket,
    sources: [s3Deployment.Source.asset("../out")]
  });

Finally we need to know the endpoint of our website:

new cdk.CfnOutput(this, "WebsiteURL", {
      value: websiteBucket.bucketWebsiteUrl
  });

Running the deploy

Simply run:

cdk deploy

This will create a new 'Stack' called DeployStack, and the necessary resources to host your site.

When it's all said and done CDK will output the URL of the newly hosted site:

 ✅  DeployStack

Outputs:
DeployStack.WebsiteURL = http://deploystack-websitebucket75c24d94-16jtb8ug8sqtg.s3-website-ap-southeast-2.amazonaws.com

In the next post Next up, we'll use CDK to create a CloudFront distribution.