Middleware redirects to login but want to preserve url params
Answered
Sun bear posted this in #help-forum
Sun bearOP
When a logged-off user lands on a protected route, Next middleware takes care of routing back to login page. However, the middleware has no notion of the search parameters, how do I preserve those throughout the flow so they land back where they started with the correct url search parameters?
Answered by Southern rough shrimp
this is how I do it
let callbackUrl = nextUrl.pathname;
if (nextUrl.search) {
callbackUrl += nextUrl.search;
}
const encodedCallbackUrl = encodeURIComponent(callbackUrl);
const returnUrl = new URL(
`/auth/login?callbackUrl=${encodedCallbackUrl}`,
nextUrl
);
return Response.redirect(returnUrl);9 Replies
@Sun bear When a logged-off user lands on a protected route, Next middleware takes care of routing back to login page. However, the middleware has no notion of the search parameters, how do I preserve those throughout the flow so they land back where they started with the correct url search parameters?
Southern rough shrimp
this is how I do it
let callbackUrl = nextUrl.pathname;
if (nextUrl.search) {
callbackUrl += nextUrl.search;
}
const encodedCallbackUrl = encodeURIComponent(callbackUrl);
const returnUrl = new URL(
`/auth/login?callbackUrl=${encodedCallbackUrl}`,
nextUrl
);
return Response.redirect(returnUrl);Answer
Sun bearOP
oh right, and then from the successful login you use the callback url to send them back to where they were trying to go
thanks!
np!
Sun bearOP
heya do you happen to know the difference between
request.url and request.nextUrl?and also can you remind me how to mark this as answered and give you the credit? 🙏🏼
As well as
Response vs NextResponse fromimport { NextResponse } from "next/server";@Sun bear heya do you happen to know the difference between `request.url` and `request.nextUrl`?
request.url is this one: https://developer.mozilla.org/en-US/docs/Web/API/Request/urlrequest.nextUrl is the extension to the request object that Next.js adds, which has a few extra properties: https://nextjs.org/docs/app/api-reference/functions/next-request#nexturlNextResponse is simply Response extended with a few additional Next.js-specific convenience methods such as NextResponse.rewrite or NextResponse.next: https://nextjs.org/docs/app/api-reference/functions/next-response