Search code examples
github-actionsgithub-actions-self-hosted-runners

Environment Secrets in Next.js with actions-runner and GitHub Actions


I deployed a Next.js app to a VPS with action-runners using GitHub Actions. Howver, I discovered that secrets not prefixed with NEXT_PUBLIC are not being picked up in the app. Only variables prefixed with NEXT_PUBLIC are picked up in production.

Below is my workflow:

name: Node.js CI

on:
  push:
    branches: [ "production" ]
jobs:
  build:

    runs-on: self-hosted
    environment: production
    strategy:
      matrix:
        node-version: [16.20.2]
    env:
      NEXT_PUBLIC_BASE_URL:  ${{secrets.NEXT_PUBLIC_BASE_URL}}
      NEXT_PUBLIC_COMMENT_URL: ${{secrets.NEXT_PUBLIC_COMMENT_URL}}
      NEXT_PUBLIC_COMMENT_LIST_URL: ${{secrets.NEXT_PUBLIC_COMMENT_LIST_URL}}
      NEXT_PUBLIC_WEBINAR_REGISTER_URL: ${{secrets.NEXT_PUBLIC_WEBINAR_REGISTER_URL}}
      
      #These secrets are not picked up:

      GOOGLE_CLIENT_ID: ${{secrets.GOOGLE_CLIENT_ID}}
      GOOGLE_CLIENT_SECRET: ${{secrets.GOOGLE_CLIENT_SECRET}}
      NEXTAUTH_URL: ${{secrets.NEXTAUTH_URL}}
      SECRET: ${{secrets.SECRET}}
    steps:
    - uses: actions/checkout@v3
    - name: Use Node.js ${{ matrix.node-version }}
      uses: actions/setup-node@v3
      with:
        node-version: ${{ matrix.node-version }}
        cache: 'npm'       
    - run: npm ci
    - run: npm run build --if-present
    - name: Switch to the Project Directory
      run: cd /home/xxxxx/actions-runner/_work/yyyy/yyyy
    - run: pm2 restart 1


Solution

  • After struggling for a few hours, I was able to edit my workflow file this way and it worked:

    name: Node.js CI
    
    on:
      push:
        branches: [ "production" ]
    jobs:
      build:
    
        runs-on: self-hosted
        environment: Production
        strategy:
          matrix:
            node-version: [16.20.2]
        env: # Env variables needed during build
          NEXT_PUBLIC_BASE_URL:  ${{secrets.NEXT_PUBLIC_BASE_URL}}
          NEXT_PUBLIC_COMMENT_URL: ${{secrets.NEXT_PUBLIC_COMMENT_URL}}
          NEXT_PUBLIC_COMMENT_LIST_URL: ${{secrets.NEXT_PUBLIC_COMMENT_LIST_URL}}
        steps:
        - uses: actions/checkout@v3
        - name: Use Node.js ${{ matrix.node-version }}
          uses: actions/setup-node@v3
          with:
            node-version: ${{ matrix.node-version }}
            cache: 'npm'
        - run: npm ci
        - run: npm run build --if-present
        - name: Set Secrets and Change Dir
          run: | # Secrets needed on the server
            echo "SECRET=${{secrets.SECRET}}" >> .env.production
            echo "GOOGLE_CLIENT_ID=${{secrets.GOOGLE_CLIENT_ID}}" >> .env.production
            echo "GOOGLE_CLIENT_SECRET=${{secrets.GOOGLE_CLIENT_SECRET}}" >> .env.production
            echo "NEXTAUTH_URL=${{secrets.NEXTAUTH_URL}}" >> .env.production
            cd /home/mumumu/actions-runner/_work/production/production
        - run: pm2 restart 1