Introduction
Middleware.ts helps you run code before a page or API responds. It controls requests easily.
Jump into concepts and practice - no test required
Middleware.ts helps you run code before a page or API responds. It controls requests easily.
import { NextRequest, NextResponse } from 'next/server'; export function middleware(request: NextRequest) { // Your code here return NextResponse.next(); } export const config = { matcher: ['/path1/:path*', '/path2'], };
The middleware function runs on every matching request.
The config.matcher controls which paths use this middleware.
export function middleware(request: NextRequest) { return NextResponse.redirect(new URL('/login', request.url)); }
export function middleware(request: NextRequest) { const userAgent = request.headers.get('user-agent') || ''; if (userAgent.includes('Mobile')) { return NextResponse.rewrite(new URL('/mobile', request.url)); } return NextResponse.next(); }
export const config = { matcher: ['/dashboard/:path*', '/settings'], };
This middleware checks if a user has a 'token' cookie. If not, it redirects to the login page. It only runs on URLs starting with '/protected'.
import { NextRequest, NextResponse } from 'next/server'; export function middleware(request: NextRequest) { const token = request.cookies.get('token')?.value; if (!token) { return NextResponse.redirect(new URL('/login', request.url)); } return NextResponse.next(); } export const config = { matcher: ['/protected/:path*'], };
Middleware runs before the page or API code.
Use NextResponse.next() to continue the request normally.
Be careful with redirects to avoid loops.
Middleware.ts runs code before pages or APIs respond.
Use it to check, redirect, or modify requests.
Configure paths with config.matcher.
middleware.ts file in a Next.js project?middleware.ts?export const middleware = (req) => NextResponse.next(); which is valid and recommended.middleware.ts snippet, what will happen when a request to /dashboard is made?
import { NextResponse } from 'next/server';
export const config = { matcher: ['/dashboard'] };
export const middleware = (req) => {
if (!req.cookies.get('token')) {
return NextResponse.redirect(new URL('/login', req.url));
}
return NextResponse.next();
};middleware.ts code snippet:
import { NextResponse } from 'next/server';
export const middleware = (req) => {
if (req.cookies.token === undefined) {
return NextResponse.redirect('/login');
}
return NextResponse.next();
};req.cookies.get('name'), not as object properties.req.cookies.token will be undefined or cause error; correct is req.cookies.get('token').middleware.ts to run only on API routes starting with /api/private and redirect users without a valid auth cookie to /api/auth/unauthorized. Which config and middleware code correctly implements this?/api/private/:path* correctly matches all routes under /api/private.req.cookies.get('auth') is correct. Redirect uses NextResponse.redirect(new URL(...)) with full URL.