Filtering query parameters

Learn how to filter query parameters in your Edge Middleware.
Last updated on August 2, 2024
Middleware

The following example shows how to filter query parameters in your Edge Middleware.

Your middleware file should be placed at the root of your project. If you are using the src directory, the file should be placed in the src directory.

middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
 
const allowedParams = ['allowed'];
 
export const config = {
  matcher: '/',
};
 
export default function middleware(request: NextRequest) {
  const url = request.nextUrl;
  let changed = false;
 
  url.searchParams.forEach((_, key) => {
    if (!allowedParams.includes(key)) {
      url.searchParams.delete(key);
      changed = true;
    }
  });
 
  // Avoid infinite loop by only redirecting if the query
  // params were changed
  if (changed) {
    return NextResponse.rewrite(url);
  }
}