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 need | Version / notes |
|---|---|
| Node.js | A recent LTS version (Next.js 15/16 needs Node 20 or newer – check the docs for your version) |
| npm / pnpm / yarn | Package manager (npm comes with Node) |
| Editor | VS Code with ESLint and Tailwind CSS IntelliSense |
| Basics | React components and hooks; TypeScript is recommended |
3. Local setup
1Install Node.js LTS
Check your version first.
BASHnode -v # should be a current LTS npm -v2Create the app
create-next-appasks about TypeScript, ESLint, Tailwind CSS, thesrc/folder, App Router and import alias. Accept the defaults if unsure (TypeScript + App Router).BASHnpx create-next-app@latest my-next-app3Start the dev server
Open http://localhost:3000. Pages reload as you edit.
BASHcd my-next-app npm run dev
4. Create & run a project
1Edit the home page
In the App Router every folder under
app/is a route andpage.tsxis its UI. Components are Server Components by default.app/page.tsxexport 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> ); }2Add a page that loads data on the server
Server Components can be
asyncand fetch data directly.revalidatecaches the result for 60 seconds (ISR).app/posts/page.tsxtype 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> ); }3Create an API route
Route Handlers live in
route.tsfiles.app/api/health/route.tsexport async function GET() { return Response.json({ status: 'ok', time: new Date().toISOString() }); }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>; }5Set page metadata for SEO
Export
metadata(orgenerateMetadata) from a layout or page.app/posts/layout.tsximport 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
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 browserKey dependencies
| Package / tool | Used for |
|---|---|
next, react, react-dom | Framework and React |
typescript, @types/react | Type checking |
eslint, eslint-config-next | Linting with Next.js rules |
tailwindcss (optional) | Utility-first CSS |
next/image, next/font | Built-in image optimisation and self-hosted fonts |
Folder 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.jsonEssential commands
| Command | What it does |
|---|---|
npm run dev | Development server with fast refresh |
npm run build | Production build (.next/) – also type-checks and lints |
npm run start | Run the production build (next start, port 3000) |
npm run lint | ESLint |
npx next info | Print 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
| Requirement | Recommendation |
|---|---|
| Server | Ubuntu VPS, 1 vCPU / 2 GB RAM recommended (builds need memory; or build in CI) |
| Runtime | Node.js LTS (same major as development) |
| Process manager | PM2 or systemd to keep next start running |
| Reverse proxy | Nginx in front of port 3000 |
| Domain + SSL | DNS A record + Let’s Encrypt |
Deployment steps
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.
BASHssh 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_IP2Install 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.
BASHcurl -o- https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh | bash source ~/.bashrc nvm install --lts node -v && npm -v3Get the code and build it
Clone the repository on the server (or upload a build artifact from CI). Install exact dependency versions with
npm ciand build.BASHgit 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 build4Keep the app running with PM2
PM2 restarts the app if it crashes and starts it again after a server reboot.
pm2 startupprints one command – run it with sudo, thenpm2 save.BASHsudo 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 deploy5Install Nginx as a reverse proxy
Nginx receives requests on ports 80/443 and forwards them to your app on
127.0.0.1:3000. Replaceexample.comwith your domain./etc/nginx/sites-available/example.comserver { 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"; } }6Enable the site and reload Nginx
Link the config into
sites-enabled, test it and reload.nginx -tmust say syntax is ok before you reload.BASHsudo apt install -y nginx sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/ sudo nginx -t sudo systemctl reload nginx7Open 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.
BASHsudo ufw allow OpenSSH sudo ufw allow 'Nginx Full' # ports 80 and 443 (after installing Nginx) sudo ufw enable sudo ufw status8Point your domain to the server
In your domain registrar's DNS panel add an A record for
@(andwww) with the server's public IP address. DNS changes usually appear within minutes but can take up to 24–48 hours. Check withdigor 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.com9Add 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.BASHsudo apt install -y certbot python3-certbot-nginx sudo certbot --nginx -d example.com -d www.example.com sudo certbot renew --dry-run10Optional: Docker with standalone output
Set
output: 'standalone'so the build contains only the files needed to run, then copy.next/standalone,.next/staticandpublicinto 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"]11Deploy updates
Pull, install, build, then reload without downtime.
BASHcd /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.
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.tsandrobots.tsfor 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.