HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
🧚
[1기]최종 프로젝트 데브코스
/
🏄‍♂️
[팀8] 어푸(Ah puh) - Surf
/
🔫
Trouble shooting
/
document.cookie 문제

document.cookie 문제

WHO
STATUS
solved
WHEN
Dec 14, 2021

👿 Problem

Cookie.get으로 cookie를 가져올 경우, ssr 일 땐 document가 존재하지 않기 때문에 undefined로 출력된다.
JSON.parse() 함수 자체에는 문제가 없지만, undefined가 인자로 들어가게 되어 아래 에러가 출력된다.
Uncaught SyntaxError: Unexpected token u in JSON at position 0
  • JSON에서 0번째의 u시작하는 문자열을 parse하려다가 에러를 throw 하는 것을 의미한다.
  • JSON.parse(undefined)

😇 Solution

  1. useEffect() 내부에서 cookie를 핸들링하는 로직을 추가한다.
    1. // ex) const [user,setUser]=useState('') useEffect(()=>{ setUser(JSON.parse(Cookies.get('user')) },[]) const {data}=useGetUser(user.userId) /* parsing한 값을 활용하기 위해서는 반드시 State를 활용해야 한다. state가 아닌 일반 변수를 사용하면 안된다. useEffect() 외부에서도 사용하기 위해 외부에 변수를 선언해야 하지만, 그렇게 하는 경우, js 인터프리터가 평가하는 과정에서 useEffect() 안에 있는 정의를 거치지 않기 때문에, 선언만 이뤄진 상태에서 실행 즉, undefined가 출력된다. */
  1. 혹은 csr 일 때 사용한다.
      • 컴포넌트가 mounted된 후에는 ssr로 실행되기 때문에 document가 존재하게 되어 참조가 가능하다.

🧐 Reference

Troubleshoot 'Uncaught SyntaxError: Unexpected token u in JSON at position 0'
The 'Uncaught SyntaxError: Unexpected token u in JSON at position 0' error is caused when the client has been asked to execute JSON.parse() on a string beginning with u instead of the stringified object it was expecting. Usually this is a stringified version of the undefined primitive.
Troubleshoot 'Uncaught SyntaxError: Unexpected token u in JSON at position 0'
https://developers.suitecommerce.com/troubleshooting-uncaught-syntaxerror-unexpected-token-u-in-json-at-position-0.html
Troubleshoot 'Uncaught SyntaxError: Unexpected token u in JSON at position 0'