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

Deployment on Vercel, Netlify, and other platforms

11 min read ยท
In this lesson8

After creating a Next.js application, a key stage is deploying it to the production environment. In this module, we will look at various hosting platforms that offer an optimized environment for Next.js applications, with a particular focus on Vercel - the platform created by the Next.js authors.

Deployment on Vercel

Vercel is a platform that offers the best native support for Next.js applications, as both technologies are developed by the same company. This ensures optimal support for all Next.js features, automated deployments, and a global CDN.

Project preparation

Before deploying, ensure that your project is ready for production:

  1. Checking environment variables - ensure that all environment variables are properly configured
  2. Initial optimization - run next build locally to check for potential errors
  3. Version control - ensure that your project is in a Git repository (GitHub, GitLab or Bitbucket)

Step by step: Deployment on Vercel

  1. Create an account on Vercel

    • Go to vercel.com and sign up, preferably using a GitHub/GitLab/Bitbucket account
  2. Import the project

    • After logging in, click "Add New..." > "Project"
    • Select your repository from the list
  3. Deployment configuration

    • Vercel automatically detects that the project is a Next.js application
    • You can customize the project name, deployment branch, and environment variables
    • For standard Next.js projects, the default settings are usually sufficient
  4. Deployment

    • Click "Deploy"
    • Vercel will build and deploy your application, optimizing it for production
  5. Deployment verification

    • After a successful deployment, you will receive a unique URL
    • Check your application and ensure that everything works correctly

Custom domain configuration

To configure a custom domain for your project on Vercel:

  1. Go to the project panel
  2. Select the tab "Domains"
  3. Click "Add" and enter your domain name
  4. Follow the instructions to configure the DNS records:
    • For root domains (e.g., example.com): Create an A record pointing to Vercel's IP
    • For subdomains (e.g., www.example.com): Create a CNAME record pointing to the Vercel domain

Automatic deployments and previews

One of Vercel's greatest strengths is the automatic deployment system:

  1. Automatic production deployments

    • Each push to the main branch (e.g., main) triggers an automatic deployment
  2. Preview Deployments

    • Each pull request automatically creates a unique preview environment
    • This allows testing changes before merging with the main branch
// Example of Next.js configuration optimized for Vercel
// next.config.js

module.exports = {
  // Image optimization - automatically handled by Vercel Image Optimization
  images: {
    domains: ['example.com', 'images.unsplash.com'],
  },

  // Integrated Vercel analytics
  vercelAnalytics: {
    enabled: true,
  },

  // Internationalization settings
  i18n: {
    locales: ['pl', 'en', 'de'],
    defaultLocale: 'pl',
  },
};

Advanced Vercel features

Vercel offers a range of advanced features worth using:

  1. Edge Functions - running code close to the user on Vercel's global edge network
  2. Serverless Functions - automatic conversion of API Routes into serverless functions
  3. Edge Middleware - running middleware at the network edge
  4. Edge Config - storing configuration at the edge with ultra-fast reads
  5. Analytics - built-in analytics tools
  6. Speed Insights - monitoring Core Web Vitals

Deployment on Netlify

Netlify is another popular platform that offers excellent support for Next.js applications, especially after the introduction of the Netlify Next.js Runtime feature.

Project preparation for Netlify

  1. Create the netlify.toml configuration file in the project's main directory:
# netlify.toml
[build]
  command = "npm run build"
  publish = ".next"

[[plugins]]
  package = "@netlify/plugin-nextjs"
  1. Install the Next.js plugin for Netlify:
npm install -D @netlify/plugin-nextjs
# or
yarn add -D @netlify/plugin-nextjs

