Middleware Not Redirecting Correctly Based on Token Validity and URL

  Kiến thức lập trình

I’m encountering issues with my middleware function in a Next.js application where redirection based on token validity and URL is not happening as expected. When I have a valid token and navigate to the “/login” URL, it doesn’t redirect me to the dashboard. Additionally, when I delete the token from the cookie, it still shows me the dashboard instead of redirecting me to the login page.

import { NextRequest, NextResponse } from "next/server";
import { verifyAuth } from "~/lib/auth";

export async function middleware(req: NextRequest) {
    // Get the token from the cookie (user-token)
    const token = req.cookies.get("user-token")?.value;

    // Validate the token
    let verifiedToken = null;
    if (token) {
        try {
            verifiedToken = await verifyAuth(token);
        } catch (error) {
            console.error("Error verifying token:", error);
        }
    }

    const isLoginRoute = req.nextUrl.pathname.startsWith('/login');
    const isDashboardRoute = req.nextUrl.pathname.startsWith('/dashboard');

    // If the URL is '/login' and the token is valid, redirect to dashboard
    if (isLoginRoute && verifiedToken) {
        return NextResponse.redirect(new URL('/dashboard', req.url));
    }

    // If the URL is '/login' and the token is invalid, continue to the login page
    if (isLoginRoute && !verifiedToken) {
        return;
    }

    // If the URL is '/dashboard' and the token is valid, continue to the dashboard
    if (isDashboardRoute && verifiedToken) {
        return;
    }

    // If the token is invalid or missing and the URL is not '/login', redirect to login
    if ((!verifiedToken || !token) && !isLoginRoute) {
        return NextResponse.redirect(new URL("/login", req.url));
    }
}

export const config = {
    matcher: ["/dashboard", "/login"],
};

Github repo Link

What I tried:
I attempted to adjust the logic in the middleware function to properly handle redirection based on the presence and validity of the token, as well as the requested URL. However, the behavior is not as expected.

Expected outcome:
I expected the middleware to redirect me to the dashboard when I have a valid token and navigate to the “/login” URL, and to redirect me to the login page when the token is invalid or missing.

New contributor

Ayush Maurya is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT