Frontend

Next.js Setup & Deployment Guide

React framework with server rendering, routing and API routes – create, configure and deploy to Vercel or your own server.

Updated Official documentation ↗

1. Introduction & use cases

Next.js is a React framework by Vercel. It adds file-based routing, server-side rendering (SSR), static generation (SSG), React Server Components, API endpoints (Route Handlers), image optimisation and built-in SEO metadata – things plain React leaves to you.

Pages render on the server, so search engines and social previews see real HTML. You can deploy to Vercel (zero config), to any Node.js server (next start), in a Docker container (standalone output), or as a static export when you need no server features.

Where it is used

  • SEO-friendly marketing sites, blogs and documentation
  • E-commerce stores with fast server-rendered product pages
  • Full-stack apps with UI and API in one project
  • Dashboards with authentication and server-side data fetching

2. Prerequisites

You needVersion / notes
Node.jsA recent LTS version (Next.js 15/16 needs Node 20 or newer – check the docs for your version)
npm / pnpm / yarnPackage manager (npm comes with Node)
EditorVS Code with ESLint and Tailwind CSS IntelliSense
BasicsReact components and hooks; TypeScript is recommended

3. Local setup

  1. 1Install Node.js LTS

    Check your version first.

    BASH
    node -v   # should be a current LTS
    npm -v
  2. 2Create the app

    create-next-app asks about TypeScript, ESLint, Tailwind CSS, the src/ folder, App Router and import alias. Accept the defaults if unsure (TypeScript + App Router).

    BASH
    npx create-next-app@latest my-next-app
  3. 3Start the dev server

    Open http://localhost:3000. Pages reload as you edit.

    BASH
    cd my-next-app
    npm run dev

4. Create & run a project

  1. 1Edit the home page

    In the App Router every folder under app/ is a route and page.tsx is its UI. Components are Server Components by default.

    app/page.tsx
    export default function Home() {
      return (
        <main className="p-8">
          <h1 className="text-3xl font-bold">Hello Next.js</h1>
          <p>Rendered on the server.</p>
        </main>
      );
    }
  2. 2Add a page that loads data on the server

    Server Components can be async and fetch data directly. revalidate caches the result for 60 seconds (ISR).

    app/posts/page.tsx
    type Post = { id: number; title: string };
    
    export const revalidate = 60;
    
    export default async function PostsPage() {
      const res = await fetch('https://jsonplaceholder.typicode.com/posts?_limit=5');
      const posts: Post[] = await res.json();
      return (
        <ul>{posts.map((p) => <li key={p.id}>{p.title}</li>)}</ul>
      );
    }
  3. 3Create an API route

    Route Handlers live in route.ts files.

    app/api/health/route.ts
    export async function GET() {
      return Response.json({ status: 'ok', time: new Date().toISOString() });
    }
  4. 4Add a client component for interactivity

    Add 'use client' at the top of files that use state, effects or browser APIs.

    app/components/LikeButton.tsx
    'use client';
    import { useState } from 'react';
    
    export default function LikeButton() {
      const [likes, setLikes] = useState(0);
      return <button onClick={() => setLikes(likes + 1)}>♥ {likes}</button>;
    }
  5. 5Set page metadata for SEO

    Export metadata (or generateMetadata) from a layout or page.

    app/posts/layout.tsx
    import type { Metadata } from 'next';
    export const metadata: Metadata = {
      title: 'Posts',
      description: 'Latest posts',
    };

✅ When it works you should see output like Figure 1.

5. Development configuration

Environment variables

Next.js loads .env.local (git-ignored) automatically. Variables are server-only unless they start with NEXT_PUBLIC_, which are inlined into browser code at build time – so rebuild after changing them.

.env.local
# .env.local
DATABASE_URL=postgres://user:pass@localhost:5432/app   # server only
AUTH_SECRET=change-me                                 # server only
NEXT_PUBLIC_SITE_URL=http://localhost:3000            # visible in the browser

Key dependencies