Step by step: Deployment on Netlify

  1. Create an account on Netlify

  2. Import the project

    • Click "Add new site" > "Import an existing project"
    • Connect to your Git provider and select your repository
  3. Deployment configuration

    • Netlify should automatically detect the Next.js project settings
    • Make sure the build command is npm run build or yarn build
    • The publish directory should be set to .next
  4. Configure environment variables

    • Go to "Site settings" > "Build & deploy" > "Environment"
    • Add all needed environment variables
  5. Deployment

    • Click "Deploy site"

Netlify-specific features

Netlify offers a range of unique features that can be useful in Next.js projects:

  1. Netlify Functions - the equivalent of API Routes
  2. Netlify Edge Functions - similar to Next.js Middleware, but running at the edge
  3. Netlify Forms - built-in form handling without the need to create API endpoints
  4. Netlify Identity - user authentication service
// Example of using Netlify Functions with Next.js
// /netlify/functions/hello-world.js

exports.handler = async function(event, context) {
  return {
    statusCode: 200,
    body: JSON.stringify({ message: "Hello World" }),
    headers: {
      'Content-Type': 'application/json'
    }
  };
};

// Access from the Next.js application
// pages/api-example.js
import { useState, useEffect } from 'react';

export default function ApiExample() {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch('/.netlify/functions/hello-world')
      .then(res => res.json())
      .then(data => setData(data));
  }, []);

  return (
    <div>
      <h1>API Example</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}

Deployment on AWS Amplify

AWS Amplify is a service from Amazon that also offers good support for Next.js applications, especially if you already use the AWS ecosystem.

Project preparation for AWS Amplify

  1. Create the amplify.yml file in the project's main directory:
# amplify.yml
version: 1
frontend:
  phases:
    preBuild:
      commands:
        - npm ci
    build:
      commands:
        - npm run build
  artifacts:
    baseDirectory: .next
    files:
      - '**/*'
  cache:
    paths:
      - node_modules/**/*

Step by step: Deployment on AWS Amplify

  1. Create an AWS account or log in to an existing one

  2. Go to the AWS Amplify console

    • Select "Host web app"
  3. Connect the repository

    • Select a repository provider (GitHub, GitLab, BitBucket, or AWS CodeCommit repository)
    • Log in and select your repository
  4. Build settings configuration

    • Amplify should automatically detect the Next.js framework
    • You can adjust or confirm the build settings
  5. Configure environment variables

    • Add all needed environment variables in the "Environment variables" section
  6. Deployment

    • Click "Save and deploy"

Integration with AWS services

One of the main strengths of AWS Amplify is easy integration with other AWS services:

// Example: Integration with AWS Lambda and DynamoDB
// pages/api/users.js

import { DynamoDB } from 'aws-sdk';

const dynamoDB = new DynamoDB.DocumentClient();

export default async function handler(req, res) {
  if (req.method === 'GET') {
    const params = {
      TableName: process.env.DYNAMODB_TABLE_NAME,
    };

    try {
      const data = await dynamoDB.scan(params).promise();
      res.status(200).json(data.Items);
    } catch (error) {
      res.status(500).json({ error: 'Failed to fetch users' });
    }
  }
}

Deployment on Digital Ocean App Platform

Digital Ocean App Platform is another hosting option that offers good support for Next.js applications.

Step by step: Deploying on Digital Ocean

  1. Create a Digital Ocean account or log in to an existing one

  2. Go to Digital Ocean App Platform

    • Click "Create App"
  3. Select the code source

    • Connect your GitHub, GitLab repository, or choose another source
  4. Application configuration

    • Select the branch to deploy
    • Select the application type as "Web Service"
    • In the build settings, select "Next.js" as the example application
  5. Adjust the settings

    • Set the build command to npm run build or yarn build
    • Set the run command to npm start or yarn start
  6. Finalization

    • Select a pricing plan
    • Click "Launch App"

Other hosting options for Next.js

GitHub Pages with GitHub Actions

For statically generated Next.js applications, you can use GitHub Pages with GitHub Actions:

  1. Create a GitHub Actions workflow file:
