Deploying a serverless site to production is a key milestone in any project. GitHub Actions lets you automate this process to trigger on specific events, such as merging into the main
branch. Here's how to create a GitHub Actions workflow to deploy a Next.js-based serverless site to production and set up the necessary keys for authentication and environment variables.
Prerequisites
- A GitHub repository.
- A serverless framework (like SST).
- Credentials to access your AWS environment.
Setting Up GitHub Actions
GitHub Actions allows you to automate tasks directly from your GitHub repository. To deploy your serverless site when changes are merged into the main
branch, create a new workflow in your GitHub repository.
- Location: Workflow files must be in the
.github/workflows
directory, this should be in the root of the repository. Create it if it doesn't exist. - File Name: Name your workflow something like
deploy.yml
. - Workflow Trigger: Configure the workflow to trigger on a push to the
main
branch. Other triggers are available, such as pull requests or tags.
name: Deploy to Production
on:
push:
branches:
- main
jobs:
deploy:
name: Deploy to Prod
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v3
- name: Set up Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
- name: Install PNPM
run: npm install -g pnpm
- name: Install Dependencies
run: pnpm install
- name: Deploy to Production
env:
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
run: pnpm sst deploy --stage=prod
Setting Up AWS Access Keys
To deploy to AWS, you need access keys for authentication. If you don't have these keys, create them as follows:
Create an IAM User: Go to IAM in the AWS Management Console and create a new user with programmatic access. Set Permissions: Attach appropriate permissions or a policy (like AdministratorAccess). Get Access Keys: AWS will provide an Access Key ID and a Secret Access Key.
Adding Secrets to GitHub
Once you have your AWS keys, add them to GitHub Actions secrets for secure handling.
Open Your GitHub Repository: Go to your GitHub repository. Settings > Secrets > Actions: Navigate here to add new secrets. Add Secrets: Add the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY values from AWS. Name them correctly for the workflow to use.
Conclusion
With this GitHub Actions workflow and proper setup of secrets, you can automate deploying your serverless site to production when you merge into the main branch. This automation ensures a consistent and reliable deployment process, reducing manual effort and potential errors.
Test this setup in a non-production environment before deploying to production to ensure smooth operation. Happy deploying!