Reputation: 11
im trying to take the token from the url of a route in my site but the middleware log 3 times the token and in the second time the token is null while i logged the req url my url that im in is http://localhost:3000/auth/newPassword but in the second render its http://localhost:3000/_next/static/chunks/pages/auth/newPassword.js?ts=1667894719054 someone knows what is the problem here?
i sent an email for new password to the user email with query token in the url i wan the middleware to check if the token is valid before accessing the new password route and then verify it there but its render null for me in the second time and that crashed my project
import { NextResponse, NextRequest } from "next/server";
import { verify } from "jsonwebtoken";
const secret = process.env.JWT_SECRET!;
export default async function middleware(req: NextRequest) {
const url = req.url;
const token = await req.nextUrl.searchParams.get("token")!;
const cookies = req.cookies;
if (url.includes("/auth/newPassword")) {
console.log(url);
if (token === undefined) {
return NextResponse.redirect("http://localhost:3000/auth/signin");
}
try {
verify(token, secret);
return NextResponse.next();
} catch (e) {
return NextResponse.redirect("http://localhost:3000/auth/signin");
}
}
}
Upvotes: 0
Views: 643
Reputation: 7256
That because when you load http://localhost:3000/auth/newPassword
next will make a request to http://localhost:3000/_next/static/chunks/pages/auth/newPassword.js?ts=1667894719054
(i guess for hydration), this file basically contains only react related javascript stuff, and you wont that your middleware will match this route, while currently it is (because it contains auth/newPassword
).
I sueggest to use middleware with negative matchers :
export const config = {
matcher: [
/*
* Match all paths except for:
* 1. /api routes
* 2. /_next (Next.js internals)
* 3. /fonts (inside /public)
* 4. /examples (inside /public)
* 5. all root files inside /public (e.g. /favicon.ico)
*/
'/((?!api|_next|fonts|500|examples|[\\w-]+\\.\\w+).*)',
],
};
export default function middleware(req: NextRequest) {
const url = req.url;
const token = await req.nextUrl.searchParams.get("token")!;
const cookies = req.cookies;
if (url.includes("/auth/newPassword")) {
console.log(url);
if (token === undefined) {
return NextResponse.redirect("http://localhost:3000/auth/signin");
}
try {
verify(token, secret);
return NextResponse.next();
} catch (e) {
return NextResponse.redirect("http://localhost:3000/auth/signin");
}
}
}
Upvotes: 0