Skip to content

Latest commit

 

History

History
84 lines (60 loc) · 2.56 KB

File metadata and controls

84 lines (60 loc) · 2.56 KB
name slug description framework useCase css deployUrl demoUrl relatedTemplates
Filtering Query Parameters
edge-functions-filter-query-params
Learn how to filter query params in Edge Middleware.
Next.js
Edge Middleware
Documentation
Tailwind
ab-testing-simple

Filtering Query Parameters

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.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.redirect(url)
    // It's also useful to do a rewrite instead of a redirect
    // return NextResponse.rewrite(url)
  }
}

Demo

https://edge-functions-query-params-filter.vercel.app

How to Use

You can choose from one of the following two methods to use this repository:

One-Click Deploy

Deploy the example using Vercel:

Deploy with Vercel

Clone and Deploy

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).