Next.js course ยท Module 8: Deployment and Production

CI/CD and deployment automation

13 min read ยท
In this lesson12

In modern software development, Continuous Integration (CI) and Continuous Deployment (CD) are key practices that allow for faster and more reliable application delivery. Next.js, as a modern framework, integrates perfectly with various CI/CD tools, which allows automating the process of testing, building, and deploying applications.

What are CI/CD?

Continuous Integration (CI)

Continuous Integration is a practice where developers regularly integrate their code changes into the main branch of the repository. Each integration is automatically verified by:

  • Running unit and integration tests
  • Static code analysis (linting)
  • Checking code quality
  • Type checking (in the case of TypeScript)

CI allows early detection of errors and ensures that the code in the main branch remains stable.

Continuous Deployment (CD)

Continuous Deployment goes one step further - after successfully passing the CI stage, it automatically deploys changes to the production or test environment. The CD process includes:

  • Automatic application building
  • Deployment to a selected environment (staging, production)
  • Automatic E2E tests after deployment
  • Deployment monitoring

For Next.js applications, we can use various CI/CD tools:

  1. GitHub Actions - integrated with GitHub, offers excellent integration with the repo
  2. GitLab CI/CD - built into GitLab, allows creating CI/CD pipelines
  3. CircleCI - a popular CI/CD platform with simple configuration
  4. Jenkins - an open, extensible automation server
  5. Vercel CI/CD - native solution for Next.js applications
  6. Netlify CI/CD - an alternative with similar features
  7. Travis CI - one of the oldest CI/CD platforms

CI/CD configuration with GitHub Actions

The easiest way to implement CI/CD for a Next.js project is to use GitHub Actions if your repository is hosted on GitHub.

1. Configuring the testing workflow

Create the file .github/workflows/ci.yml in your repository:

name: CI

on:
  push:
    branches: [main, development]
  pull_request:
    branches: [main, development]

jobs:
  test:
    runs-on: ubuntu-latest

    strategy:
      matrix:
        node-version: [18.x]

    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'

      - name: Install dependencies
        run: npm ci

      - name: Lint
        run: npm run lint

      - name: Type check
        run: npm run type-check

      - name: Run tests
        run: npm test

      - name: Build
        run: npm run build

This workflow runs on every push to the main and development branches and when a Pull Request is created to these branches.

2. Vercel deployment workflow configuration

Create the file .github/workflows/deploy.yml:

name: Deploy to Production

on:
  push:
    branches: [main]

jobs:
  deploy:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v3

      - name: Deploy to Vercel
        uses: amondnet/vercel-action@v20
        with:
          vercel-token: ${{ secrets.VERCEL_TOKEN }}
          vercel-org-id: ${{ secrets.ORG_ID }}
          vercel-project-id: ${{ secrets.PROJECT_ID }}
          vercel-args: '--prod'

For this to work, you need to configure the following secrets in your repository settings:

  • VERCEL_TOKEN - Vercel API token
  • ORG_ID - Vercel organization ID
  • PROJECT_ID - Vercel project ID

3. Workflow configuration for the staging environment

name: Deploy to Staging

on:
  push:
    branches: [development]

jobs:
  deploy:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v3

      - name: Deploy to Vercel (Preview)
        uses: amondnet/vercel-action@v20
        with:
          vercel-token: ${{ secrets.VERCEL_TOKEN }}
          vercel-org-id: ${{ secrets.ORG_ID }}
          vercel-project-id: ${{ secrets.PROJECT_ID }}
          github-comment: true

CI/CD configuration with GitLab CI

If you use GitLab, you can configure CI/CD using .gitlab-ci.yml:

image: node:18-alpine

stages:
  - test
  - build
  - deploy_staging
  - deploy_production

cache:
  key: ${CI_COMMIT_REF_SLUG}
  paths:
    - node_modules/
    - .next/cache/

test:
  stage: test
  script:
    - npm ci
    - npm run lint
    - npm run type-check
    - npm test
  except:
    - tags

build:
  stage: build
  script:
    - npm ci
    - npm run build
  artifacts:
    paths:
      - .next/
  except:
    - tags

