The example shows how to filter query parameters from the URL using Edge Middleware.
To see how it works, check the middleware function in middleware.ts
:
import { NextRequest, NextResponse } from 'next/server'const allowedParams = ['allowed']export const config = {matcher: '/',}export default function middleware(req: NextRequest) {const url = req.nextUrllet changed = falseurl.searchParams.forEach((_, key) => {if (!allowedParams.includes(key)) {url.searchParams.delete(key)changed = true}})// Avoid infinite loop by only redirecting if the query// params were changedif (changed) {return NextResponse.redirect(url)// It's also useful to do a rewrite instead of a redirect// return NextResponse.rewrite(url)}}
https://edge-functions-query-params-filter.vercel.app
You can choose from one of the following two methods to use this repository:
Deploy the example using Vercel:
Execute create-next-app
with pnpm to bootstrap the example:
pnpm create next-app --example https://github.com/vercel/examples/tree/main/edge-middleware/query-params-filter query-params-filter
Next, run Next.js in development mode:
pnpm dev
Before URL: http://localhost:3000?a=b&allowed=test
After URL: http://localhost:3000?allowed=test
Deploy it to the cloud with Vercel (Documentation).
The example shows how to filter query parameters from the URL using Edge Middleware.
To see how it works, check the middleware function in middleware.ts
:
import { NextRequest, NextResponse } from 'next/server'const allowedParams = ['allowed']export const config = {matcher: '/',}export default function middleware(req: NextRequest) {const url = req.nextUrllet changed = falseurl.searchParams.forEach((_, key) => {if (!allowedParams.includes(key)) {url.searchParams.delete(key)changed = true}})// Avoid infinite loop by only redirecting if the query// params were changedif (changed) {return NextResponse.redirect(url)// It's also useful to do a rewrite instead of a redirect// return NextResponse.rewrite(url)}}
https://edge-functions-query-params-filter.vercel.app
You can choose from one of the following two methods to use this repository:
Deploy the example using Vercel:
Execute create-next-app
with pnpm to bootstrap the example:
pnpm create next-app --example https://github.com/vercel/examples/tree/main/edge-middleware/query-params-filter query-params-filter
Next, run Next.js in development mode:
pnpm dev
Before URL: http://localhost:3000?a=b&allowed=test
After URL: http://localhost:3000?allowed=test
Deploy it to the cloud with Vercel (Documentation).