Next.js Protected Route 설정

김태규·2024년 9월 3일

Aper 프로젝트

목록 보기
4/4

이 포스팅은 NextJS 에서 Protected Route 설정을 하는 세가지 방법에 대해 포스팅 합니다.
방법은 크게 세 가지로 클라이언트, 서버, 미들웨어를 활용하는 방법이 있습니다.

클라이언트 라우트 프로텍트

먼저, @/Utils/Auth.ts를 만들고, 해당 파일에 인증 절차를 만든다. 인증 절차는 프로젝트마다 다를 수 있기 때문에 생략하고, 결과적으로 isAuthenticated를 반환할 수 있도록 작성한다.

이후 렌더링 시 클라이언트 측에서 isAuthenticated를 확인할 수 있도록 useEffect 훅에서 인증되지 않은 사용자를 리디렉션 시키고, 인증받은 사용자만이 컴포넌트를 랜더링 받을 수 있도록 한다.

// isAuth.tsx

"use client";
import { isAuthenticated } from "@/Utils/Auth";
import { useEffect } from "react";
import { redirect } from "next/navigation";


export default function isAuth(Component: any) {
  return function IsAuth(props: any) {
    const auth = isAuthenticated;


    useEffect(() => {
      if (!auth) {
        return redirect("/");
      }
    }, []);


    if (!auth) {
      return null;
    }

    return <Component {...props} />;
  };
}

작성된 isAuth 함수는 아래와 같이 활용할 수 있다.

// dashboard/page.tsx

import isAuth from "@/Components/isAuth";

const Dashboard = () => {
  return (
    <main className=" h-screen flex justify-center items-center">
      <p>Dashboard</p>
    </main>
  );
};


export default isAuth(Dashboard);

서버 라우트 프로텍트

서버는 조금 더 단순하다. 인증되었는지 여부를 서버에서 확인하고 리디렉션 시켜주기만 하면 된다.

// admin/page.tsx

import {isAuthenticated} from '@/Utils/Auth';
import { redirect } from 'next/navigation';


const Admin = () => {
  const isAuth = isAuthenticated;


  if(!isAuth) {
      redirect("/");
  }
  
  return (
    <main>
      <h1>Admin Page</h1>
    </main>
  );
};


export default Admin;

미들웨어 라우트 프로택트

마지막으로 미들웨어를 이용한 방법은 루트 디렉토리에 있는 middleware.ts 파일에 설정을 해주어야 한다.

//middleware.ts

import { isAuthenticated } from "@/Utils/Auth";
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";


const protectedRoutes = ["/settings"];


export default function middleware(req: NextRequest) {
  if (!isAuthenticated && protectedRoutes.includes(req.nextUrl.pathname)) {
    const absoluteURL = new URL("/", req.nextUrl.origin);
    return NextResponse.redirect(absoluteURL.toString());
  }
}

이처럼 보호할 라우트를 설정하고, 보호 조건을 걸어주면 해당 라우트를 보호할 수 있다.

참고 링크

https://www.freecodecamp.org/news/secure-routes-in-next-js/

profile
Frontend, Mobile Developer

0개의 댓글