← Back to Guides

Learn how to filter query parameters in your Edge 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 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);
  }
}

Last updated on June 21, 2024