Skip to content

Latest commit

 

History

History
 
 

query-params-filter

name slug description framework useCase css deployUrl demoUrl
Filtering Query Parameters
edge-functions-filter-query-params
Learn how to filter query params in Edge Functions.
Next.js
Edge Functions
Documentation
Tailwind

Filtering Query Parameters

The example shows how to filter query parameters from the URL using Edge Functions.

To see how it works, check the middleware function in pages/_middleware.ts:

import { NextRequest, NextResponse } from 'next/server'

const allowedParams = ['allowed']

export 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)
  }
}

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 npm or Yarn to bootstrap the example:

npx create-next-app --example https://github.com/vercel/examples/tree/main/edge-functions/query-params-filter query-params-filter
# or
yarn create next-app --example https://github.com/vercel/examples/tree/main/edge-functions/query-params-filter query-params-filter

Next, run Next.js in development mode:

npm install
npm run dev

# or

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