For example, if the user is on the page http://localhost/article/1
Assign ?modal=auth to the current URL
http://localhost/article/1?modal=auth
Here is my middleware. At the moment, if the user is not authorized, it redirects to /?modal=auth
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export async function middleware(req: NextRequest) {
const token = req.cookies.get("session")?.value || "";
const res = await fetch(`${process.env.HOST}/api/user/me`, {
headers: {
cookie: `session=${token}`,
},
});
const user = await res.json();
const { pathname } = req.nextUrl;
if (!token || res.status === 403) {
return NextResponse.redirect(new URL("/?modal=auth", req.url));
}
return NextResponse.next();
}
export const config = {
matcher: [
"/my",
"/bookmarks",
"/new"
],
};
For example, if the user is on the page http://localhost/article/1
Assign ?modal=auth to the current URL
http://localhost/article/1?modal=auth
Here is my middleware. At the moment, if the user is not authorized, it redirects to /?modal=auth
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export async function middleware(req: NextRequest) {
const token = req.cookies.get("session")?.value || "";
const res = await fetch(`${process.env.HOST}/api/user/me`, {
headers: {
cookie: `session=${token}`,
},
});
const user = await res.json();
const { pathname } = req.nextUrl;
if (!token || res.status === 403) {
return NextResponse.redirect(new URL("/?modal=auth", req.url));
}
return NextResponse.next();
}
export const config = {
matcher: [
"/my",
"/bookmarks",
"/new"
],
};
Share
Improve this question
asked Mar 19 at 7:33
FreeFree
431 silver badge5 bronze badges
0
2 Answers
Reset to default 1Right now you are precisely redirecting to /?modal=auth
Create a concatenated URL instead:
const url = request.nextUrl.clone();
if (!token || res.status === 403) {
return NextResponse.redirect(url.origin + "/?modal=auth");
}
Or you can use this method present in Next docs:
if (!token || res.status === 403) {
// Given an incoming request...
const loginUrl = request.nextUrl.clone();
loginUrl.searchParams.set('modal',"auth");
// And redirect to the new URL
return NextResponse.redirect(loginUrl)
}
new URL("/?modal=auth", req.url)
A relative URL that starts with a leading slash, refers to the domain root. If you want to overwrite the query string, but keep the current path, you need to use ?modal=auth
instead.