로고로고

JWT를 활용한 로그인 기능 구현 (Next.js)

2025년 7월 2일

위리브 프로젝트 - 로그인 기능 구현을 블로그 글로 정리

 

 

 

 

 

export const postLogin = async (form: LoginForm) => {
  const res = await axios.post("/api/login", form, {
    withCredentials: true, 
  });
  return res.data;
};
const onSubmit = async (data: LoginForm) => {
  try {
    await postLogin(data);
    toast.success("로그인 성공!");
    router.push("/dashboard");
  } catch (e) {
    toast.error("로그인 실패");
  }
};

 

 

export const getServerSideProps: GetServerSideProps = async ({ req }) => {
  const cookies = cookie.parse(req.headers.cookie || "");
  const token = cookies["access_token"];

  if (!token) {
    return { redirect: { destination: "/", permanent: false } };
  }

  const decoded = jwt.verify(token, process.env.JWT_SECRET!) as JwtPayload;

  return {
    props: { user: decoded }, 
  };
};

 

 

interface AuthState {
  user: User | null;
  setUser: (user: User) => void;
}

export const useAuthStore = create<AuthState>((set) => ({
  user: null,
  setUser: (user) => set({ user }),
}));

 

 

export const postLogout = () => {
  return axios.post("/api/logout", null, { withCredentials: true });
};
const handleLogout = async () => {
  await postLogout();
  useAuthStore.getState().setUser(null);
  router.push("/");
};