Package / toolUsed for
next, react, react-domFramework and React
typescript, @types/reactType checking
eslint, eslint-config-nextLinting with Next.js rules
tailwindcss (optional)Utility-first CSS
next/image, next/fontBuilt-in image optimisation and self-hosted fonts

Folder structure

project structure
my-next-app/
├── app/
│   ├── layout.tsx        # root layout (<html>, <body>)
│   ├── page.tsx          # route: /
│   ├── posts/page.tsx    # route: /posts
│   └── api/health/route.ts  # GET /api/health
├── public/               # static files
├── .env.local
├── next.config.ts
├── package.json
└── tsconfig.json

Essential commands

CommandWhat it does
npm run devDevelopment server with fast refresh
npm run buildProduction build (.next/) – also type-checks and lints
npm run startRun the production build (next start, port 3000)
npm run lintESLint
npx next infoPrint versions for bug reports

6. Production deployment

Easiest: push to GitHub and import the repo in Vercel – it builds and hosts automatically with SSL. Below is the self-hosted path on your own Linux server with PM2 and Nginx, which supports every Next.js feature.

Server & hosting requirements

RequirementRecommendation
ServerUbuntu VPS, 1 vCPU / 2 GB RAM recommended (builds need memory; or build in CI)
RuntimeNode.js LTS (same major as development)
Process managerPM2 or systemd to keep next start running
Reverse proxyNginx in front of port 3000
Domain + SSLDNS A record + Let’s Encrypt

Deployment steps

  1. 1Prepare an Ubuntu server

    Create a VPS (AWS EC2, DigitalOcean, Hostinger VPS, Linode …) with Ubuntu 24.04 LTS, at least 1 vCPU and 1–2 GB RAM. Log in with SSH, update the system and create a non-root user for the app.

    BASH
    ssh root@YOUR_SERVER_IP
    apt update && apt upgrade -y
    adduser deploy
    usermod -aG sudo deploy
    # copy your SSH key to the new user, then log in as deploy
    rsync --archive --chown=deploy:deploy ~/.ssh /home/deploy
    exit
    ssh deploy@YOUR_SERVER_IP
  2. 2Install Node.js on the server

    Install the current LTS release with nvm (or the NodeSource packages). Use the same major version as on your computer.

    BASH
    curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh | bash
    source ~/.bashrc
    nvm install --lts
    node -v && npm -v
  3. 3Get the code and build it

    Clone the repository on the server (or upload a build artifact from CI). Install exact dependency versions with npm ci and build.

    BASH
    git clone https://github.com/you/your-app.git /var/www/my-next-app
    cd /var/www/my-next-app
    cp .env.example .env.production   # then edit real values
    npm ci
    npm run build
  4. 4Keep the app running with PM2

    PM2 restarts the app if it crashes and starts it again after a server reboot. pm2 startup prints one command – run it with sudo, then pm2 save.

    BASH
    sudo npm install -g pm2
    pm2 start npm --name my-next-app -- start
    pm2 startup          # run the command it prints
    pm2 save
    pm2 logs my-next-app        # live logs
    pm2 restart my-next-app     # after each deploy
  5. 5Install Nginx as a reverse proxy

    Nginx receives requests on ports 80/443 and forwards them to your app on 127.0.0.1:3000. Replace example.com with your domain.

    /etc/nginx/sites-available/example.com
    server {
        listen 80;
        server_name example.com www.example.com;
    
        location / {
            proxy_pass http://127.0.0.1:3000;
            proxy_http_version 1.1;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
        }
    }
  6. 6Enable the site and reload Nginx

    Link the config into sites-enabled, test it and reload. nginx -t must say syntax is ok before you reload.

    BASH
    sudo apt install -y nginx
    sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
    sudo nginx -t
    sudo systemctl reload nginx
  7. 7Open only the ports you need

    Allow SSH, HTTP and HTTPS through the firewall. Application ports (3000, 8000 …) stay closed to the internet – Nginx forwards traffic to them.

    BASH
    sudo ufw allow OpenSSH
    sudo ufw allow 'Nginx Full'   # ports 80 and 443 (after installing Nginx)
    sudo ufw enable
    sudo ufw status
  8. 8Point your domain to the server

    In your domain registrar's DNS panel add an A record for @ (and www) with the server's public IP address. DNS changes usually appear within minutes but can take up to 24–48 hours. Check with dig or an online DNS checker.

    OUTPUT
    # Type  Name  Value              TTL
    # A     @     203.0.113.10       3600
    # A     www   203.0.113.10       3600
    dig +short example.com
  9. 9Add free HTTPS with Let’s Encrypt

    Certbot gets a free SSL certificate, adds it to the Nginx config and redirects HTTP to HTTPS. Certificates renew automatically (a systemd timer runs twice a day); test renewal once with --dry-run.

    BASH
    sudo apt install -y certbot python3-certbot-nginx
    sudo certbot --nginx -d example.com -d www.example.com
    sudo certbot renew --dry-run
  10. 10Optional: Docker with standalone output

    Set output: 'standalone' so the build contains only the files needed to run, then copy .next/standalone, .next/static and public into a small Node image.

    DOCKERFILE
    // next.config.ts
    const nextConfig = { output: 'standalone' };
    export default nextConfig;
    
    # Dockerfile (runtime stage)
    FROM node:lts-alpine
    WORKDIR /app
    ENV NODE_ENV=production
    COPY .next/standalone ./
    COPY .next/static ./.next/static
    COPY public ./public
    EXPOSE 3000
    CMD ["node", "server.js"]
  11. 11Deploy updates

    Pull, install, build, then reload without downtime.

    BASH
    cd /var/www/my-next-app
    git pull
    npm ci && npm run build
    pm2 reload my-next-app

