Getting Started with Next.js
1. Installation & Setup
Next.js is a React framework by Vercel offering hybrid static and server rendering, performance by default, and zero-config routing. To get started, install Node.js (version 18.18+). Then run:
npx create-next-app@latest my-next-app --experimental-app
Select recommended features like TypeScript, ESLint, Tailwind CSS, `src/` folder, App Router, and Turbopack. If you prefer full control, install manually:
npm install next@latest react@latest react-dom@latest
package.json
should include key commands:
{
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
}
}
2. File Structure & App Router
With Next.js 15, the **App Router** is the modern default. It coexists with the Pages Router perfect for incremental migration. Inside behind `app/`, you structure features cleanly:
// app/layout.tsx
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
{children}
</body>
</html>
);
}
// app/page.tsx
export default function Home() {
return <h1>Welcome to Next.js with App Router</h1>;
}
The `layout.tsx` file replaces `_app.js` and `_document.js`, maintaining persistent layout across pages with zero re-rendering and built-in support for React Server Components and streaming.
3. Layouts & Routing
File-based routing makes your folder structure match your URL paths:
// app/blog/[slug]/page.tsx
export default async function BlogPost({ params }: { params: { slug: string } }) {
const slug = params.slug;
return <h1>Blog Post: {slug}</h1>;
}
Nest layouts for page hierarchies:
// app/dashboard/layout.tsx
export default function DashboardLayout({ children }: { children: React.ReactNode }) {
return (
<section>
<nav>Dashboard Menu</nav>
<main>{children}</main>
</section>
);
}
Use `loading.js`, `error.js`, and nested layouts to improve UX with suspense boundaries and fallbacks. it’s all baked in.
4. Data Fetching & Rendering Modes
Choose your rendering strategy at the function level:
- SSG (default): data fetched at build time (
cache: 'force-cache'
) - SSR: fresh data each request (
cache: 'no-store'
) - ISR: partially built pages with revalidation (
revalidate: seconds
)
// app/page.tsx
export default async function Page() {
const staticRes = await fetch('/api/data', { cache: 'force-cache' });
const liveRes = await fetch('/api/live', { cache: 'no-store' });
return (
<div>
<p>Static Data: {JSON.stringify(await staticRes.json())}</p>
<p>Live Data: {JSON.stringify(await liveRes.json())}</p>
</div>
);
}
This gives you granular control over performance and freshness . For example, blogs vs dashboards can handle data differently.
5. API Routes & Route Handlers
App Router uses Route Handlers instead of the Pages API:
// app/api/hello/route.ts
export async function GET(request: Request) {
return new Response(JSON.stringify({ message: 'Hello from Next.js API' }), {
headers: { 'content-type': 'application/json' }
});
}
These use native Web Request/Response, allow streaming, and support edge runtime No extra setup needed.
6. SEO, Metadata & Optimization
Next.js auto-handles SEO-friendly rendering. Use the metadata API for head tags:
// app/page.tsx
export const metadata = {
title: 'Home – My Site',
description: 'An awesome home page'
};
Use dynamic metadata or file-based OpenGraph (like `sitemap.ts`) for rich previews and SEO customization Learn More.
7. TypeScript & Tooling
TypeScript is integrated; write `.tsx` files and enjoy type safety and suggestions:
// app/page.tsx
type Props = { title: string };
export default function Page({ title }: Props) {
return <h1>{title}</h1>;
}
Use tools like ESLint, Prettier, and Tailwind configured by the initial CLI prompt. No extra setup needed.
8. Deployment Options (including Docker)
Easiest: Deploy on Vercel with optimized builds:
vercel --prod
Containerize your app with a multi-stage Docker approach:
# Dockerfile
FROM node:22-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:22-alpine AS runner
WORKDIR /app
COPY --from=builder /app ./
EXPOSE 3000
CMD ["npm", "start"]
Add a `.dockerignore` to exclude unnecessary files:
node_modules
.next
.git
README.md
.env*
Run:
docker build -t my-nextapp .docker run -p 3000:3000 my-nextapp
Docker deployments support all Next.js features and are portable to platforms like AWS, Railway, Kubernetes, etc.
9. Best Practices & Tips
- Use App Router as the default for new projects.
- Isolate server and client logic using `"use client"` declarations.
- Prefetch routes using ``, and optimize images with ``.
- Cache fetches with ISR or `no-store` depending on data volatility.
- Use the new codemod CLI for smooth upgrades:
npx @next/codemod@canary upgrade latest. G
reat for migrating to Next.js 15 and React 19.
Wrap-Up
You now have a thoroughly expanded and polished guide to Neo.js from installation and routing to data fetching, deployment, and best practices. This is crafted to get you building fast, optimized, and scalable web applications with confidence. Let me know when you're ready to explore middleware, internationalization, or authentication next!
Powered by Froala Editor