Redirect issue when accessing protected routes with an active session supabase

109 Views Asked by At

I am currently working on a middleware function in my Next.js application that handles authentication and redirects users based on their session status in supabase. However, I am encountering an issue where, if a user has an active session and tries to access a protected route (e.g., "/app"), they are redirected back to the home page instead of the intended route. Similarly, if a user with an active session tries to access the login page ("/login"), they are also redirected back to the home page instead of the app page. I have checked my code and I'm not sure what might be causing this issue. Any help in understanding and resolving this bug would be greatly appreciated. This is my middleware function :

import { createMiddlewareClient } from "@supabase/auth-helpers-nextjs";
import { NextResponse } from "next/server";

import type { NextRequest } from "next/server";

export async function middleware(req: NextRequest) {
  const res = NextResponse.next();
  const supabase = createMiddlewareClient({ req, res });
  
  // Get the session before running the middleware logic
  const { data: { session } } = await supabase.auth.getSession();

  // if session is signed in and the current path is /login redirect the session to /app
  if (session && req.nextUrl.pathname.startsWith("/login")) {
    return NextResponse.redirect(new URL("/app", req.url));
  }

  // if session is not signed in and the current path is not / redirect the session to /
  if (!session && req.nextUrl.pathname !== "/") {
    return NextResponse.redirect(new URL("/", req.url));
  }
  
  return res;
}

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

There are 0 best solutions below