lib/api/user/user.ts
...
const handleLogin = (): void => {
const currentUrl = window.location.href; // 현재 URL 저장
localStorage.setItem('lastVisitedPage', currentUrl);
window.location.href = socialLoginForKaKaoUrl;
};
...
app/callback/page.ts
import { useEffect } from 'react';
import { useRouter } from 'next/router';
const CallbackPage = () => {
const router = useRouter();
useEffect(() => {
const lastVisitedPage = localStorage.getItem('lastVisitedPage') || '/';
localStorage.removeItem('lastVisitedPage'); // 사용 후 제거
router.replace(lastVisitedPage);
}, [router]);
return <div>로그인 중...</div>;
};
export default CallbackPage;
lib/api/user/user.ts
import { useEffect, useState } from 'react';
import { useRouter } from 'next/router';
const socialLoginForKaKaoUrl = `http://localhost:8080/oauth2/authorization/kakao`;
const socialLogoutUrl = `http://localhost:8080/logout`;
export const useAuth = () => {
const router = useRouter();
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [nickname, setNickname] = useState<string | null>(null);
const [profileImage, setProfileImage] = useState<string | null>(null);
useEffect(() => {
fetch('http://localhost:8080/user/info', {
method: 'GET',
credentials: 'include',
})
.then((response) => {
if (response.ok) {
return response.json();
}
throw new Error('Not logged in');
})
.then((data) => {
setIsLoggedIn(true);
setNickname(data.nickname);
setProfileImage(data.profileImage);
// 로그인 성공 후 리디렉트 처리
if (router.pathname === '/callback') {
const lastVisitedPage = localStorage.getItem('lastVisitedPage') || '/';
localStorage.removeItem('lastVisitedPage');
router.replace(lastVisitedPage);
}
})
.catch(() => {
setIsLoggedIn(false);
setNickname(null);
setProfileImage(null);
});
}, [router]);
const handleLogin = (): void => {
const currentUrl = window.location.pathname;
localStorage.setItem('lastVisitedPage', currentUrl);
window.location.href = socialLoginForKaKaoUrl;
};
const handleLogout = (): void => {
fetch(socialLogoutUrl, {
method: 'GET',
credentials: 'include',
})
.then(() => {
setIsLoggedIn(false);
window.location.href = '/';
})
.catch((error) => {
console.error('Logout error:', error);
});
};
return { isLoggedIn, nickname, profileImage, handleLogin, handleLogout };
};
CallbackPage
유지보수 용이, 높은 확장성
useAuth
인증 로직과 리디렉트 로직이 섞임