Next.js course Β· Module 8: Deployment and Production

Preparing the application for production (build, analyze)

6 min read Β·
In this lesson6

Preparing a Next.js application for production deployment is a crucial stage of the development process that requires special attention to optimization, analysis, and configuration. A properly prepared application will provide a better user experience, higher performance, and easier maintenance.

The Next.js application build process

The build process in Next.js transforms source code into an optimized version ready for deployment. During this process, Next.js:

  1. Compiles React and TypeScript code into JavaScript
  2. Minifies CSS and JavaScript code
  3. Optimizes images
  4. Pre-renders static routes at build time (Static Site Generation for routes without dynamic data)
  5. Prepares Server Components and route handlers to render on the server (Server-Side Rendering)
  6. Creates the files needed for client-side navigation

Basic build process

To build a Next.js application, follow these steps:

# First, make sure all dependencies are installed
npm install

# Then build the application
npm run build

After the build process completes, Next.js will display a summary of pages, their types (static, SSR, API), and the size of each page. This summary provides valuable information about application performance.

Running the built application

After successfully building the application, you can run the production version locally using:

npm run start

This command starts a Node.js server that serves your Next.js application in production mode, without hot-reloading and with optimized assets.

Bundle analysis

Bundle size analysis is essential to understand exactly what affects your application's size. Next.js offers a built-in bundle analysis tool that can be enabled using an environment variable:

ANALYZE=true npm run build

To use this feature, you need to install and configure the tool @next/bundle-analyzer:

npm install --save-dev @next/bundle-analyzer

Then update the file next.config.js:

const withBundleAnalyzer = require('@next/bundle-analyzer')({
  enabled: process.env.ANALYZE === 'true',
})

module.exports = withBundleAnalyzer({
  // Place other Next.js configuration options here
})

After running the build with the analyzer enabled, visual reports will be generated showing a detailed breakdown of client and server bundle sizes.

Interpreting bundle analysis results

Bundle analysis reveals:

  1. Large dependencies - libraries that significantly affect bundle size
  2. Duplicates - the same packages loaded multiple times
  3. Unused code - dead code that can be removed
  4. Module distribution - which parts of the application take up the most space

Based on this information, you can make informed optimization decisions:

  • Replace large libraries with lighter alternatives
  • Implement lazy loading for large components
  • Remove unused dependencies
  • Split code into smaller chunks

Performance optimization

Code splitting

Next.js automatically implements code splitting, but you can further optimize this process using dynamic imports:

import dynamic from 'next/dynamic';

// Instead of importing directly
// import HeavyComponent from '../components/HeavyComponent';

// Use dynamic import
const HeavyComponent = dynamic(() => import('../components/HeavyComponent'), {
  loading: () => <p>Loading...</p>,
  // SSR can be disabled for components that are not needed on the server
  ssr: false,
});

export default function HomePage() {
  return (
    <div>
      <h1>Home page</h1>
      <HeavyComponent />
    </div>
  );
}

Image optimization

Next.js offers the component Image which automatically optimizes images, but it's worth additionally configuring the options:

import Image from 'next/image';

export default function ProductCard({ product }) {
  return (
    <div>
      <Image
        src={product.imageUrl}
        alt={product.name}
        width={300}
        height={200}
        placeholder="blur"
        blurDataURL={product.thumbnailUrl}
        priority={product.featured} // Loads image with high priority if featured
      />
      <h2>{product.name}</h2>
    </div>
  );
}

Tree shaking

Tree shaking is a technique for eliminating dead code during the build process. Next.js uses Webpack, which performs tree shaking automatically. To maximize the benefits of tree shaking:

  1. Use ES Module imports instead of require
  2. Avoid side-effect imports (e.g. import 'library')
  3. Prefer named imports over default imports when you only need part of a library:
// Bad: imports the entire library
import _ from 'lodash';
const sortedItems = _.sortBy(items, 'name');

// Good: imports only the needed function
import { sortBy } from 'lodash-es';
const sortedItems = sortBy(items, 'name');

Environment variables

Next.js handles environment variables through files .env, .env.local, .env.development i .env.production. They are key for configuring the application in different environments.

