Next.js on localhost:3000

http://localhost:3000

Next.js development server runs on port 3000 by default with fast refresh, hot module replacement, and automatic routing. This is the standard port for React-based Next.js applications.

→ Open localhost:3000

Create New Next.js Application

# Create with create-next-app (Recommended) npx create-next-app@latest my-next-app # Interactive setup will ask: # - TypeScript? (Yes/No) # - ESLint? (Yes) # - Tailwind CSS? (Yes/No) # - src/ directory? (Yes/No) # - App Router? (Yes - recommended) # - Import alias? (@/*) # Navigate into directory cd my-next-app # Start development server npm run dev # Server starts at http://localhost:3000

Next.js Commands

# Development mode (with hot reload) npm run dev # Build for production npm run build # Start production server npm run start # Run linter npm run lint # Development on custom port PORT=3001 npm run dev # Windows set PORT=3001 && npm run dev

Next.js Project Structure

App Router (Next.js 13+)

my-next-app/ ├── app/ │ ├── layout.js # Root layout │ ├── page.js # Home page → / │ ├── about/ │ │ └── page.js # → /about │ ├── blog/ │ │ ├── page.js # → /blog │ │ └── [slug]/ │ │ └── page.js # → /blog/post-1 │ └── api/ │ └── users/ │ └── route.js # → /api/users ├── public/ │ ├── images/ │ └── favicon.ico ├── styles/ │ └── globals.css ├── next.config.js ├── package.json └── README.md

Pages Router (Legacy)

my-next-app/ ├── pages/ │ ├── index.js # → / │ ├── about.js # → /about │ ├── blog/ │ │ ├── index.js # → /blog │ │ └── [slug].js # → /blog/post-1 │ └── api/ │ └── users.js # → /api/users ├── public/ ├── styles/ ├── components/ └── next.config.js

File-Based Routing

File Route Description
app/page.js / Home page
app/about/page.js /about About page
app/blog/page.js /blog Blog index
app/blog/[slug]/page.js /blog/:slug Dynamic route
app/api/users/route.js /api/users API endpoint

Create Pages

Simple Page (App Router)

// app/about/page.js export default function AboutPage() { return ( <div> <h1>About Us</h1> <p>Welcome to our Next.js application!</p>
); } // With metadata export const metadata = { title: 'About Us', description: 'Learn more about our company', };

Dynamic Route

// app/blog/[slug]/page.js export default function BlogPost({ params }) { const { slug } = params; return ( <div> <h1>Blog Post: {slug}</h1> <p>Content for {slug}</p>
); } // Generate static params export async function generateStaticParams() { const posts = ['post-1', 'post-2', 'post-3']; return posts.map((slug) => ({ slug: slug, })); }

API Routes

Create API Endpoint

// app/api/users/route.js import { NextResponse } from 'next/server'; // GET /api/users export async function GET(request) { const users = [ { id: 1, name: 'John Doe' }, { id: 2, name: 'Jane Smith' }, ]; return NextResponse.json(users); } // POST /api/users export async function POST(request) { const body = await request.json(); // Save to database const newUser = { id: Date.now(), ...body }; return NextResponse.json(newUser, { status: 201 }); }

Access API from Client

'use client' import { useEffect, useState } from 'react'; export default function UsersPage() { const [users, setUsers] = useState([]); useEffect(() => { fetch('http://localhost:3000/api/users') .then(res => res.json()) .then(data => setUsers(data)); }, []); return ( <ul> {users.map(user => ( <li key={user.id}>{user.name}</li> ))} </ul> ); }

Data Fetching

Server Components (Default)

// app/posts/page.js async function getPosts() { const res = await fetch('https://api.example.com/posts'); return res.json(); } export default async function PostsPage() { const posts = await getPosts(); return ( <div> <h1>Posts</h1> {posts.map(post => ( <article key={post.id}> <h2>{post.title}</h2> <p>{post.excerpt}</p> </article> ))}
); }

Client Components

'use client' import { useEffect, useState } from 'react'; export default function ClientComponent() { const [data, setData] = useState(null); useEffect(() => { fetch('/api/data') .then(res => res.json()) .then(setData); }, []); if (!data) return <p>Loading...</p>; return <div>{data.content}
; }

Configure Next.js

next.config.js

/** @type {import('next').NextConfig} */ const nextConfig = { // Custom port in config (or use PORT env variable) // Not recommended - use PORT=3001 npm run dev instead // Image domains images: { domains: ['example.com', 'cdn.example.com'], }, // Environment variables env: { CUSTOM_KEY: 'my-value', }, // Redirects async redirects() { return [ { source: '/old-page', destination: '/new-page', permanent: true, }, ]; }, // Rewrites async rewrites() { return [ { source: '/api/:path*', destination: 'https://api.example.com/:path*', }, ]; }, }; module.exports = nextConfig;

Environment Variables

# .env.local DATABASE_URL=postgresql://user:password@localhost:5432/mydb API_KEY=your-api-key-here # Public variables (available in browser) NEXT_PUBLIC_API_URL=http://localhost:3000/api NEXT_PUBLIC_SITE_NAME=My Next.js Site # Usage in code // Server-side const dbUrl = process.env.DATABASE_URL; // Client-side (must start with NEXT_PUBLIC_) const apiUrl = process.env.NEXT_PUBLIC_API_URL;

Fix "Next.js localhost Not Working"

Issue: Port 3000 already in use

# Find what's using port 3000 # Windows netstat -ano | findstr :3000 # Linux/Mac lsof -i :3000 # Kill process or use different port PORT=3001 npm run dev

Issue: Fast refresh not working

Issue: Module not found

# Reinstall dependencies rm -rf node_modules package-lock.json npm install # Or npm ci

Issue: Page not found (404)

Change Next.js Port

# Method 1: Environment variable PORT=3001 npm run dev # Windows set PORT=3001 && npm run dev # Method 2: package.json { "scripts": { "dev": "next dev -p 3001", "start": "next start -p 3001" } } # Method 3: Cross-platform (cross-env) npm install --save-dev cross-env { "scripts": { "dev": "cross-env PORT=3001 next dev" } }

Next.js Features

Production Build

# Build for production npm run build # Analyze bundle size npm run build -- --profile # Start production server npm run start # Runs on localhost:3000 # Export static site # next.config.js module.exports = { output: 'export', }; npm run build # Creates out/ directory
Pro Tip: Use App Router (Next.js 13+) for new projects. It provides better performance with Server Components, improved data fetching, and enhanced routing capabilities.

Frequently Asked Questions

What port does Next.js use?

Next.js uses port 3000 by default for development. You can change it using the PORT environment variable or -p flag.

Do I need a backend for Next.js?

No, Next.js includes API Routes that let you build backend endpoints within your Next.js application. However, you can connect to external APIs if needed.

What's the difference between App Router and Pages Router?

App Router (Next.js 13+) uses the app/ directory and supports React Server Components. Pages Router uses pages/ directory. App Router is recommended for new projects.

Can I use Next.js without Node.js?

No, Next.js requires Node.js to run. However, you can deploy as a static site (next export) which doesn't need Node.js at runtime.

How do I deploy Next.js from localhost?

Use Vercel (recommended), Netlify, or any hosting that supports Node.js. Run npm run build, then deploy the .next folder and node_modules.

Related Resources