Next.js Discord

Discord Forum

NextJs 14 middleware redirect issue: User Keeps getting redirected to login after successful Sign-In

Unanswered
Mahati Singh posted this in #help-forum
Open in Discord
I'm working on a Next.js 14 project and facing an issue with user authentication and redirection. After a user signs in, they should be redirected to the dashboard page. However, they are being redirected back to the /login page. I suspect the original middleware redirect might be cached, causing subsequent requests to redirect to the /login page. How can I resolve this?

middleware.ts

import { jwtVerify } from "jose";
import { NextResponse, NextRequest } from "next/server";

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

// verify if user is authenticated
const isAuthenticated = async (sessionToken: string) => {
  try {
    const userSession = await jwtVerify(
      sessionToken,
      new TextEncoder().encode(process.env.JWT_SECRET)
    );
    return userSession;
  } catch (e) {
    return false;
  }
};


export async function middleware(request: NextRequest) {
  try {
    const sessionToken = request.cookies.get("sessionToken")?.value || null;

    if (!sessionToken) {
     
      if (request.nextUrl.pathname === "/login") {
        return NextResponse.next();
      }
      
      return NextResponse.redirect(new URL("/login", request.url));
    }

    // If there is a sessionToken, check if it is valid
    let userSession = null;
    if (sessionToken) {
      userSession = await isAuthenticated(sessionToken);
      if (!userSession) {
        return NextResponse.redirect(new URL("/login", request.url));
      }
    }


    return NextResponse.next();
  } catch (e) {
    return NextResponse.redirect(new URL("/login", request.url));
  }
}


"use client";
import Link from "next/link";
export default function Navbar() {  
  return (
      <div>
        <nav>
          <ul>
            <li>
              <Link href="/dashboard">
                Dashboard
              </Link>
            </li>
          </ul>
        </nav>
      </div>
  );
}

3 Replies

Devon Rex
I am also facing similar problem. I hope someone can help.
Harlequin
I have the same issue but i suspect its about my two RootLayouts (one for secured area and one for public webpage incl. login). When i successfully log in my server action is doing a redirect to the dashboard of the app but because there is a RootLayout Switch, there is a full page reload which is also documented.

Do you guys have the same setup?
Harlequin