deploy_staging:
  stage: deploy_staging
  script:
    - npm install -g vercel
    - vercel --token ${VERCEL_TOKEN} --confirm
  environment:
    name: staging
    url: ${CI_PROJECT_NAME}-git-${CI_COMMIT_REF_NAME}-${CI_PROJECT_NAMESPACE}.vercel.app
  only:
    - development

deploy_production:
  stage: deploy_production
  script:
    - npm install -g vercel
    - vercel --token ${VERCEL_TOKEN} --prod --confirm
  environment:
    name: production
    url: ${CI_PROJECT_NAME}.vercel.app
  only:
    - main

CI/CD configuration for a Next.js application with CircleCI

To configure CircleCI, create the file .circleci/config.yml:

version: 2.1

orbs:
  node: circleci/node@5.0.3

jobs:
  test:
    docker:
      - image: cimg/node:18.15.0
    steps:
      - checkout
      - node/install-packages:
          pkg-manager: npm
      - run:
          name: Run tests
          command: npm test
      - run:
          name: Run linter
          command: npm run lint
      - run:
          name: Check types
          command: npm run type-check

  build:
    docker:
      - image: cimg/node:18.15.0
    steps:
      - checkout
      - node/install-packages:
          pkg-manager: npm
      - run:
          name: Build application
          command: npm run build
      - persist_to_workspace:
          root: .
          paths:
            - .next
            - node_modules
            - package.json

  deploy-staging:
    docker:
      - image: cimg/node:18.15.0
    steps:
      - checkout
      - attach_workspace:
          at: .
      - run:
          name: Install Vercel CLI
          command: npm install -g vercel
      - run:
          name: Deploy to Staging
          command: vercel --token ${VERCEL_TOKEN} --confirm

  deploy-production:
    docker:
      - image: cimg/node:18.15.0
    steps:
      - checkout
      - attach_workspace:
          at: .
      - run:
          name: Install Vercel CLI
          command: npm install -g vercel
      - run:
          name: Deploy to Production
          command: vercel --token ${VERCEL_TOKEN} --prod --confirm

workflows:
  version: 2
  test-build-deploy:
    jobs:
      - test
      - build:
          requires:
            - test
      - deploy-staging:
          requires:
            - build
          filters:
            branches:
              only: development
      - deploy-production:
          requires:
            - build
          filters:
            branches:
              only: main

CI/CD configuration with Jenkins

Jenkins is a powerful CI/CD tool, but requires more configuration. Here is an example Jenkinsfile for a CI/CD pipeline for a Next.js application:

pipeline {
    agent {
        docker {
            image 'node:18-alpine'
        }
    }

    stages {
        stage('Install Dependencies') {
            steps {
                sh 'npm ci'
            }
        }

        stage('Lint') {
            steps {
                sh 'npm run lint'
            }
        }

        stage('Type Check') {
            steps {
                sh 'npm run type-check'
            }
        }

        stage('Test') {
            steps {
                sh 'npm test'
            }
        }

        stage('Build') {
            steps {
                sh 'npm run build'
            }
        }

        stage('Deploy to Staging') {
            when {
                branch 'development'
            }
            steps {
                sh 'npm install -g vercel'
                sh 'vercel --token ${VERCEL_TOKEN} --confirm'
            }
        }

        stage('Deploy to Production') {
            when {
                branch 'main'
            }
            steps {
                sh 'npm install -g vercel'
                sh 'vercel --token ${VERCEL_TOKEN} --prod --confirm'
            }
        }
    }

    post {
        always {
            cleanWs()
        }
    }
}

Testing in the CI/CD process

An important element of the CI/CD process is automatic testing. For Next.js applications, we can configure different types of tests:

1. Unit tests with Jest and React Testing Library

// __tests__/components/Header.test.tsx
import { render, screen } from '@testing-library/react';
import Header from '@/components/Header';

describe('Header Component', () => {
  it('renders the logo', () => {
    render(<Header />);
    const logo = screen.getByAltText('Logo');
    expect(logo).toBeInTheDocument();
  });

  it('has the correct navigation links', () => {
    render(<Header />);
    expect(screen.getByText('Home')).toBeInTheDocument();
    expect(screen.getByText('About')).toBeInTheDocument();
    expect(screen.getByText('Contact')).toBeInTheDocument();
  });
});

2. Integration tests for API Routes

// __tests__/api/user.test.ts
import { createMocks } from 'node-mocks-http';
import userHandler from '@/app/api/user/route';

describe('/api/user endpoint', () => {
  it('returns a user when provided with a valid ID', async () => {
    const { req, res } = createMocks({
      method: 'GET',
      query: { id: '123' },
    });

    await userHandler(req, res);

    expect(res._getStatusCode()).toBe(200);
    expect(JSON.parse(res._getData())).toEqual(
      expect.objectContaining({
        id: '123',
        name: expect.any(String),
      })
    );
  });

  it('returns 404 for non-existent user', async () => {
    const { req, res } = createMocks({
      method: 'GET',
      query: { id: 'non-existent' },
    });

    await userHandler(req, res);

    expect(res._getStatusCode()).toBe(404);
  });
});

3. End-to-End tests with Cypress

// cypress/integration/navigation.spec.js
describe('Navigation', () => {
  it('should navigate to the about page', () => {
    cy.visit('/');

    cy.get('a[href*="about"]').click();

    cy.url().should('include', '/about');
    cy.get('h1').contains('About');
  });

  it('should navigate to the contact page', () => {
    cy.visit('/');

    cy.get('a[href*="contact"]').click();

    cy.url().should('include', '/contact');
    cy.get('h1').contains('Contact');
  });
});

Add Cypress configuration to GitHub Actions:

# .github/workflows/e2e-tests.yml
name: E2E Tests

on:
  deployment_status:

jobs:
  e2e-tests:
    if: github.event.deployment_status.state == 'success'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - name: Install dependencies
        run: npm ci

      - name: Cypress run
        uses: cypress-io/github-action@v5
        with:
          record: true
        env:
          CYPRESS_RECORD_KEY: ${{ secrets.CYPRESS_RECORD_KEY }}
          CYPRESS_BASE_URL: ${{ github.event.deployment_status.target_url }}

Automation of development tasks

Beyond CI/CD, we can automate various other development tasks:

1. Automatic code formatting with Husky and lint-staged

Install the required packages:

npm install --save-dev husky lint-staged prettier

Update package.json:

{
  "scripts": {
    "prepare": "husky install"
  },
  "lint-staged": {
    "*.{js,jsx,ts,tsx}": [
      "prettier --write",
      "eslint --fix"
    ],
    "*.{json,md}": [
      "prettier --write"
    ]
  }
}

Create a pre-commit hook:

npx husky add .husky/pre-commit "npx lint-staged"

2. Automatic versioning with Semantic Release

Install the required packages:

npm install --save-dev semantic-release @semantic-release/git @semantic-release/changelog

Create the file .releaserc.json:

{
  "branches": ["main"],
  "plugins": [
    "@semantic-release/commit-analyzer",
    "@semantic-release/release-notes-generator",
    "@semantic-release/changelog",
    "@semantic-release/npm",
    ["@semantic-release/git", {
      "assets": ["package.json", "CHANGELOG.md"],
      "message": "chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}"
    }],
    "@semantic-release/github"
  ]
}

Add a workflow for semantic-release:

# .github/workflows/release.yml
name: Release

on:
  push:
    branches: [main]

jobs:
  release:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '18'
          cache: 'npm'
      - name: Install dependencies
        run: npm ci
      - name: Release
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
        run: npx semantic-release

3. Automatic documentation generation

For TypeScript projects, you can automate documentation generation:

# .github/workflows/docs.yml
name: Generate Documentation

on:
  push:
    branches: [main]

jobs:
  docs:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '18'
          cache: 'npm'
      - name: Install dependencies
        run: npm ci
      - name: Generate docs
        run: npx typedoc --out docs src
      - name: Deploy docs to GitHub Pages
        uses: peaceiris/actions-gh-pages@v3
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          publish_dir: ./docs

Deployment and rollback strategies

When deploying applications, it's worth implementing safe deployment strategies:

1. Blue-Green Deployment

Blue-Green deployment involves maintaining two identical production environments, of which only one is active. In the case of Vercel, you can use their built-in "Preview Deployments" feature and domain aliasing:

// scripts/blue-green-deploy.js
const { execSync } = require('child_process');

// Deploy to new environment (but not live yet)
const output = execSync('vercel --prod').toString();
const deploymentUrl = output.match(/https:\/\/[\w.-]+/)[0];

// Run smoke tests against new deployment
const smokeTestResult = execSync(`npm run test:smoke -- --url=${deploymentUrl}`).toString();

if (smokeTestResult.includes('All tests passed')) {
  // Switch traffic to new deployment
  execSync(`vercel alias set ${deploymentUrl} your-production-domain.com`);
  console.log('Successfully switched to new deployment');
} else {
  console.error('Smoke tests failed, aborting deployment');
  process.exit(1);
}

2. Canary Releases

In the Canary strategy, a new version is gradually released, initially only for a small percentage of users. In Next.js, you can achieve this using feature flags and traffic splitting:

// lib/feature-flags.ts
import { useEffect, useState } from 'react';

const CANARY_PERCENTAGE = 10; // 10% of users will get the new version

export function useCanaryFeature(featureName: string): boolean {
  const [isEnabled, setIsEnabled] = useState(false);

  useEffect(() => {
    // Generate a random number for the user and save it in local storage
    let userBucket = localStorage.getItem('userBucket');
    if (!userBucket) {
      userBucket = Math.floor(Math.random() * 100).toString();
      localStorage.setItem('userBucket', userBucket);
    }

    // Check if the user is in the canary group
    const inCanaryGroup = parseInt(userBucket) < CANARY_PERCENTAGE;

    // Check if the feature is active for this user
    fetch('/api/feature-flags')
      .then(res => res.json())
      .then(flags => {
        // If the flag exists and the user is in the canary group, enable the feature
        if (flags[featureName] && inCanaryGroup) {
          setIsEnabled(true);
        }
      });
  }, [featureName]);

  return isEnabled;
}

3. Automatic rollback

Automatic rollback deployment when issues arise is a key practice:

# .github/workflows/deploy-monitor-rollback.yml
name: Deploy, Monitor & Rollback

on:
  push:
    branches: [main]

jobs:
  deploy:
    runs-on: ubuntu-latest
    outputs:
      deployment_id: ${{ steps.deploy.outputs.deployment_id }}
    steps:
      - uses: actions/checkout@v3
      - name: Deploy to Vercel
        id: deploy
        uses: amondnet/vercel-action@v20
        with:
          vercel-token: ${{ secrets.VERCEL_TOKEN }}
          vercel-org-id: ${{ secrets.ORG_ID }}
          vercel-project-id: ${{ secrets.PROJECT_ID }}
          vercel-args: '--prod'


  monitor:
    needs: deploy
    runs-on: ubuntu-latest
    steps:
      - name: Wait for 2 minutes
        run: sleep 120

      - name: Check for errors
        id: check_errors
        run: |
          ERROR_COUNT=$(curl -s "https://api.example.com/monitoring/errors?since=$(date -u -d '2 minutes ago' +%Y-%m-%dT%H:%M:%SZ)" | jq '.count')
          echo "::set-output name=error_count::$ERROR_COUNT"
          if [ "$ERROR_COUNT" -gt "10" ]; then
            echo "Error count too high ($ERROR_COUNT). Failing job."
            exit 1
          fi

      - name: Monitor Core Web Vitals
        id: web_vitals
        run: |
          LCP=$(curl -s "https://api.example.com/monitoring/web-vitals" | jq '.lcp')
          if [ "$LCP" -gt "2500" ]; then
            echo "LCP too high ($LCP ms). Failing job."
            exit 1
          fi

  rollback:
    needs: [deploy, monitor]
    runs-on: ubuntu-latest
    if: ${{ failure() }}
    steps:
      - name: Rollback to previous deployment
        uses: amondnet/vercel-action@v20
        with:
          vercel-token: ${{ secrets.VERCEL_TOKEN }}
          vercel-org-id: ${{ secrets.ORG_ID }}
          vercel-project-id: ${{ secrets.PROJECT_ID }}
          vercel-args: '--prod --scope myorg'  # Rollback to previous deployment

Managing environment variables

Secure management of environment variables is a critical aspect of CI/CD:

1. Storing environment variables in the CI/CD system

Most CI/CD systems offer secure storage of secrets, e.g., GitHub Secrets:

# .github/workflows/deploy.yml
name: Deploy

on:
  push:
    branches: [main]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - name: Create .env file
        run: |
          cat > .env.production << EOL
          DATABASE_URL=${{ secrets.DATABASE_URL }}
          API_KEY=${{ secrets.API_KEY }}
          NEXT_PUBLIC_ANALYTICS_ID=${{ secrets.NEXT_PUBLIC_ANALYTICS_ID }}
          EOL

      - name: Deploy
        run: npm run deploy

2. Automatic rotation of secrets

For critical applications, it's worth implementing automatic rotation of secrets:

# .github/workflows/rotate-secrets.yml
name: Rotate Secrets

on:
  schedule:
    - cron: '0 0 1 * *'  # Every month

jobs:
  rotate:
    runs-on: ubuntu-latest
    steps:
      - name: Generate new API key
        id: new_key
        run: echo "::set-output name=api_key::$(openssl rand -base64 32)"

      - name: Update API service with new key
        run: |
          curl -X POST -H "Authorization: Bearer ${{ secrets.ADMIN_TOKEN }}"           -d '{"api_key": "${{ steps.new_key.outputs.api_key }}"}'           https://api.example.com/admin/update-key

      - name: Update GitHub secret
        uses: gliech/create-github-secret-action@v1
        with:
          name: API_KEY
          value: ${{ steps.new_key.outputs.api_key }}
          pa_token: ${{ secrets.PA_TOKEN }}

Deployment monitoring

A key element of the CI/CD process is deployment monitoring to quickly detect and respond to potential problems:

1. Integration with monitoring services

# .github/workflows/deploy-and-monitor.yml
name: Deploy and Monitor

on:
  push:
    branches: [main]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Deploy to Vercel
        uses: amondnet/vercel-action@v20
        with:
          vercel-token: ${{ secrets.VERCEL_TOKEN }}
          vercel-org-id: ${{ secrets.ORG_ID }}
          vercel-project-id: ${{ secrets.PROJECT_ID }}
          vercel-args: '--prod'

      - name: Notify Datadog of deployment
        run: |
          curl -X POST "https://api.datadoghq.com/api/v1/events"           -H "Content-Type: application/json"           -H "DD-API-KEY: ${{ secrets.DATADOG_API_KEY }}"           -d '{"title":"Deployment to production","text":"Deployed commit ${{ github.sha }} to production","tags":["environment:production","team:frontend"],"alert_type":"info"}'

2. Automatic post-deployment tests

# .github/workflows/post-deploy-tests.yml
name: Post-deployment Tests

on:
  deployment_status:

jobs:
  smoke-tests:
    if: github.event.deployment_status.state == 'success'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - name: Run smoke tests
        run: |
          npm ci
          npm run test:smoke -- --url=${{ github.event.deployment_status.target_url }}

      - name: Post results to Slack
        if: always()
        uses: slackapi/slack-github-action@v1
        with:
          payload: |
            {
              "text": "Smoke test results: ${{ job.status }}\nDeployment URL: ${{ github.event.deployment_status.target_url }}"
            }
        env:
          SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}

Summary

Implementing CI/CD for Next.js applications is a key element of the modern software development process that brings many benefits:

  1. Faster deployment of changes - process automation reduces the time needed to deliver new features
  2. Higher code quality - automatic tests and code analysis ensure higher quality
  3. Lower risk of errors - automation eliminates human errors
  4. Faster feedback - developers receive immediate feedback on code quality
  5. Increased productivity - developers focus on feature development, not on manual processes

A properly configured CI/CD pipeline is an investment that pays off in time savings, higher code quality, and more reliable deployments. Regardless of the chosen platform (GitHub Actions, GitLab CI, CircleCI, Jenkins), the key is to adapt the process to the specific needs of the project and team.

Code for this lesson: App.tsx
import React, { useState } from 'react';

// Demo: CI/CD and deployment automation
interface PipelineStage {
  id: string;
  name: string;
  icon: string;
  status: 'pending' | 'running' | 'success' | 'failed' | 'skipped';
  duration?: number;
  steps: string[];
}

