Introduction
Middleware intercepts requests to check or change them before they reach your app. It helps control who can see what and how your app responds.
Jump into concepts and practice - no test required
Middleware intercepts requests to check or change them before they reach your app. It helps control who can see what and how your app responds.
import { NextResponse } from 'next/server'; export function middleware(request) { // Your code here return NextResponse.next(); }
import { NextResponse } from 'next/server'; export function middleware(request) { // Let all requests continue return NextResponse.next(); }
import { NextResponse } from 'next/server'; export function middleware(request) { if (!request.cookies.get('user')) { // Redirect if no user cookie return NextResponse.redirect(new URL('/login', request.url)); } return NextResponse.next(); }
This middleware checks if the user has a 'loggedIn' cookie. If missing, it redirects them to '/login'. Otherwise, it lets the request continue.
import { NextResponse } from 'next/server'; export function middleware(request) { const url = request.nextUrl.clone(); if (!request.cookies.get('loggedIn')) { url.pathname = '/login'; return NextResponse.redirect(url); } return NextResponse.next(); }
Middleware runs on the server before your page or API code.
Use middleware to protect pages or add common logic for many routes.
Middleware lets you check or change requests before your app handles them.
It is useful for security, redirects, and modifying requests.
Always return a NextResponse to control the flow.
import { NextResponse } from 'next/server';
export function middleware(request) {
if (!request.cookies.get('token')) {
return NextResponse.redirect(new URL('/login', request.url));
}
return NextResponse.next();
}import { NextResponse } from 'next/server';
export function middleware(request) {
if (request.nextUrl.pathname === '/admin') {
NextResponse.redirect('/login');
}
return NextResponse.next();
}