Why is my middleware failing?
// middleware.ts
export function middleware(request: NextRequest) {
if (protectedRoutes.includes(request.nextUrl.pathname)) {
return authMiddleware(request);
}
return NextResponse.next();
}
// middlewares/authMiddleware.ts
export function authMiddleware(request: NextRequest): NextResponse | undefined {
try {
const tokenCookie = request.cookies?.get("token");
// If no token is found in the cookies, return unauthorized response
if (!tokenCookie) {
// ...
}
// Verify the JWT token
const decodedToken = jwt.verify(tokenCookie.value, process.env.JWT_SECRET!);
// If the token is valid, allow the request to continue
return undefined;
} catch (error: any) {
// ... returns
}
This is what my login route looks like to sign the token:
// Generate JWT token with user data
const tokenData = {
id: user.id,
email: user.email,
firstName: user.firstName,
lastName: user.lastName,
};
const token = jwt.sign(tokenData, process.env.JWT_SECRET!, {
expiresIn: rememberMe ? "7d" : "1d",
});
// Create response and set the token as a cookie
const response = NextResponse.json({
message: "Inloggen gelukt.",
success: true,
});
response.cookies.set("token", token, {
httpOnly: true,
sameSite: "strict",
path: "/",
secure: process.env.NODE_ENV === "production", // Set to true only in production
});
return response;
My login itself is successfull and a cookie is being set: Token from cookie: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVC......
<- console logged cookie
But how come that when I try to access a protected route I get the following error: error "Authentication failed."
(coming from authMiddleware.ts
)
I've tried adding or removing parameters from the cookie itself but that is not working.
This does work:
import { NextRequest, NextResponse } from "next/server";
import jwt from "jsonwebtoken";
export async function GET(request: NextRequest): Promise<NextResponse> {
const testPayload = "testkey";
const payload = {
testkey: "data",
};
const token = jwt.sign(payload, testPayload);
console.log(token);
const decoded = jwt.verify(token, testPayload);
console.log(decoded);
return NextResponse.json({ message: "Success" });
}