function CICDDemo() {
  const [stages, setStages] = useState<PipelineStage[]>([
    { id: 'install', name: 'Install', icon: 'I', status: 'pending', steps: ['npm ci', 'Cache dependencies'] },
    { id: 'lint', name: 'Lint', icon: 'L', status: 'pending', steps: ['ESLint', 'Prettier check', 'TypeScript check'] },
    { id: 'test', name: 'Test', icon: 'T', status: 'pending', steps: ['Unit tests', 'Integration tests', 'Coverage report'] },
    { id: 'build', name: 'Build', icon: 'B', status: 'pending', steps: ['next build', 'Bundle analysis', 'Optimize assets'] },
    { id: 'deploy', name: 'Deploy', icon: 'D', status: 'pending', steps: ['Deploy to staging', 'Health check', 'Promote to production'] },
  ]);
  const [activeProvider, setActiveProvider] = useState<'github' | 'gitlab' | 'vercel'>('github');
  const [isRunning, setIsRunning] = useState(false);
  const [failAt, setFailAt] = useState<string>('none');

  const statusColors: Record<string, string> = {
    pending: '#64748b', running: '#f59e0b', success: '#10b981', failed: '#ef4444', skipped: '#8892b0',
  };

  const statusIcons: Record<string, string> = {
    pending: 'o', running: '~', success: 'V', failed: 'X', skipped: '-',
  };

  const runPipeline = async () => {
    setIsRunning(true);
    setStages(prev => prev.map(s => ({ ...s, status: 'pending', duration: undefined })));

    for (let i = 0; i < stages.length; i++) {
      const stage = stages[i];

      setStages(prev => prev.map((s, idx) => idx === i ? { ...s, status: 'running' } : s));

      const duration = Math.floor(Math.random() * 3000) + 1000;
      await new Promise(r => setTimeout(r, duration));

      if (failAt === stage.id) {
        setStages(prev => prev.map((s, idx) =>
          idx === i ? { ...s, status: 'failed', duration } :
          idx > i ? { ...s, status: 'skipped' } : s
        ));
        setIsRunning(false);
        return;
      }

      setStages(prev => prev.map((s, idx) => idx === i ? { ...s, status: 'success', duration } : s));
    }

    setIsRunning(false);
  };

  const ciConfigs: Record<string, string> = {
    github: "# .github/workflows/deploy.yml\nname: Deploy\non:\n  push:\n    branches: [main]\n\njobs:\n  deploy:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v4\n      - uses: actions/setup-node@v4\n      - run: npm ci\n      - run: npm run lint\n      - run: npm run test\n      - run: npm run build\n      - run: npx vercel --prod",
    gitlab: "# .gitlab-ci.yml\nstages:\n  - install\n  - lint\n  - test\n  - build\n  - deploy\n\ninstall:\n  stage: install\n  script: npm ci\n  cache:\n    paths: [node_modules/]\n\ntest:\n  stage: test\n  script: npm run test\n\nbuild:\n  stage: build\n  script: npm run build",
    vercel: "// vercel.json\n{\n  \"buildCommand\": \"npm run build\",\n  \"devCommand\": \"npm run dev\",\n  \"installCommand\": \"npm ci\",\n  \"framework\": \"nextjs\",\n  \"github\": {\n    \"autoAlias\": true,\n    \"silent\": true\n  }\n}",
  };

  return (
    <div style={{ background: '#0f0f23', minHeight: '100vh', padding: '20px', color: '#e0e0e0', fontFamily: 'system-ui' }}>
      <h1 style={{ color: '#64ffda', marginBottom: '8px' }}>CI/CD Pipeline</h1>
      <p style={{ color: '#8892b0', marginBottom: '24px' }}>Automation of Next.js application deployments</p>

      <div style={{ display: 'flex', gap: '8px', marginBottom: '20px' }}>
        {[
          { id: 'github' as const, label: 'GitHub Actions' },
          { id: 'gitlab' as const, label: 'GitLab CI' },
          { id: 'vercel' as const, label: 'Vercel' },
        ].map(p => (
          <button key={p.id} onClick={() => setActiveProvider(p.id)} style={{
            padding: '8px 16px', borderRadius: '8px', border: 'none', cursor: 'pointer',
            background: activeProvider === p.id ? '#64ffda' : '#1a1a2e', color: activeProvider === p.id ? '#0f0f23' : '#8892b0', fontWeight: 'bold',
          }}>{p.label}</button>
        ))}
      </div>

      <div style={{ background: '#1a1a2e', padding: '20px', borderRadius: '12px', border: '1px solid #333', marginBottom: '24px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px' }}>
          <h3 style={{ color: '#64ffda', margin: 0 }}>Pipeline Stages</h3>
          <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
            <select value={failAt} onChange={e => setFailAt(e.target.value)} style={{ padding: '6px 10px', borderRadius: '6px', background: '#0f0f23', color: '#fff', border: '1px solid #333', fontSize: '12px' }}>
              <option value="none">No failure</option>
              {stages.map(s => <option key={s.id} value={s.id}>Fail at {s.name}</option>)}
            </select>
            <button onClick={runPipeline} disabled={isRunning} style={{ padding: '8px 16px', borderRadius: '6px', background: isRunning ? '#333' : '#64ffda', color: '#0f0f23', border: 'none', cursor: isRunning ? 'default' : 'pointer', fontWeight: 'bold' }}>
              {isRunning ? 'Running...' : 'Run Pipeline'}
            </button>
          </div>
        </div>

        <div style={{ display: 'flex', gap: '16px', alignItems: 'flex-start', flexWrap: 'wrap' }}>
          {stages.map((stage, i) => (
            <React.Fragment key={stage.id}>
              <div style={{ textAlign: 'center', minWidth: '120px' }}>
                <div style={{
                  width: '50px', height: '50px', borderRadius: '50%', margin: '0 auto 8px',
                  border: '3px solid ' + statusColors[stage.status],
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  background: stage.status === 'running' ? statusColors[stage.status] + '30' : 'transparent',
                  fontSize: '18px', fontWeight: 'bold', color: statusColors[stage.status],
                }}>
                  {statusIcons[stage.status]}
                </div>
                <div style={{ fontWeight: 'bold', fontSize: '14px', color: statusColors[stage.status] }}>{stage.name}</div>
                {stage.duration && <div style={{ fontSize: '11px', color: '#8892b0' }}>{(stage.duration / 1000).toFixed(1)}s</div>}
                <div style={{ marginTop: '8px' }}>
                  {stage.steps.map((step, j) => (
                    <div key={j} style={{ fontSize: '11px', color: '#555', padding: '1px 0' }}>{step}</div>
                  ))}
                </div>
              </div>
              {i < stages.length - 1 && <div style={{ paddingTop: '20px', color: '#333', fontSize: '20px' }}>-&gt;</div>}
            </React.Fragment>
          ))}
        </div>
      </div>

      <div style={{ background: '#1a1a2e', padding: '16px', borderRadius: '8px', border: '1px solid #333' }}>
        <h3 style={{ color: '#f59e0b', fontSize: '14px', marginTop: 0 }}>Configuration ({activeProvider}):</h3>
        <pre style={{ fontSize: '12px', color: '#e0e0e0', margin: 0, overflow: 'auto', whiteSpace: 'pre-wrap' }}>{ciConfigs[activeProvider]}</pre>
      </div>
    </div>
  );
}

export default CICDDemo;

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. CI/CD stands for:

  2. 2. What is the difference between Continuous Delivery and Continuous Deployment?

Hands-on tasks in the game

  • Code editor

    Create a GitHub Actions workflow that runs on push to the main branch: checkout, setup-node, install the dependencies, run the tests, build, and finally deploy to Vercel with the token from the VERCEL_TOKEN secret.

  • Vertical ordering

    Arrange the elements in the correct order: Code push โ†’ Run tests โ†’ Build app

  • Vertical ordering

    Arrange the GitHub Actions workflow trigger configuration syntax:

  • Code editor

    Create a health check API endpoint with database connectivity, external services status, and system metrics

  1. QuestionCI/CD stands for:
  2. Coding taskPractice: Create a GitHub Actions Workflow for Automated Deployment
  3. Put in orderSequence: Code push โ†’ Run tests โ†’ Build app
  4. QuestionContinuous Delivery vs Continuous Deployment
  5. Put in orderGitHub Actions Workflow Trigger Syntax
  6. Coding taskPractice: Create a Health Check API Endpoint

Useful articles