How do I set a cookie and rewrite the url with middleware? #34822
-
Is there some way to set a cookie and rewrite the url with a single middleware function? I have a page in my app that is protected. It requires a JWT to be present in the user's cookies. The cookie is set by middleware on that page when some particular query parameters are set. I would like the middleware to not only set the cookie but to also rewrite the url to remove the query parameters once the cookie is set. I can't seem to find any way to do this. Here's some code that hopefully illustrates what I'm trying to do. // _middleware.ts
export function middleware(req: NextRequest) {
const res = NextResponse.next();
if (req.cookies["myCookie"] && validJwt(req.cookies["myCookie"])) {
return res;
}
const token = req.url.searchParams.get("token");
if (validToken(token)) {
const myJwt = createJwt(token);
res.cookie("myCookie", myJwt);
// need to remove the "token" query parameter somehow
return res;
}
return NextResponse.redirect("/"); // send user somewhere else |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 8 replies
-
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 somewhere else
}
} |
Beta Was this translation helpful? Give feedback.
-
Will the inbuilt next cookies not work here? |
Beta Was this translation helpful? Give feedback.
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.