# .github/workflows/deploy.yml
name: Deploy to GitHub Pages

on:
  push:
    branches: [ main ]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-node@v2
        with:
          node-version: '18'
      - name: Install dependencies
        run: npm ci
      - name: Build and export
        run: npm run build && npm run export
      - name: Deploy
        uses: peaceiris/actions-gh-pages@v3
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          publish_dir: ./out
  1. Adjust next.config.js:
// next.config.js
module.exports = {
  output: 'export',
  basePath: '/repository-name', // If the page is not on the main domain
  images: {
    unoptimized: true, // For GitHub Pages
  },
};
  1. Add a script to package.json:
{
  "scripts": {
    "export": "next export"
  }
}

Firebase Hosting

Firebase Hosting is another option, especially if you use other Firebase services:

  1. Install the Firebase CLI:
npm install -g firebase-tools
  1. Initialize the Firebase project:
firebase login
firebase init hosting
  1. Configure the firebase.json file:
{
  "hosting": {
    "public": "out",
    "ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  }
}
  1. Build and deploy the application:
npm run build
npm run export
firebase deploy

Self-hosting on your own server

If you prefer to host the application on your own server:

Node.js server

  1. Prepare the start script in package.json:
{
  "scripts": {
    "start": "next start -p $PORT"
  }
}
  1. Use PM2 to manage the process:
npm install -g pm2
pm2 start npm --name "next-app" -- start
  1. Configuring Nginx as a reverse proxy:
server {
  listen 80;
  server_name yourpage.com www.yourpage.com;

  location / {
    proxy_pass http://localhost:3000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
  }
}

Containerization with Docker

  1. Create a Dockerfile:
# Dockerfile
FROM node:24-alpine AS base

# Dependency installation stage
FROM base AS deps
WORKDIR /app
COPY package.json yarn.lock* package-lock.json* pnpm-lock.yaml* ./
RUN   if [ -f yarn.lock ]; then yarn --frozen-lockfile;   elif [ -f package-lock.json ]; then npm ci;   elif [ -f pnpm-lock.yaml ]; then yarn global add pnpm && pnpm i;   else echo "No lockfile present" && exit 1;   fi

# Build stage
FROM base AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build

# Production stage
FROM base AS runner
WORKDIR /app
ENV NODE_ENV production

RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs

COPY --from=builder /app/public ./public
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static

USER nextjs
EXPOSE 3000
ENV PORT 3000

CMD ["node", "server.js"]
  1. Configure next.config.js:
// next.config.js
module.exports = {
  output: 'standalone',
};
  1. Build and run the container:
docker build -t next-app .
docker run -p 3000:3000 next-app

Best practices

Environment variables

Manage environment variables according to Next.js best practices:

  1. Distinguish between client and server variables:

    • Variables that should be available in the browser should have the prefix NEXT_PUBLIC_
    • The remaining variables are available only in server code
  2. Environment files:

    • .env.local - variables for the local environment, not committed to the repository
    • .env.development - variables for the development environment
    • .env.production - variables for the production environment
    • .env.test - variables for the test environment

Deployment optimization

  1. Cache and CDN:

    • Configure appropriate cache headers for static resources
    • Use a CDN to speed up the delivery of static resources
  2. Compression:

    • Enable Gzip or Brotli compression on the server
  3. Core Web Vitals:

    • Monitor Web Vitals metrics after deployment
    • Use tools like Lighthouse or PageSpeed Insights
// next.config.js - production optimization
module.exports = {
  // Compression
  compress: true,

  // Image optimization
  images: {
    domains: ['images.example.com'],
    formats: ['image/avif', 'image/webp'],
  },

  // Static generator - maximum performance for ISR/SSG pages
  staticPageGenerationTimeout: 120,

  // Production optimization
  productionBrowserSourceMaps: false, // Disable source maps in production

  // webpack configuration
  webpack: (config, { dev, isServer }) => {
    // webpack optimizations...
    return config;
  },
};

Deployment automation

Consider implementing Continuous Deployment (CD) to automate the deployment process:

# GitHub Actions - deploy.yml
name: Deploy

on:
  push:
    branches: [ main ]

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

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

      - name: Install dependencies
        run: npm ci

      - name: Run tests
        run: npm test

      - name: Build project
        run: npm run build

      - name: Deploy to production
        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'

Summary

Next.js application deployment can be done in many ways, depending on the project's needs and the team's preferences:

  1. Vercel - the best native support, optimized for Next.js
  2. Netlify - strong competitor with good Next.js support and additional features
  3. AWS Amplify - good choice for users of the AWS ecosystem
  4. Digital Ocean App Platform - simple PaaS platform with good Next.js support
  5. Self-hosting - ability to have full control over the infrastructure

The choice of hosting platform should be tailored to:

  • The specifics of the project and its technical requirements
  • Budget and expected costs
  • The team's experience with the given platform
  • Needs related to scalability and performance
  • Additional services and integrations that may be needed

Regardless of the chosen platform, it's worth following best practices for managing environments, environment variables, security, and deployment automation.

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

// Demo: Deploying to Vercel, Netlify and other platforms
interface Platform {
  id: string;
  name: string;
  icon: string;
  color: string;
  features: string[];
  pricing: string;
  deployCommand: string;
  envSetup: string;
  pros: string[];
  cons: string[];
}

const platforms: Platform[] = [
  {
    id: 'vercel', name: 'Vercel', icon: 'V', color: '#000',
    features: ['Edge Functions', 'ISR', 'Analytics', 'Preview Deploys', 'Serverless'],
    pricing: 'Free tier / $20/mo Pro',
    deployCommand: 'vercel deploy --prod',
    envSetup: 'vercel env add DATABASE_URL\nvercel env add NEXTAUTH_SECRET',
    pros: ['Native Next.js support', 'Automatic CI/CD', 'Edge Network', 'Preview on every PR'],
    cons: ['Vendor lock-in', 'Costs at scale', 'Serverless limits'],
  },
  {
    id: 'netlify', name: 'Netlify', icon: 'N', color: '#00ad9f',
    features: ['Edge Functions', 'Forms', 'Identity', 'Split Testing', 'Plugins'],
    pricing: 'Free tier / $19/mo Pro',
    deployCommand: 'netlify deploy --prod',
    envSetup: 'netlify env:set DATABASE_URL "value"\nnetlify env:set NEXTAUTH_SECRET "value"',
    pros: ['Easy configuration', 'Built-in forms', 'Split testing', 'Plugin ecosystem'],
    cons: ['Slower SSR', 'Limited Next.js features', 'Build limits'],
  },
  {
    id: 'docker', name: 'Docker / VPS', icon: 'D', color: '#2496ed',
    features: ['Full control', 'Custom runtime', 'Scaling', 'No limits'],
    pricing: 'VPS from $5/mo',
    deployCommand: 'docker build -t myapp .\ndocker run -p 3000:3000 myapp',
    envSetup: '# .env.production\nDATABASE_URL=postgresql://...\nNEXTAUTH_SECRET=...',
    pros: ['Full control', 'No vendor lock-in', 'Lower costs at scale', 'Custom configuration'],
    cons: ['More work', 'DevOps knowledge required', 'No auto-scaling', 'Self-managed monitoring'],
  },
  {
    id: 'aws', name: 'AWS Amplify', icon: 'A', color: '#ff9900',
    features: ['CloudFront CDN', 'Lambda@Edge', 'DynamoDB', 'S3', 'CI/CD'],
    pricing: 'Pay-as-you-go',
    deployCommand: 'amplify push\namplify publish',
    envSetup: 'amplify add env staging\n# Configure in Amplify Console',
    pros: ['AWS ecosystem', 'Scaling', 'Multiple regions', 'Integration with other AWS services'],
    cons: ['Complexity', 'Learning curve', 'Costs hard to predict'],
  },
];

type DeployStep = 'idle' | 'building' | 'testing' | 'deploying' | 'done';

function DeploymentDemo() {
  const [selectedPlatform, setSelectedPlatform] = useState<Platform>(platforms[0]);
  const [deployStep, setDeployStep] = useState<DeployStep>('idle');
  const [showComparison, setShowComparison] = useState(false);

  const simulateDeploy = async () => {
    setDeployStep('building');
    await new Promise(r => setTimeout(r, 1500));
    setDeployStep('testing');
    await new Promise(r => setTimeout(r, 1000));
    setDeployStep('deploying');
    await new Promise(r => setTimeout(r, 2000));
    setDeployStep('done');
  };

  const stepLabels: Record<DeployStep, string> = {
    idle: 'Ready to deploy',
    building: 'Building application...',
    testing: 'Running tests...',
    deploying: 'Deploying to ' + selectedPlatform.name + '...',
    done: 'Deployed successfully!',
  };

  const stepColors: Record<DeployStep, string> = {
    idle: '#8892b0', building: '#f59e0b', testing: '#3b82f6', deploying: '#8b5cf6', done: '#10b981',
  };

  return (
    <div style={{ background: '#0f0f23', minHeight: '100vh', padding: '20px', color: '#e0e0e0', fontFamily: 'system-ui' }}>
      <h1 style={{ color: '#64ffda', marginBottom: '8px' }}>Deployment Platforms</h1>
      <p style={{ color: '#8892b0', marginBottom: '24px' }}>Deploying a Next.js application to various platforms</p>

      <div style={{ display: 'flex', gap: '12px', marginBottom: '24px', flexWrap: 'wrap' }}>
        {platforms.map(p => (
          <button key={p.id} onClick={() => { setSelectedPlatform(p); setDeployStep('idle'); }} style={{
            padding: '14px 20px', borderRadius: '12px', cursor: 'pointer', border: '2px solid',
            borderColor: selectedPlatform.id === p.id ? '#64ffda' : '#333',
            background: selectedPlatform.id === p.id ? '#1a2a3e' : '#1a1a2e', color: '#fff',
          }}>
            <div style={{ fontSize: '20px', fontWeight: 'bold', color: '#64ffda' }}>{p.icon}</div>
            <div style={{ fontSize: '14px' }}>{p.name}</div>
          </button>
        ))}
        <button onClick={() => setShowComparison(!showComparison)} style={{ padding: '14px 20px', borderRadius: '12px', background: showComparison ? '#7c3aed' : '#1a1a2e', color: '#fff', border: '1px solid #333', cursor: 'pointer', marginLeft: 'auto' }}>
          Compare
        </button>
      </div>

      {!showComparison ? (
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '20px' }}>
          <div>
            <div style={{ background: '#1a1a2e', padding: '20px', borderRadius: '12px', border: '1px solid #333', marginBottom: '16px' }}>
              <h3 style={{ color: '#64ffda', marginTop: 0 }}>{selectedPlatform.name}</h3>
              <p style={{ color: '#8892b0', fontSize: '13px' }}>Pricing: {selectedPlatform.pricing}</p>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: '6px', marginBottom: '12px' }}>
                {selectedPlatform.features.map(f => (
                  <span key={f} style={{ fontSize: '11px', padding: '3px 8px', borderRadius: '4px', background: '#333', color: '#8892b0' }}>{f}</span>
                ))}
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
                <div>
                  <strong style={{ color: '#10b981', fontSize: '13px' }}>Advantages:</strong>
                  <ul style={{ fontSize: '12px', paddingLeft: '16px', color: '#8892b0', margin: '4px 0' }}>
                    {selectedPlatform.pros.map((p, i) => <li key={i}>{p}</li>)}
                  </ul>
                </div>
                <div>
                  <strong style={{ color: '#ef4444', fontSize: '13px' }}>Cons:</strong>
                  <ul style={{ fontSize: '12px', paddingLeft: '16px', color: '#8892b0', margin: '4px 0' }}>
                    {selectedPlatform.cons.map((c, i) => <li key={i}>{c}</li>)}
                  </ul>
                </div>
              </div>
            </div>

            <div style={{ background: '#1a1a2e', padding: '16px', borderRadius: '8px', border: '1px solid #333' }}>
              <strong style={{ color: '#f59e0b', fontSize: '13px' }}>Deploy command:</strong>
              <pre style={{ fontSize: '12px', color: '#64ffda', margin: '8px 0 0', whiteSpace: 'pre-wrap' }}>{selectedPlatform.deployCommand}</pre>
            </div>
          </div>

          <div>
            <div style={{ background: '#1a1a2e', padding: '20px', borderRadius: '12px', border: '1px solid #333' }}>
              <h3 style={{ color: '#64ffda', marginTop: 0, fontSize: '16px' }}>Deploy simulation</h3>
              <div style={{ marginBottom: '16px', padding: '12px', borderRadius: '8px', background: stepColors[deployStep] + '20', border: '1px solid ' + stepColors[deployStep] }}>
                <span style={{ color: stepColors[deployStep] }}>{stepLabels[deployStep]}</span>
              </div>
              <button onClick={simulateDeploy} disabled={deployStep !== 'idle' && deployStep !== 'done'} style={{ padding: '10px 20px', borderRadius: '8px', background: '#64ffda', color: '#0f0f23', border: 'none', cursor: 'pointer', fontWeight: 'bold' }}>
                Deploy
              </button>
            </div>
          </div>
        </div>
      ) : (
        <div style={{ overflowX: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '13px' }}>
            <thead>
              <tr>{['', ...platforms.map(p => p.name)].map((h, i) => <th key={i} style={{ padding: '10px', textAlign: 'left', borderBottom: '1px solid #333', color: '#64ffda' }}>{h}</th>)}</tr>
            </thead>
            <tbody>
              {['pricing', 'features'].map(field => (
                <tr key={field}>
                  <td style={{ padding: '10px', borderBottom: '1px solid #222', color: '#8892b0' }}>{field}</td>
                  {platforms.map(p => (
                    <td key={p.id} style={{ padding: '10px', borderBottom: '1px solid #222', color: '#e0e0e0' }}>
                      {field === 'pricing' ? p.pricing : p.features.slice(0, 3).join(', ')}
                    </td>
                  ))}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

export default DeploymentDemo;

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. Vercel is:

  2. 2. Netlify offers:

These are 2 of 5 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Click in order

    Arrange the syntax of the FROM instruction in a Dockerfile

  • Code editor

    Create a Dockerfile for a Next.js app with a multi-stage build: install the dependencies and build the app in a stage based on a node image, copy only the build output into the final stage (COPY --from), set NODE_ENV=production, run the app as a non-root user (USER) and start it with CMD.

  • Horizontal ordering

    Arrange the elements in the correct order for the build and production start command:

  • Click in order

    Arrange the syntax for configuring the bundle analyzer in Next.js

  • Click in order

    Click in the correct order to arrange the Vercel CLI deploy command:

  1. QuestionVercel is:
  2. QuestionNetlify offers:
  3. QuestionDocker in the context of Next.js is used for:
  4. Click in orderSequence: FROM โ†’ node:18-alpine โ†’ AS
  5. Coding taskPractice: Create a Dockerfile for a Next.js Application
  6. Put in orderSequence: Build and Production Start in Next.js
  7. Click in orderConfiguring next.config.js with Analyzer
  8. Click in orderVercel Deploy via npx
  9. QuestionServerless functions in Next.js work:
  10. QuestionEdge functions are optimal for:

Useful articles