Next.js & App Router (50 Qs)•Part 1: Basic & Foundational Concepts (Junior / Entry-Level)
What is Next.js Middleware (`middleware.ts`) and where does it run?
junior LevelCode ExamplenextjsBasic
In Simple Words: Middleware runs before an incoming request is completed, at the Edge network layer:
- Common Use Cases:
- Authentication redirects (checking session cookies before page render).
- Geolocation-based routing and internationalization (i18n).
- Security headers and Bot protection.
- A/B testing URL rewrites.
typescript
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const token = request.cookies.get('session_token')?.value;
if (!token && request.nextUrl.pathname.startsWith('/dashboard')) {
return NextResponse.redirect(new URL('/login', request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ['/dashboard/:path*']
};