React - next js login redirect
naver, 쿠팡과 같은 웹 사이트에서 로그인을 할 때, network를 보면... 순간적으로 한 페이지를 갔다가 넘어가는 것을 볼 수 있다. 컴퓨터의 성능이 좋다면 너무 빨리 지나 가지만, 어떤 사이트를 들렀다가 redirect를 하는것 같다.
# object
- 대형 웹사이트 로그인 과정 확인
- next js를 통해서 구현 해보기
만약 어떤 사이트를 들리지 않고, 그냥 로그인을 한다면 무슨일이 일어나게 되는가??
다른 사이트를 통해서 가지 않는다면 React에서 통신을 할 때, 어떤 payload를 보냈는지 알 수 있다. 즉, 로그인 할 때 사용했던 id와 password가 남아있다.(브라우져 network에서 확인 가능)
## Next js config file 설정
next js는 어떤 특정 사이트를 들어갔을 때, 다른 페이지로 redirect하는 기능이 있다. next.config.js 파일에 기술을 하면 되는데,
이렇게 redirect() {} 추가 해주면 된다.
*source: 페이지 이동 경로
*destination: source 페이지로 들어왔을 때, redirect 시킬 페이지 주소
*permanent: true는 308 redirect(with cached) / false는 307 redirect(without cached
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
async redirects() {
return [
{ source: "/signin/auth", destination: "/", permanent: true },
];
},
};
module.exports = nextConfig;
위와같이 config file을 설정을 하고 나서 로그인 로직을 보면, 로그인이 sucess 하고 config 파일에 설정해놓은 source path로 이동을 시킨다.
const data = {
login_id: userInfo.userId,
password: userInfo.password,
site: "admin",
};
const res = await dispatch(signin(data));
if (res) {
dispatch(clear());
if (
router.query.redirect &&
typeof router.query.redirect === "string"
) {
router.replace(`/signin/auth/${router.query.redirect}`);
} else {
router.replace("/signin/auth");
}
}
로그인이 성공 되면 redirect(status 308) 되는것을 알 수 있고, 브라우져에 로그인 했던 아이디와 비밀번호숨길 수 있다.
### referenct
https://nextjs.org/docs/api-reference/next.config.js/redirects
next.config.js: Redirects | Next.js
Add redirects to your Next.js app.
nextjs.org