Next.js Discord

Discord Forum

JWT auth middleware failing

Unanswered
Pteromalid wasp posted this in #help-forum
Open in Discord
Pteromalid waspOP
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)

0 Replies