Documentation
Middlewares

Middlewares

Leverage middlewares in your Next.js application to capture headers like Authorization for authenticated users or Accept-Language for localized content. These headers can enhance the server-side rendering process by delivering tailored content.

Complete Example

A comprehensive middleware combining all patterns:

//This is sample code , update this according to the requirement.
import { NextRequest, NextResponse } from 'next/server';
 
export function middleware(request: NextRequest) {
	const headers = new Headers(request.headers);
	
	// Authentication
	const authToken = request.headers.get('authorization');
	const userId = request.cookies.get('user-id')?.value;
	
	if (authToken) headers.set('x-user-token', authToken);
	if (userId) headers.set('x-user-id', userId);
	
	// Localization
	const locale = request.headers.get('accept-language')?.split(',')[0] || 'en-US';
	const country = request.geo?.country || 'US';
	
	headers.set('x-user-locale', locale);
	headers.set('x-user-country', country);
	
	// Device detection
	const userAgent = request.headers.get('user-agent') || '';
	const deviceType = /Mobile|Android|iPhone/i.test(userAgent) ? 'mobile' : 
	                  /iPad|Tablet/i.test(userAgent) ? 'tablet' : 'desktop';
	
	headers.set('x-device-type', deviceType);
	
	// Performance hints
	if (request.headers.get('save-data') === 'on') {
		headers.set('x-save-data', 'true');
	}
	
	// Request context
	headers.set('x-request-id', crypto.randomUUID());
	headers.set('x-timestamp', Date.now().toString());
	headers.set('x-path-name', request.nextUrl.pathname);
	
	return NextResponse.next({ headers });
}
 
export const config = {
	matcher: [
		'/search/:path*',
		'/products/:path*',
		'/category/:path*',
		'/api/search/:path*'
	]
};