In a Next.js middleware, you can get URL query parameters by accessing the "nextUrl.searchParams" property on the NextRequest object, which is passed to the middleware function as the first argument:

// middleware.js
export function middleware(request) {
    const queryParams = request.nextUrl.searchParams; // `URLSearchParams`
    const foo = queryParams.get('foo');
    // ...
}

The "searchParams" property actually returns an instance of the JavaScript URLSearchParams object.

Alternatively, you may achieve the same by using the NextRequest.url property in the following way:

// middleware.js
export function middleware(request) {
    const url = new URL(request.url);
    const queryParams = url.searchParams; // `URLSearchParams`
    const foo = queryParams.get('foo');
    // ...
}

In either case, you can call any method available on the URLSearchParams object. For instance, as you can see in the examples above, the URLSearchParams.get() method allows you to get the value of the specified query parameter, returning one of the following:

  1. String value if the key exists in the URL, or;
  2. null if the key is not present in the URL.