Next.js

[Next.js] middleware.ts

ejunyang 2024. 7. 10. 23:37
const {
    data: { user },
  } = await supabase.auth.getUser();

  // TODO: /api로 시작하는 주소는 무시
  if (
    !user &&
    !request.nextUrl.pathname.startsWith("/api") &&
    !request.nextUrl.pathname.startsWith("/auth")
  ) {
    // no user, potentially respond by redirecting the user to the login page
    const url = request.nextUrl.clone();
    url.pathname = "/auth/login";
    return NextResponse.redirect(url);
  }

 

Supabase의 getUser 메서드를 사용하여 현재 인증된 사용자의 정보를 가져온다.

  • user 객체가 존재하지 않는 경우 (즉, 사용자가 인증되지 않은 경우)
  • 요청된 URL 경로가 /api로 시작하지 않는 경우
  • 요청된 URL 경로가 /auth로 시작하지 않는 경우

조건을 모두 만족하면, 사용자를 로그인 페이지로 리다이렉션한다. NextResponse.redirect(url) 메서드는 사용자를 /auth/login 경로로 리다이렉션 시킨다.