React/NextJS

[ NextJS ] CSR에서 cookie 내용 가져오기

shiro21 2023. 5. 1. 18:21
반응형

클라이언트 쪽에서 httpOnly cookie내용을 가져오는 방법입니다.

이번에 클라이언트 부분에서 쿠키값을 가져와야 하는 상황이 생겨서 쿠키값을 가져오려 하는데, httpOnly 때문인지는 몰라도 js-cookie, cookies-next 등등을 사용해 봐도 빈 토큰값만 가져오는 상황이 발생했습니다.

:: getServerSideProps는 사용하지 않았습니다.

 

useEffect 훅을 사용해서 pages/api/ 내부에 credentials.ts를 생성하여 서버에서 쿠키내용을 가져오게끔 만들었습니다.

 

pages/api/credentials.ts

import { NextApiRequest, NextApiResponse } from "next";
import cookie from "cookie";

export default function handler(req: NextApiRequest, res: NextApiResponse) {

    const cookies = cookie.parse(req.headers.cookie || "");
    const cookieValue = cookies["cookie-name"];

    res.status(200).json({ cookieValue });
}

 

app.tsx

import ...

const App = () => {

    useEffect(() => {
        const fetchCookieValue = async () => {
            const response = await fetch("/api/credentials", { credentials: "include" });
            const data = await response.json();

            if (data.cookieValue === undefined) {
                // 토큰이 아예 없는 경우
                Swal.fire({
                    title: '로그인',
                    text: "로그인 하러 가시겠습니까?",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#3085d6',
                    cancelButtonColor: '#d33',
                    confirmButtonText: '로그인 하러가기',
                    cancelButtonText: "취소"
                })
                .then((result) => {
                    if (result.isConfirmed) router.push("/login");
                    else router.push("/");
                })
            } else {

                await setTokenCookie(data.cookieValue);

                const token: any | null = jwt.decode(data.cookieValue, { complete: true });

                dispatch(userList(token.payload.user[0]));

            }

        };

        fetchCookieValue();
    }, []);
    
    
    return (...);
}
반응형