What is Middleware?
Middleware runs before a request reaches the server. It's perfect for authentication, redirects, A/B testing and header manipulation.
Basic Middleware
// middleware.ts (at the project root)
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
// Protect dashboard routes
if (pathname.startsWith("/dashboard")) {
const token = request.cookies.get("auth-token");
if (!token) {
return NextResponse.redirect(new URL("/login", request.url));
}
}
return NextResponse.next();
}
export const config = {
matcher: ["/dashboard/:path*", "/admin/:path*"],
};
Language Detection and Redirects
export function middleware(request: NextRequest) {
const lang = request.headers.get("accept-language")?.split(",")[0].slice(0, 2);
const pathname = request.nextUrl.pathname;
const hasLocale = ["en", "tr"].some(l => pathname.startsWith(`/${l}`));
if (!hasLocale) {
const locale = lang === "tr" ? "tr" : "en";
return NextResponse.redirect(new URL(`/${locale}${pathname}`, request.url));
}
return NextResponse.next();
}
Adding Security Headers
export function middleware(request: NextRequest) {
const response = NextResponse.next();
response.headers.set("X-Frame-Options", "DENY");
response.headers.set("X-Content-Type-Options", "nosniff");
response.headers.set(
"Content-Security-Policy",
"default-src 'self'; script-src 'self' 'unsafe-inline'"
);
return response;
}
Önemli Noktalar
- middleware.ts lives at the project root
- config.matcher specifies which routes trigger the middleware
- NextResponse.redirect() redirects; rewrite() changes content without changing the URL
- Middleware runs on the Edge Runtime — extremely fast