MERN Course: Next.js Essentials
Weeks 14–16 of the MERN syllabus — App Router, SSR, data fetching, API routes, dynamic routing, next/image, auth, and full-stack project deployment.
Introduction
Next.js is how many MERN teams ship React in production. This guide maps the syllabus to App Router patterns — the same architecture powering this portfolio and blog.
Course Reference
Quick index
| # | Topic | Description |
|---|---|---|
| 1 | Getting Started with Next.js | Next.js extends React with file-based routing, SSR, API routes, and built-in optimizations. |
| 2 | Server-Side Rendering (SSR) | SSR renders HTML per request — great for personalized or frequently changing data. |
| 3 | Data Fetching Strategies | Choose by freshness needs: SSG (build time), ISR (revalidate interval), SSR (per request), client (SWR/React Query for interactive UI).. |
| 4 | Building API Routes | Route Handlers in app/api/ are serverless functions — ideal for BFF layers hiding secrets from the browser.. |
| 5 | Dynamic Routing | Dynamic segments [slug] map to params. |
| 6 | Image Optimization, SSG & ISR | next/image serves responsive WebP/AVIF, lazy loads, and prevents CLS with required dimensions.. |
| 7 | Authentication in Next.js | Auth belongs on the server: httpOnly cookies, session validation in middleware, protected Server Components and API routes.. |
| 8 | Final Next.js Full-Stack Project | Build a MERN-style app on Next.js: MongoDB via Mongoose in Route Handlers, React front-end, deploy to Vercel with env vars.. |
Week 14: Next.js & Server-Side Rendering
1. Getting Started with Next.js
Next.js extends React with file-based routing, SSR, API routes, and built-in optimizations. App Router (Next 13+) uses app/ with Server Components by default.
Example:
// app/blog/[slug]/page.tsx — Server Component
export default async function PostPage({ params }) {
const { slug } = await params
const post = getPostBySlug(slug)
return <article>{post.title}</article>
}2. Server-Side Rendering (SSR)
SSR renders HTML per request — great for personalized or frequently changing data. In App Router, dynamic pages opt into SSR by default unless cached.
Example:
// Force dynamic rendering (SSR on each request)
export const dynamic = 'force-dynamic'
export default async function Dashboard() {
const stats = await fetch('https://api.example.com/stats', {
cache: 'no-store',
}).then((r) => r.json())
return <pre>{JSON.stringify(stats, null, 2)}</pre>
}3. Data Fetching Strategies
Choose by freshness needs: SSG (build time), ISR (revalidate interval), SSR (per request), client (SWR/React Query for interactive UI).
- Static blog posts → SSG (
generateStaticParams) - Product catalog → ISR with
revalidate: 3600 - User dashboard → SSR or client fetch with auth
Example:
// ISR — revalidate every hour
const res = await fetch('https://api.example.com/products', {
next: { revalidate: 3600 },
})Week 15: API Routes, Dynamic Routing & Advanced Features
4. Building API Routes
Route Handlers in app/api/ are serverless functions — ideal for BFF layers hiding secrets from the browser.
Example:
// app/api/tasks/route.ts
import { NextResponse } from 'next/server'
export async function GET() {
const tasks = await db.task.findMany()
return NextResponse.json(tasks)
}
export async function POST(request: Request) {
const body = await request.json()
const task = await db.task.create({ data: body })
return NextResponse.json(task, { status: 201 })
}5. Dynamic Routing
Dynamic segments [slug] map to params. generateStaticParams pre-builds known paths; unknown paths can 404 or SSR on demand.
Example:
export function generateStaticParams() {
return getPostSlugs().map((slug) => ({ slug }))
}
export async function generateMetadata({ params }) {
const post = getPostBySlug((await params).slug)
return { title: post?.title ?? 'Not Found' }
}6. Image Optimization, SSG & ISR
next/image serves responsive WebP/AVIF, lazy loads, and prevents CLS with required dimensions.
Example:
import Image from 'next/image'
;<Image
src="/blog/cover.png"
alt="MERN course cover"
width={1200}
height={630}
priority={false}
sizes="(max-width: 768px) 100vw, 720px"
/>Week 16: Authentication & Final Project
7. Authentication in Next.js
Auth belongs on the server: httpOnly cookies, session validation in middleware, protected Server Components and API routes.
Example:
// middleware.ts
import { NextResponse } from 'next/server'
export function middleware(request) {
const token = request.cookies.get('session')?.value
if (!token && request.nextUrl.pathname.startsWith('/dashboard')) {
return NextResponse.redirect(new URL('/login', request.url))
}
return NextResponse.next()
}8. Final Next.js Full-Stack Project
Build a MERN-style app on Next.js: MongoDB via Mongoose in Route Handlers, React front-end, deploy to Vercel with env vars.
- Blog, e-commerce, or dashboard with auth
- Mix SSG public pages + SSR authenticated views
- Add API rate limiting and input validation
Subscribe to my newsletter
Stay up to date and get notified when I share new contents.
No spam ever, unsubscribe anytime