1.2.4 • Published 3 years ago

next-deploy v1.2.4

Weekly downloads
40
License
MIT
Repository
github
Last release
3 years ago

Next Deploy

Effortless deployment to AWS and GitHub Pages for Next.js apps 🚀

Table of Contents

Getting Started

Make sure your environment is configured to deploy.

  • yarn add --dev next-deploy
  • yarn next-deploy

Or as a one-liner:

  • npx next-deploy

You can safely add the .next-deploy and .next-deploy-build directories to your .gitignore.

Features

Next Deploy strives to support the latest

  • ✔ effortless deployment to AWS and GitHub pages
  • ✔ deployments to a custom domain
  • ✔ static generation (SSG), server side rendering (SSR)
  • ✔ serverless AWS architecture serving your Next.js content globally via CloudFront and Lambda@Edge
  • ✔ multi-environment support
  • ⚠ getStaticPaths with fallback
  • ⚠ preview mode
  • ⚠ incremental static regeneration

Background

Next Deploy was created to deploy web applications built using the wonderful Next.js framework. It allows teams to easily integrate with the supported engines (AWS, GitHub Pages) and keep the entirety of their code in source control. From frontend, to backend, to the deployment logic. Next Deploy started as a fork of serverless-next.js which itself is an orchestrator of various orphaned serverless-components.

CLI

Next Deploy comes with a next-deploy [argument] CLI that you can run with npx next-deploy or yarn next-deploy.

There are currently 5 supported arguments:

  • default (default): Runs Build followed by Deploy.

  • init: Creates the base next-deploy.config.js configuration for your project.

  • build: Build the application for deployment.

  • deploy: Deploy the built application.

  • remove: Remove the deployed resources. Note that some resources (such as lambda@edge lambdas need to be cleaned up manually due to a timing constraint).

Distributed Deployments

Note how build and deploy can be run separately through the CLI. This allows for creating build artifacts that could be deployed at a later time. You may want to publish such build artifacts to your private artifactory for later retrieval (can be useful for rollbacks) and/or analysis. Consider publishing with the following config in your package.json:

"files": [
    ".next/!(cache)", // not needed for deployment and is very large in size
    ".next-deploy",
    ".next-deploy-build",
    "next-deploy.config.js"
  ]

Environment

AWS

To deploy to AWS you will need to set your credentials in your environment:

AWS_ACCESS_KEY_ID=******
AWS_SECRET_ACCESS_KEY=******

If your account is restricted, ensure that you have enough permissions to deploy. You will need the following permissions:

[
  'acm:DescribeCertificate', // only for custom domains
  'acm:ListCertificates', // only for custom domains
  'acm:RequestCertificate', // only for custom domains
  'cloudfront:CreateCloudFrontOriginAccessIdentity',
  'cloudfront:CreateDistribution',
  'cloudfront:CreateInvalidation',
  'cloudfront:GetDistribution',
  'cloudfront:GetDistributionConfig',
  'cloudfront:ListCloudFrontOriginAccessIdentities',
  'cloudfront:ListDistributions',
  'cloudfront:ListDistributionsByLambdaFunction',
  'cloudfront:ListDistributionsByWebACLId',
  'cloudfront:ListFieldLevelEncryptionConfigs',
  'cloudfront:ListFieldLevelEncryptionProfiles',
  'cloudfront:ListInvalidations',
  'cloudfront:ListPublicKeys',
  'cloudfront:ListStreamingDistributions',
  'cloudfront:UpdateDistribution',
  'iam:AttachRolePolicy',
  'iam:CreateRole',
  'iam:CreateServiceLinkedRole',
  'iam:GetRole',
  'iam:PassRole',
  'lambda:CreateFunction',
  'lambda:EnableReplication',
  'lambda:DeleteFunction', // only for custom domains
  'lambda:GetFunction',
  'lambda:GetFunctionConfiguration',
  'lambda:PublishVersion',
  'lambda:UpdateFunctionCode',
  'lambda:UpdateFunctionConfiguration',
  'route53:ChangeResourceRecordSets', // only for custom domains
  'route53:ListHostedZonesByName',
  'route53:ListResourceRecordSets', // only for custom domains
  's3:CreateBucket',
  's3:GetAccelerateConfiguration',
  's3:GetObject',
  's3:HeadBucket',
  's3:ListBucket',
  's3:PutAccelerateConfiguration',
  's3:PutBucketPolicy',
  's3:PutObject',
];

