Deploying Serverless App with Next.js 8, AWS Lambda and CircleCI — Part 2

CircleCI

Example repo

Prerequisites

Getting started

Add deploy scripts to package.json

$ sls deploy -v --stage staging // for staing
$ sls deploy -v --stage production // for production
/* package.json */{
"name": "my-app",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start",
"deploy:staging": "sls deploy --stage staging -v", // add here
"deploy:production": "sls deploy --stage production -v" // add here
},
...
}

Add Node job to the configuration

# .circleci/config.ymlversion: 2.1executors:
default:
docker:
- image: circleci/node:10.0.0
working_directory: ~/my-app
commands:
restore_yarn:
steps:
- restore_cache:
key: yarn-v1-{{ checksum "yarn.lock" }}-{{ arch }}-{{ .Branch }}
save_yarn:
steps:
- save_cache:
key: yarn-v1-{{ checksum "yarn.lock" }}-{{ arch }}-{{ .Branch }}
paths:
- ~/.cache/yarn
restore_node:
steps:
- restore_cache:
key: node-v1-{{ checksum "package.json" }}-{{ arch }}-{{ .Branch }}
save_node:
steps:
- save_cache:
key: node-v1-{{ checksum "package.json" }}-{{ arch }}-{{ .Branch }}
paths:
- node_modules
jobs:
node:
executor:
name: default
steps:
- checkout
- restore_yarn
- restore_node
- run: yarn
- save_yarn
- save_node
workflows:
build_and_deploy:
jobs:
- node
node job

Add Deploy job to the configuration

version: 2.1orbs:
aws-cli: circleci/aws-cli@0.1.13
...
jobs:
deploy:
parameters:
env:
type: enum
enum: ["production", "staging"]
aws-access-key-id:
type: env_var_name
aws-secret-access-key:
type: env_var_name
aws-region:
type: env_var_name
executor:
name: default
steps:
- checkout
- restore_yarn
- restore_node
- run: yarn
- save_yarn
- save_node
- aws-cli/install
- aws-cli/configure:
aws-access-key-id: << parameters.aws-access-key-id >>
aws-secret-access-key: << parameters.aws-secret-access-key >>
aws-region: << parameters.aws-region >>
- run: yarn deploy:<< parameters.env >>
- store_build_artifacts
...
workflows:
build_and_deploy:
jobs:
- node
# for staging
- deploy: &deploy
env: staging
aws-access-key-id: AWS_ACCESS_KEY_ID
aws-secret-access-key: AWS_SECRET_ACCESS_KEY
aws-region: AWS_DEFAULT_REGION
requires:
- node
name: deploy_staging
filters:
branches:
only: staging
tags:
ignore: /.*/
# for production
- deploy:
<<: *deploy
env: production name: deploy_production
filters:
branches:
ignore: /.*/
tags:
only: /^v.+$/
Environment Variables
$ git push origin staging -u
Staging workflow

Conclusion

Web Developer, TypeScript, React, React Native, Vue.js, Go, Swift, and Ruby on Rails https://manatoworks.me/

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store