Next.js


Next.js is a React framework designed to simplify the process of building fast, SEO-friendly and production-ready web applications. While React helps you build the UI, Next.js handles routing, rendering, performance optimization, and more — all out of the box.
It was created by Vercel and adds powerful features on top of React.
Core Features of Next.js
1.File-based Routing
- Pages are automatically created based on files in the
pages/
orapp/
directory.
2.Server-Side Rendering (SSR)
Pages can be rendered on the server at request time.
Improves performance and SEO.
3.Static Site Generation (SSG)
- Pages are pre-rendered at build time.
4.API Routes
- You can build a backend inside the same project using files inside
pages/api
.
5.Built-in CSS and Sass Support
- Supports global and module-based styles.
6.Image Optimization
- Automatically optimizes images with
<Image />
fromnext/image
.
7.Typescript Support
- Fully supports TypeScript with zero config.
8.App Router (New)
- Uses React Server Components, layouts, and Server Actions for better flexibility.
Why Use Next.js?
SEO-Friendly (supports SSR)
Fast page load (via SSG and caching)
Great Developer Experience
Easy deployment on platforms like Vercel
Full-stack capabilities (Frontend + API)
What is SSG and SSR ?
SSG pre-renders HTML at build time. It creates static pages that are served instantly on request.
Use When:
Your content doesn’t change frequently.
You want fast performance and can tolerate data staleness.
You need excellent SEO (blog, documentation, landing pages).
export async function getStaticProps() { const data = await fetchData(); return { props: { data }, }; }
SSR generates HTML at each request, ensuring the latest data is always shown.
Use When:
Content changes frequently (e.g., dashboard, user-specific pages).
Real-time data is important.
SEO is important, but data can't be pre-rendered.
export async function getServerSideProps(context) { const data = await fetchData(); return { props: { data }, }; }
Dynamic Routing and File-Based Navigation in Next.js
What is Dynamic Routing?
Sometimes, we don’t know the exact path ahead of time — like user profiles, product details, etc. For such cases, dynamic routes help.
Syntax:
Create a file with square brackets [param]
inside the pages/
folder.
pages/product/[id].js
This maps to URLs like:
/product/1
/product/abc
/product/xyz
What is File-Based Routing?
Next.js uses the file-system as the main API for routing. This means:
Each file inside the
pages/
directory automatically becomes a route.For example:
pages/index.js
→/
pages/about.js
→/about
No need to manually configure routes like in React Router.
Creating API Routing in Next.js for Backend Functionality
In Next.js, you can create backend functionality using API routes, which allow you to write server-side code directly in your project.
How API Routing Works in Next.js
API routes live inside the
pages/api/
directory.Each file in
pages/api
corresponds to an endpoint.API route files export a default function that handles HTTP requests.
Example: Creating an API Route
Let’s create a simple API route at /api/hello
:
pages/api/hello.js
export default function handler(req, res) {
if (req.method === 'GET') {
res.status(200).json({ message: 'Hello from Next.js API!' });
} else {
res.status(405).json({ error: 'Method Not Allowed' });
}
}
Output:
When you visit http://localhost:3000/api/hello
, you’ll get:
{ "message": "Hello from Next.js API!" }
API Route with POST Request Example
pages/api/contact.js
export default function handler(req, res) {
if (req.method === 'POST') {
const { name, email } = req.body;
// You can now save this data to a database, send an email, etc.
res.status(200).json({ success: true, message: `Thanks ${name}!` });
} else {
res.status(405).json({ error: 'Only POST requests allowed' });
}
}
Then from the frontend:
fetch('/api/contact', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Himanshu', email: 'him@example.com' })
})
Explain difference between React and Next.js
React
What it is: A JavaScript library for building user interfaces.
Created by: Facebook
Focus: Only the frontend (UI part).
Rendering: By default, it uses Client-Side Rendering (CSR).
Routing: You need to set up routing manually (e.g., using
react-router
).Features:
Component-based architecture
Virtual DOM
Reusable UI components
State management (via hooks or external libraries)
Next.js
What it is: A React framework for building full-stack web applications.
Created by: Vercel
Focus: Both frontend and backend.
Rendering: Supports multiple types:
Client-Side Rendering (CSR)
Server-Side Rendering (SSR)
Static Site Generation (SSG)
Incremental Static Regeneration (ISR)
Routing: Built-in file-based routing (no need for
react-router
)Extra Features:
API routes (server functions)
Image optimization
SEO-friendly pages
Middleware & server actions
Better performance out-of-the-box
When to Use:
React: When building only a frontend UI or SPA with a custom backend.
Next.js: When you want a full-stack React app with better performance and SEO.
Basic Folder Structure
my-next-app/
├── app/ # App Router (replaces 'pages/')
│ ├── layout.tsx # Root layout component
│ ├── page.tsx # Home page (route: '/')
│ ├── about/ # Nested route (route: '/about')
│ │ └── page.tsx
│ ├── dashboard/
│ │ ├── layout.tsx # Nested layout for dashboard
│ │ ├── page.tsx # Dashboard main page
│ │ └── settings/
│ │ └── page.tsx # Route: '/dashboard/settings'
│ └── api/ # API routes (replaces pages/api/)
│ └── hello/
│ └── route.ts # Route: /api/hello
│
├── components/ # Reusable UI components
│ └── Button.tsx
│
├── lib/ # Utilities, services, or helpers
│ └── auth.ts
│
├── public/ # Static assets (served from '/')
│ └── favicon.ico
│
├── styles/ # Global or modular CSS
│ ├── globals.css
│ └── theme.css
│
├── middleware.ts # Middleware for auth, redirects, etc.
├── next.config.js # Next.js config
├── tailwind.config.js # Tailwind CSS config (if used)
├── tsconfig.json # TypeScript config
├── .env.local # Environment variables (local only)
└── package.json # Project metadata and scripts
Key Concepts
Folder/File | Purpose |
app/ | App Router system – defines routes using folders |
layout.tsx | Wraps child pages, good for navbars, themes, etc. |
page.tsx | Page component for a specific route |
route.ts | API route handler (new in App Router) |
components/ | Shared React components |
lib/ | Business logic, db clients, helper functions |
public/ | Static files like images, robots.txt |
middleware.ts | Runs before request, useful for auth, i18n |
.env.local | Secure environment variables (not committed) |
Optional Additions:
hooks/
— For React hookscontext/
— For React Context providersstore/
— For global state (e.g., Redux, Zustand)types/
— TypeScript typestests/
— For unit/integration tests
Examples of Blog pages , products routes and API handlers
1. Dynamic Routing (File-Based Routing)
Next.js uses the file structure inside the pages/
directory to define routes. You can create dynamic routes using square brackets.
Example: Blog Pages
Let's say you want to create a blog and each blog has a unique slug (URL part).
pages/
blog/
[slug].js
- If a user visits
/blog/how-to-code
,[slug].js
will render with the slug value"how-to-code"
.
// pages/blog/[slug].js
import { useRouter } from 'next/router'
export default function BlogPost() {
const router = useRouter();
const { slug } = router.query;
return <h1>Blog: {slug}</h1>;
}
2. Dynamic Product Routes
For e-commerce product pages:
pages/
products/
[id].js
- Visiting
/products/123
will render the product page with ID 123.
Code:
// pages/products/[id].js
import { useRouter } from 'next/router';
export default function ProductPage() {
const { id } = useRouter().query;
return <h1>Product ID: {id}</h1>;
}
3. API Routes (Backend Handlers)
Next.js allows backend logic inside pages/api
.
Example: API to Get All Products
pages/
api/
products/
index.js
Code:
// pages/api/products/index.js
export default function handler(req, res) {
const products = [{ id: 1, name: 'Shirt' }, { id: 2, name: 'Shoes' }];
res.status(200).json(products);
}
4. Server Actions (New in Next.js App Router)
Server Actions allow you to run server-side code (like saving to DB) directly from components.
Example: Submit Blog Form
In app router (e.g., /app/blog/new/page.js
):
'use server';
export async function createPost(formData) {
const title = formData.get('title');
// Save to DB or perform server logic
console.log('Saving post:', title);
}
And inside your component:
<form action={createPost}>
<input name="title" type="text" />
<button type="submit">Post</button>
</form>
Summary
I’m truly thankful for your time and effort in reading this.
Subscribe to my newsletter
Read articles from Himanshu Maurya directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Himanshu Maurya
Himanshu Maurya
Hi, Thank-you for stopping by and having a look at my profile. Hi! I’m a web developer who loves working with the MERN stack . I enjoy making interactive and user-friendly websites and webapps. I’m great at taking ideas and bringing them to life through coding!