🗺 The whole path from your code to the live site is drawn in the deployment diagram.

7. Images & screenshots

Illustrations drawn for this guide from the commands above. Product dashboards change often, so for screens such as cloud consoles follow the step text and the official documentation.

terminal$ npm run dev> my-next-app@0.1.0 dev> next dev ▲ Next.js - Local: http://localhost:3000 - Network: http://192.168.1.5:3000 ✓ Starting... ✓ Ready in 1.8s ○ Compiling / ... ✓ Compiled / in 2.1s
Figure 1: terminal output of the sample Next.js project (section 4).
1Push to Git2npm ci && nextbuild3PM2: next start:30004Nginx reverseproxy5HTTPS (Let’sEncrypt)
Figure 2: production deployment flow (section 6).
my-next-app/├── app/│ ├── layout.tsx # root layout (<html>, <body>)│ ├── page.tsx # route: /│ ├── posts/page.tsx # route: /posts│ └── api/health/route.ts # GET /api/health├── public/ # static files├── .env.local├── next.config.ts├── package.json└── tsconfig.json
Figure 3: project folder structure (section 5).

8. Common errors & solutions

Hydration failed because the server rendered HTML did not match the client

Something differs between server and browser render – e.g. Date.now(), Math.random(), window checks or browser extensions. Move browser-only code into useEffect or a client component.

useState / useEffect only works in Client Components

Add 'use client' as the first line of that file, or move the interactive part into its own client component.

Environment variable is undefined in the browser

Prefix it with NEXT_PUBLIC_ and rebuild – public variables are inlined at build time.

Build killed / JavaScript heap out of memory on a small VPS

Build in CI or on your computer and upload the result, add swap space, or raise the heap: NODE_OPTIONS=--max-old-space-size=2048 npm run build.

next/image error: hostname is not configured

Allow the remote domain in next.config.ts under images.remotePatterns.

Pages show old data in production

The page is statically cached. Use export const revalidate = 60, fetch(url, { cache: 'no-store' }) or export const dynamic = 'force-dynamic' where fresh data is required.

Best practices

  • Keep components on the server by default; mark only interactive leaves with 'use client'.
  • Never expose secrets with NEXT_PUBLIC_.
  • Use generateMetadata, sitemap.ts and robots.ts for SEO.
  • Build in CI and deploy the artifact to keep production servers small.
  • Pin the Node.js major version (.nvmrc / engines) so local, CI and server match.