Home > other >  Redirect to login page if the user is unauthenticated
Redirect to login page if the user is unauthenticated

Time:01-10

Why my middleware is crashing after redirecting to my login page?

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

// This function can be marked `async` if using `await` inside
export async function middleware(request: NextRequest) {
  const HAS_COOKIE = isAuthenticated();
  const hostname = request.nextUrl.hostname;
  if (HAS_COOKIE) {
    if (request.nextUrl.pathname.startsWith("/auth")) {
      return NextResponse.redirect("http://localhost:3000/feed");
    }
    return NextResponse.next();
  } else {
    return NextResponse.redirect("http://localhost:3000/auth/signin");
  }
}
export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - api (API routes)
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico (favicon file)
     */
    "/((?!api|_next/static|_next/image|favicon.ico).*)",
  ],
};

This code should redirect if it doesn't detect any cookies.

CodePudding user response:

try using const HAS_COOKIE = request.cookies.has("token");

you are calling a function "isAuthenticated()" which does not exist

CodePudding user response:

What I did was to create an array of private routes and then add a condition in my code

import type { NextFetchEvent, NextRequest } from "next/server";
import { NextResponse } from "next/server";

// loop this
const privateRoutes = ["/feed", "/messages", "/search"];
// This function can be marked `async` if using `await` inside
export async function middleware(request: NextRequest, event: NextFetchEvent) {
  const hostname = request.nextUrl.origin;
  const pathname = request.nextUrl.pathname;
  const HAS_COOKIE = isAuthenticated() // this is just a code that gets the cookie
  // authenticated
  if (HAS_COOKIE) {
    if (pathname.startsWith("/auth")) {
      return NextResponse.redirect(`${hostname}/feed`);
    }
    return NextResponse.next();
  } else {
    if (privateRoutes.includes(pathname)) {
      return NextResponse.redirect(`${hostname}/auth/signin`);
    }
    return NextResponse.next();
  }
}
export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - api (API routes)
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico (favicon file)
     */
    "/((?!api|_next/static|_next/image|favicon.ico).*)",
  ],
};
  • Related