GitHub

No specific environment configuration is necessary. By default, your app will be built and exported to the gh-pages branch.

Configuration Options

The next-deploy config varies by the provider (engine) that you're deploying to. All configuration options are optional and come with sensible defaults. The deployment configuration is to be provided through next-deploy.config.js, which will be automatically created for you the first time you run next-deploy or next-deploy init.

Base Options

All engines support the basic options:

NameTypeDefaultDescription
buildBuild{}Build related options.
debugbooleanfalsePrint helpful messages to
domainstring \| string[]nullThe deployment domain.
engine"aws" \| "github"awsThe platform to deploy to.
nextConfigDirstring./The directory holding the next.config.js.
onPostDeploy() => Promise<void>nullA callback that gets called after the deployment successfully finishes.
onPreDeploy() => Promise<void>nullA callback that gets called before the deployment.
onShutdown() => Promise<void>nullA callback that gets called after the deployment is shutdown by a INT/QUIT/TERM signal like from ctrl+c.
stageStagelocalConfigure the stage ('dev', 'staging', 'production') of your deployment that will be used to synchronize its deployed state to an S3 bucket.

Build

NameTypeDefaultDescription
argsstring[]['build']A list of arguments to provide to the build command.
cmdstringnode_modules/.bin/nextThe build command.
cwdstring./The current working directory.

Stage

NameTypeDefaultDescription
bucketNamestringnext-deploy-environmentsThe S3 bucket name to sync the deployment stage to. local deployments don't get synced.
namestringlocalThe name of the stage.
versionedbooleanfalseWhether the S3 bucket containing the stage's state should be versioned.

AWS Options

NameTypeDefaultDescription
bucketNamestring*auto generated*Custom bucket name where static assets are stored.
bucketRegionstringus-east-1Region where you want to host your S3 bucket.
cloudfrontCloudFront{}Additional cloudfront options.
descriptionstring"*lambda type* handler for the Next CloudFront distribution."A description of the lambda.
domainType"www" \| "apex" \| "both"bothCan be one of: "apex" - apex domain only, don't create a www subdomain. "www" - www domain only, don't create an apex subdomain. "both" - create both www and apex domains when either one is provided.
memorynumber512The amount of memory that a lambda has access to. Increasing the lambda's memory also increases its CPU allocation. The value must be a multiple of 64 MB.
namestring*auto generated*The name of the lambda function.
policystringarn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRoleThe arn policy of the lambda.
publicDirectoryCacheboolean \|PublicDirectoryCachetrueCustomize the public/static directory asset caching policy. Assigning an object lets you customize the caching policy and the types of files being cached. Assigning false disables caching.
runtimestringnodejs12.xThe identifier of the lambda's runtime.
timeoutnumber10The amount of time that the lambda allows a function to run before stopping it. The maximum allowed value is 900 seconds.

Github Options

NameTypeDefaultDescription
publishPublish{message: "Next Deployment Update", dotfiles: true}The git-hub page options to publish with.

PublicDirectoryCache

NameTypeDefaultDescription
teststring/\.(gif\|jpe?g\|jp2\|tiff\|png\|webp\|bmp\|svg\|ico)$/iThe test to apply the caching behaviour.
valuestringpublic, max-age=31536000, must-revalidateThe caching behavior.

CloudFront

NameTypeDefaultDescription
fieldLevelEncryptionIdstring""The value of the ID for the field-level encryption configuration that you want to use.
forwardForward{}Determines the forwarding configuration
smoothStreamingbooleanfalseIndicates whether you want to distribute media files in the Microsoft Smooth Streaming format.
priceClass"PriceClass_All" \| "PriceClass_200" \| "PriceClass_100"PriceClass_AllTHe price class which determines the reach of the edge locations that will be used to serve your app.
ttlnumber0The amount of time that you want objects to stay in CloudFront's cache before it forwards another request to determine whether the object has been updated.
viewerCertificateViewerCertificate{}Determines the SSL/TLS configuration for communicating with viewers.
viewerProtocolPolicystringredirect-to-httpsThe policy for viewers to access the content.
"lambda@edge"LambdaAtEdge{}Additional lambda@edge functions.

Forward

NameTypeDefaultDescription
cookiesstring \| string[]allIndicates which cookies should be forwarded.
queryStringbooleantrueIndicates whether the query string should be forwarded.
headersstring[][]Headers to forward (whitelisted headers).
queryStringCacheKeysstring[][]Details of the query string parameters that you want to use for caching.