# .env.production
NEXT_PUBLIC_API_URL=https://api.yourdomain.com
DATABASE_URL=postgresql://user:password@production-db:5432/mydb
FEATURE_FLAGS_ENABLED=true

Variables prefixed with NEXT_PUBLIC_ are available in the browser, while the rest are visible only on the server.

Secure secrets management

For production secrets:

  1. Never store secrets in the repository
  2. Use the hosting platform's secrets management (Vercel, Netlify)
  3. For sensitive operations, prefer server-side code (API Routes)
// pages/api/secure-operation.ts
export default async function handler(req, res) {
  // API_SECRET is not accessible in client code
  const apiSecret = process.env.API_SECRET;

  // Securely perform the operation with the secret
  const result = await performSecureOperation(apiSecret);

  // Return only safe data
  res.status(200).json({ success: true, data: result.safeData });
}

Production testing

Before deployment, run production version tests:

  1. Performance tests - use Lighthouse or WebPageTest
  2. Functional tests - check that all features work as expected
  3. Responsiveness tests - check different screen sizes
  4. Browser tests - check compatibility with different browsers

Pre-production test automation

Set up a script that will run all necessary tests:

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

// Run unit tests
console.log('Running unit tests...');
execSync('npm run test', { stdio: 'inherit' });

// Run end-to-end tests
console.log('Running E2E tests...');
execSync('npm run test:e2e', { stdio: 'inherit' });

// Check types
console.log('Checking types...');
execSync('npm run typecheck', { stdio: 'inherit' });

// Check linting
console.log('Checking linting...');
execSync('npm run lint', { stdio: 'inherit' });

// Build the application
console.log('Building the application...');
execSync('npm run build', { stdio: 'inherit' });

console.log('All pre-deployment checks passed successfully!');

Summary

Preparing a Next.js application for production is a multi-step process that includes:

  1. Building an optimized version of the application
  2. Bundle analysis to identify optimization opportunities
  3. Implementing techniques to improve performance
  4. Configuring environment variables
  5. Secure secrets management
  6. Production testing

A carefully conducted production preparation process ensures better performance, security, and user experience, which translates into business success of the project.

Remember that optimization is an ongoing process - regular performance monitoring and updating the application according to new best practices is the key to maintaining a performant application.

Code for this lesson: App.tsx
// Demo: Preparing Next.js application for production
// Build process, optimization, deployment checklist
import React, { useState } from 'react';

// Next.js build process:
// 1. npm run build β†’ next build
//    - Compiles TypeScript
//    - Generates static pages (SSG)
//    - Optimizes bundle (tree shaking, code splitting)
//    - Generates sitemap, robots.txt
// 2. npm run start β†’ next start
//    - Starts production server
//    - Serves static files from .next/
//    - Handles SSR and ISR

interface ChecklistItem {
  id: string;
  category: string;
  title: string;
  description: string;
  impact: 'critical' | 'high' | 'medium';
  command?: string;
}

const checklist: ChecklistItem[] = [
  {
    id: '1', category: 'Build', title: 'Build without errors',
    description: 'npm run build must complete successfully',
    impact: 'critical', command: 'npm run build',
  },
  {
    id: '2', category: 'Build', title: 'TypeScript - no type errors',
    description: 'Strict mode, zero any warnings',
    impact: 'critical', command: 'npx tsc --noEmit',
  },
  {
    id: '3', category: 'Build', title: 'Linting',
    description: 'ESLint with no warnings or errors',
    impact: 'high', command: 'npm run lint',
  },
  {
    id: '4', category: 'Performance', title: 'Bundle analysis',
    description: 'Check bundle size, remove unused dependencies',
    impact: 'high', command: 'ANALYZE=true npm run build',
  },
  {
    id: '5', category: 'Performance', title: 'Image optimization',
    description: 'Use next/image, WebP/AVIF, lazy loading',
    impact: 'high',
  },
  {
    id: '6', category: 'Performance', title: 'Font optimization',
    description: 'Use next/font, self-hosting, font-display: swap',
    impact: 'medium',
  },
  {
    id: '7', category: 'SEO', title: 'Metadata on every page',
    description: 'title, description, Open Graph for social sharing',
    impact: 'high',
  },
  {
    id: '8', category: 'SEO', title: 'sitemap.xml and robots.txt',
    description: 'Automatic generation in app/sitemap.ts and app/robots.ts',
    impact: 'medium',
  },
  {
    id: '9', category: 'Security', title: 'Environment variables',
    description: 'Secrets in .env.local, NEXT_PUBLIC_ only for public ones',
    impact: 'critical',
  },
  {
    id: '10', category: 'Security', title: 'Security headers',
    description: 'CSP, X-Frame-Options, HSTS in next.config.js',
    impact: 'high',
  },
  {
    id: '11', category: 'Deploy', title: 'Platform selection',
    description: 'Vercel (best), Netlify, AWS, Docker',
    impact: 'high',
  },
  {
    id: '12', category: 'Deploy', title: 'CI/CD pipeline',
    description: 'GitHub Actions: build β†’ test β†’ deploy',
    impact: 'medium',
  },
];

