SyntaxStudy
Sign Up
Next.js Next.js Configuration with next.config.js
Next.js Beginner 1 min read

Next.js Configuration with next.config.js

The next.config.js file at the project root is the central place to customise Next.js behaviour. It exports a plain JavaScript object (or a function) that Next.js merges with its defaults. Common options include enabling experimental features, configuring allowed image domains for next/image, setting up redirects and rewrites, and choosing the output mode for deployment. Environment variables are a critical part of any Next.js project. Variables defined in .env.local are available on the server side via process.env. To expose a variable to the browser you must prefix it with NEXT_PUBLIC_. Next.js also supports .env, .env.development, .env.production, and .env.test files, applied in order of precedence, so you can maintain different values per environment without changing code. The output option in next.config.js controls the deployment artifact. Setting output: 'standalone' produces a minimal Node.js server bundle ideal for Docker containers. Setting output: 'export' generates a fully static HTML export with no Node.js runtime required. The default (no output option) produces a standard Next.js server that works on platforms like Vercel or any Node.js host.
Example
// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  // Enable React strict mode for catching bugs early
  reactStrictMode: true,

  // Allow next/image to load images from external domains
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'images.unsplash.com',
      },
      {
        protocol: 'https',
        hostname: 'cdn.example.com',
        port: '',
        pathname: '/uploads/**',
      },
    ],
  },

  // Permanent redirects
  async redirects() {
    return [
      {
        source: '/old-blog/:slug',
        destination: '/blog/:slug',
        permanent: true, // 308 status
      },
    ];
  },

  // Rewrites (proxy without URL change)
  async rewrites() {
    return [
      {
        source: '/api/v1/:path*',
        destination: 'https://external-api.com/:path*',
      },
    ];
  },

  // Output mode for Docker deployment
  output: 'standalone',
};

module.exports = nextConfig;