BetaLight theme is in beta. Some UI element may not be optimized.

Simple CI/CD Implementation of Next.js Project

Using GitHub Action, we can setup a simple CI/CD pipeline to automate the deployment of SSG website on a github page. By implementing this method, a programmer can protect their codebase or Intellectual Property (IP) by exposing only the public sites generated by the Next.js.

Pre-requisite

  1. Private repository for original codebase.
  2. Public repository for SSG files and folders to host static site on GitHub.
  3. Basic knowledge of GitHub Actions workflows.

Setting up GitHub

  1. Create a Personal access token (classic) at GitHub settings -> Developer settings -> Personal access token with repo and workflow access.
  2. In the private repository, create a Repository secret in Repository settings -> Secrets and variables -> Actions. Take note the newly created secret.
  3. Also in the private repository codebase, create a folder structure like this: .github/workflows/ and then create a yaml file in the folder. Paste the code below:
name: Next.js SSG Deployment

on:
  push:
    branches:
      - main # change this to the branch you want to trigger the GitHub action
  workflow_dispatch:

jobs:
  build:
    name: Deploy
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'

      - name: Install dependencies
        run: yarn install

      - name: Build Next.js project
        run: yarn build

      - name: Archive build artifact
        uses: actions/upload-artifact@v4
        with:
          name: nextjs-build
          path: out

      - name: Deploy to GitHub Pages
        uses: peaceiris/actions-gh-pages@v4
        with:
          personal_token: ${{ secrets.PERSONAL_ACCESS_TOKEN }} # link this to the created access token
          external_repository: github-account/github-account.github.io # change this to github repository for hosting the static page
          publish_branch: main
          publish_dir: out

Explanation: Upon a code push to the specified branch, it fetches the code, sets up an Ubuntu environment with Node.js 20, installs dependencies, builds the Next.js project, creates an artifact archive of the built website, and finally deploys the website to a designated GitHub Pages repository using a personal access token defined earlier.