const impactColors = { critical: '#f44336', high: '#ff9800', medium: '#64ffda' };
const categories = [...new Set(checklist.map(c => c.category))];

function BuildOutput() {
  const routes = [
    { path: '/', type: 'Static', size: '5.2 kB' },
    { path: '/products', type: 'SSG', size: '12.4 kB' },
    { path: '/products/[id]', type: 'SSG', size: '8.7 kB' },
    { path: '/dashboard', type: 'SSR', size: '15.1 kB' },
    { path: '/api/health', type: 'API', size: '1.2 kB' },
  ];

  const typeIcons: Record<string, string> = {
    Static: 'S', SSG: 'G', SSR: 'R', API: 'A',
  };
  const typeColors: Record<string, string> = {
    Static: '#7c4dff', SSG: '#64ffda', SSR: '#ff9800', API: '#2196f3',
  };

  return (
    <div style={{
      background: 'rgba(0,0,0,0.3)', borderRadius: '8px', padding: '16px',
    }}>
      <h4 style={{ color: '#64ffda', marginBottom: '8px', fontSize: '0.85rem' }}>
        $ next build
      </h4>
      <div style={{ display: 'grid', gap: '4px' }}>
        {routes.map(r => (
          <div key={r.path} style={{
            display: 'flex', alignItems: 'center', gap: '10px',
            padding: '6px 8px', fontFamily: 'monospace', fontSize: '0.8rem',
          }}>
            <span style={{
              width: '20px', height: '20px', borderRadius: '4px',
              background: typeColors[r.type], color: '#0f0f23',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: '0.7rem', fontWeight: 'bold', flexShrink: 0,
            }}>{typeIcons[r.type]}</span>
            <span style={{ color: '#b0bec5', flex: 1 }}>{r.path}</span>
            <span style={{ color: '#78909c' }}>{r.size}</span>
          </div>
        ))}
      </div>
      <div style={{
        marginTop: '12px', padding: '8px', borderTop: '1px solid rgba(255,255,255,0.05)',
        display: 'flex', justifyContent: 'space-between',
      }}>
        <span style={{ color: '#4caf50', fontSize: '0.8rem' }}>Build completed in 12.4s</span>
        <span style={{ color: '#78909c', fontSize: '0.8rem' }}>Total: 42.6 kB</span>
      </div>
    </div>
  );
}

