서버에서 보내온 jwt 토큰을 쿠키에 저장하는 방법을 적용해보았다. (저번 프리프로젝트 때는 로컬 스토리지에 저장했었다)
설치 : npm install react-cookie
setCookie
함수를 통해 쿠키를 만들고, getCookie
함수를 통해 필요 시 쿠키를 가져오고, removeCookie
함수를 통해 필요 시 쿠키를 지운다
import { Cookies } from 'react-cookie';
const cookies = new Cookies();
export const setCookie = (name: string, value: string, option?: any) => {
return cookies.set(name, value, { ...option });
};
export const getCookie = (name: string) => {
return cookies.get(name);
};
export const removeCookie = (name: string) => {
return cookies.remove(name);
};
각 인자에 대한 설명은 npmjs.com 사이트에 자세히 나와있다.
https://www.npmjs.com/package/react-cookie
name (string): cookie name
value (string|object): save the value and stringify the object if needed
options (object): Support all the cookie options from RFC 6265
path (string): cookie path, use / as the path if you want your cookie to be accessible on all pages
expires (Date): absolute expiration date for the cookie
maxAge (number): relative max age of the cookie from when the client receives it in seconds
domain (string): domain for the cookie (sub.domain.com or .allsubdomains.com)
secure (boolean): Is only accessible through HTTPS?
httpOnly (boolean): Can only the server access the cookie? Note: You cannot get or set httpOnly cookies from the browser, only the server.
sameSite (boolean|none|lax|strict): Strict or Lax enforcement
export const Login = async (LoginForm: ILogin) => {
try {
const response = await axios.post('/login', LoginForm, {
withCredentials: true,
});
const jwtToken = response.data;
setCookie('accessJwtToken', jwtToken); // 쿠키에 토큰 저장
const decodedUserInfo = jwt_decode(jwtToken); // 토큰 decode
localStorage.setItem('userInfo', JSON.stringify(decodedUserInfo)); //토큰에 저장되어있는 userInfo 저장
return response;
} catch {
alert('로그인이 실패했습니다. 정보가 올바른지 다시 확인해주세요');
}
};
setCookie
안에 인자로 jwtToken
을 accessJwtToken
으로 저장하기jwt_decode
: 토큰으로 저장된 내용을 decoding해서 localStorage
에 userInfo`로 저장하기Application 탭에서 확인한 decoded된 토큰
localStroage
에 userInfo
를 저장하고 필요 시 사용(get) 혹은 삭제(remove)할 수있는 함수를 만든다
import { getCookie, removeCookie } from '../cookie';
export const getUser = () => {
const userInfo =
localStorage.getItem('userInfo') && getCookie('accessJwtToken')
? JSON.parse(localStorage.getItem('userInfo')!)
: null;
return userInfo;
};
export const removeUser = () => {
removeCookie('accessJwtToken');
localStorage.clear();
};
...
import { getUser, removeUser } from '../../util/localstorage';
const TopNav = () => {
const userInfo = getUser();
...
const logoutHandler = () => {
alert('로그아웃 하시겠습니까?');
removeUser();
navigate('/');
};
return (
<S.Container>
// ...
</S.Menus>
{userInfo ? (
<S.LogOut>
<h4>반갑습니다 😃</h4>
<Button onClick={() => navigate('/mypage')}>마이 페이지</Button>
<Button onClick={logoutHandler}>로그아웃</Button>
</S.LogOut>
) : (
<S.LogIn>
<Button onClick={() => navigate('/login')}>로그인</Button>
<Button onClick={() => navigate('/signup')}>회원가입</Button>
</S.LogIn>
)}
//..
);
};
export default TopNav;
로그인 하기 전
로그인 후
removeUser()
을 통해 로그아웃 시 localStorage
와 cookie
에 저장되어있는 토큰 정보가 다 삭제 됨