ViewerCertificate

NameTypeDefaultDescription
ACMCertificateArnstringnullIf the SSL/TLS certificate is stored in ACM, provide the ARN of the ACM certificate. CloudFront only supports ACM certificates in the us-east-1.
SSLSupportMethodstringsni-onlySpecifies which viewers the distribution accepts HTTPS connections from. sni-only – The distribution accepts HTTPS connections only from viewers that support server SNI (all modern browsers). vip – The distribution accepts HTTPS connections from all (not recommended and results in additional monthly charges).
minimumProtocolVersionstringTLSv1.2_2019The security policy that you want to use for HTTPS connections with viewers.

LambdaAtEdge

NameTypeDefaultDescription
*cloudfront event*string \| {arn:string,includeBody:boolean}nullThe customization for a new CloudFront event handler (lambda function).

Advanced Usage

Redirecting Domains

For AWS deployments, when using the domainType option with either apex or domain values, the automatic redirection from the unsupported domain type will not automatically work, but there are manual one time steps you outlined here. In summary, you will have to create a new S3 bucket and set it up with static website hosting to redirect requests to your supported subdomain type (ex. "www.example.com" or "example.com"). To be able to support HTTPS redirects, you'll need to set up a CloudFront distribution with the S3 redirect bucket as the origin. Finally, you'll need to create an "A" record in Route 53 with your newly created CloudFront distribution as the alias target.

Deployment State

For AWS deployments, Next Deploy must know the state of your previous deployment, otherwise it will start spinning up new instances. You may find the local state files in your .next-deploy directory.

When working on a team or trying to implement CI/CD it is advisable to persist the deployment state for each stage using the stage AWS option. Alternatively, one may backup and restore the deployment state by using the onPreDeploy and onPostDeploy callbacks.

CI/CD

Implement CI/CD in your workflow with Next Deploy by substituting environment variables into your next-deploy.config.js.

Consider an advanced configuration example:

module.exports = {
  bucketName: process.env.MY_APP_BUCKET_NAME,
  description: process.env.MY_APP_LAMBDA_DESCRIPTION,
  name: {
    requestLambda: process.env.MY_APP_REQUEST_LAMBDA_NAME,
  },
  domain: [process.env.MY_APP_SUBDOMAIN, process.env.MY_APP_DOMAIN],
  stage: {
    name: process.env.ENVIRONMENT,
    versioned: true,
    bucketName: 'next-environments',
  },
  cloudfront: {
    defaults: {
      'lambda@edge': {
        'viewer-request': process.env.MY_AUTH_LAMBDA_ARN,
      },
    },
  },
  debug: true,
};

The most important configuration option in the example above is stage. It will allow for the deployment state to be persisted in S3 and it will be synced with the locale state at the start of every build.

While implementing CI/CD in your project, consider following the latest Next.js guidelines for storing and loading the environment variables in .env* files.

Examples

Check out the two examples for AWS and GitHub in the examples folder to get a sense of what the implementation will entail and how it will run when deployed.

1.2.4

3 years ago

1.2.3

4 years ago

1.2.2

4 years ago

1.2.1

4 years ago

1.2.0

4 years ago

1.1.1

4 years ago

1.1.0

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago

1.0.0-alpha.1

4 years ago

1.0.0-alpha.0

4 years ago

0.3.1

4 years ago

0.3.0

4 years ago

0.2.0-alpha-7

4 years ago

0.2.0-alpha-11

4 years ago

0.2.0-alpha-6

4 years ago

0.2.0-alpha-10

4 years ago

0.2.0-alpha-9

4 years ago

0.2.0-alpha-8

4 years ago

0.2.1

4 years ago

0.2.0

4 years ago

0.2.0-alpha-5

4 years ago

0.2.0-alpha-4

4 years ago

0.2.0-alpha-3

4 years ago

0.2.0-alpha-2

4 years ago

0.2.0-alpha-1

4 years ago

0.2.0-alpha-0

4 years ago

0.1.2

4 years ago

0.1.1

4 years ago

0.1.0

4 years ago

0.0.9

4 years ago

0.0.8

4 years ago

0.0.7

4 years ago

0.0.6

4 years ago

0.0.5

4 years ago

0.0.4

4 years ago

0.0.3

4 years ago

0.0.2

4 years ago

0.0.1

4 years ago