export default function ProductionChecklist() {
  const [completed, setCompleted] = useState<Set<string>>(new Set());
  const [activeCategory, setActiveCategory] = useState('all');

  const toggle = (id: string) => {
    setCompleted(prev => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id); else next.add(id);
      return next;
    });
  };

  const filtered = activeCategory === 'all'
    ? checklist
    : checklist.filter(c => c.category === activeCategory);

  const progress = Math.round((completed.size / checklist.length) * 100);

  return (
    <div style={{
      background: '#0f0f23', minHeight: '100vh', padding: '24px',
      color: '#fff', fontFamily: 'system-ui, sans-serif',
    }}>
      <h1 style={{ color: '#64ffda', marginBottom: '4px' }}>Production Checklist</h1>
      <p style={{ color: '#b0bec5', marginBottom: '16px' }}>
        Preparing Next.js application for deployment
      </p>

      <div style={{
        background: 'rgba(100,255,218,0.05)', borderRadius: '10px',
        padding: '12px 16px', marginBottom: '20px',
        display: 'flex', alignItems: 'center', gap: '16px',
      }}>
        <div style={{
          width: '48px', height: '48px', borderRadius: '50%',
          background: `conic-gradient(#64ffda ${progress * 3.6}deg, rgba(255,255,255,0.05) 0deg)`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <span style={{ color: '#64ffda', fontWeight: 'bold', fontSize: '0.8rem' }}>{progress}%</span>
        </div>
        <div>
          <p style={{ color: '#fff', margin: 0, fontWeight: 600 }}>{completed.size}/{checklist.length} completed</p>
          <p style={{ color: '#78909c', margin: 0, fontSize: '0.8rem' }}>
            {progress === 100 ? 'Ready to deploy!' : 'Complete all checks before deploying'}
          </p>
        </div>
      </div>

      <div style={{ display: 'flex', gap: '8px', marginBottom: '16px' }}>
        <button onClick={() => setActiveCategory('all')} style={{
          background: activeCategory === 'all' ? '#64ffda' : 'transparent',
          color: activeCategory === 'all' ? '#0f0f23' : '#b0bec5',
          border: '1px solid rgba(100,255,218,0.3)',
          padding: '6px 12px', borderRadius: '20px', cursor: 'pointer',
        }}>All</button>
        {categories.map(c => (
          <button key={c} onClick={() => setActiveCategory(c)} style={{
            background: activeCategory === c ? '#64ffda' : 'transparent',
            color: activeCategory === c ? '#0f0f23' : '#b0bec5',
            border: '1px solid rgba(100,255,218,0.3)',
            padding: '6px 12px', borderRadius: '20px', cursor: 'pointer',
          }}>{c}</button>
        ))}
      </div>

      <div style={{ display: 'grid', gap: '8px', marginBottom: '20px' }}>
        {filtered.map(item => (
          <div key={item.id} onClick={() => toggle(item.id)} style={{
            display: 'flex', alignItems: 'center', gap: '12px',
            background: completed.has(item.id) ? 'rgba(76,175,80,0.05)' : 'rgba(255,255,255,0.02)',
            border: `1px solid ${completed.has(item.id) ? 'rgba(76,175,80,0.2)' : 'rgba(255,255,255,0.06)'}`,
            borderRadius: '8px', padding: '12px', cursor: 'pointer',
          }}>
            <div style={{
              width: '22px', height: '22px', borderRadius: '6px',
              border: `2px solid ${completed.has(item.id) ? '#4caf50' : 'rgba(255,255,255,0.2)'}`,
              background: completed.has(item.id) ? '#4caf50' : 'transparent',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              color: '#fff', fontSize: '0.7rem', flexShrink: 0,
            }}>
              {completed.has(item.id) ? 'V' : ''}
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                <span style={{
                  color: completed.has(item.id) ? '#78909c' : '#fff',
                  textDecoration: completed.has(item.id) ? 'line-through' : 'none',
                }}>{item.title}</span>
                <span style={{
                  background: `${impactColors[item.impact]}15`,
                  color: impactColors[item.impact],
                  padding: '1px 8px', borderRadius: '10px', fontSize: '0.65rem',
                }}>{item.impact}</span>
              </div>
              <p style={{ color: '#78909c', fontSize: '0.8rem', margin: '2px 0 0' }}>{item.description}</p>
            </div>
          </div>
        ))}
      </div>

      <BuildOutput />
    </div>
  );
}

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. The 'npm run build' command in Next.js:

  2. 2. Bundle analyzer in Next.js is used for:

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

Hands-on tasks in the game

  • Code editor

    Build an interface with bundle size optimization and lazy loading

  • Click in order

    Arrange the elements in the correct order: npm β†’ install β†’ @next/bundle-analyzer

  1. QuestionThe 'npm run build' command in Next.js:
  2. QuestionBundle analyzer in Next.js is used for:
  3. Coding taskPractice: Optimization and Lazy Loading
  4. Click in orderSequence: npm β†’ install β†’ @next/bundle-analyzer
  5. QuestionTree shaking in JavaScript means:

Useful articles