Auth Checks and Headers

Redirect Guests to Login

A cheap first check: is there a session cookie? If not, send the user to login and remember where they wanted to go.

// middleware.ts
import { NextRequest, NextResponse } from 'next/server';

export function middleware(req: NextRequest) {
  const hasSession = req.cookies.has('session');
  if (!hasSession) {
    const login = new URL('/login', req.url);
    login.searchParams.set('next', req.nextUrl.pathname);
    return NextResponse.redirect(login);
  }
  return NextResponse.next();
}

export const config = { matcher: ['/account/:path*', '/checkout/:path*', '/admin/:path*'] };

Note: A cookie existing does not mean it is valid. The page or Server Action must still verify the session (see Authentication in the Advance level).

Request and Response Headers

export function middleware(req: NextRequest) {
  const requestHeaders = new Headers(req.headers);
  requestHeaders.set('x-request-id', crypto.randomUUID()); // visible to pages via headers()

  const res = NextResponse.next({ request: { headers: requestHeaders } });
  res.headers.set('X-Frame-Options', 'DENY');
  res.headers.set('Referrer-Policy', 'strict-origin-when-cross-origin');
  return res;
}

Location

Hosting platforms add the visitor's location as headers (for example Vercel sets x-vercel-ip-country, Cloudflare sets cf-ipcountry). Use them to pick a default currency or region:

export function middleware(req: NextRequest) {
  const country = req.headers.get('x-vercel-ip-country') ?? 'IN';
  const res = NextResponse.next();
  if (!req.cookies.has('currency')) res.cookies.set('currency', country === 'IN' ? 'INR' : 'USD');
  return res;
}