Skip to content

How do I set a cookie and rewrite the url with middleware? #34822

Answered by thibautsabot
lukevella asked this question in Help
Discussion options

You must be logged in to vote

Hello.

Did you check out this example: https://github.com/vercel/examples/tree/main/edge-functions/query-params-filter ?

Basically, you remove the token form the searchParams and you redirect to the URL.

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

export function middleware(req: NextRequest) {
  const url = req.nextUrl
  let changed = false

  const token = url.searchParams.get("token");
  if (validToken(token)) {
    url.searchParams.delete('token')
    changed = true
  }

  // Avoid infinite loop by only redirecting if the query params were changed
  if (changed) {
    return NextResponse.redirect(url)
  } else {
    return NextResponse.redirect("/");  // send user somewher…

Replies: 2 comments 8 replies

Comment options

You must be logged in to vote
6 replies
@thibautsabot
Comment options

@lukevella
Comment options

@EarthlingDavey
Comment options

@cameronthrntn
Comment options

@asc33nzio
Comment options

Answer selected by lukevella
Comment options

You must be logged in to vote
2 replies
@Raggok
Comment options

@steve-marmalade
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Help
Labels
None yet
8 participants