DEV Community

Jitesh Dhamaniya
Jitesh Dhamaniya

Posted on

Parse Cookies in Next.js

One thing i love and hate at the same time about node eco-system is, that there is always a package for everything and you have to use npm package/module for everything. Apparently that was also behind the success of nodejs and Ryan hated it and he said it repeatedly. Personally i don't like to use package until it is very essential.

Anyways so recently i was implementing session in nextjs app and i had to parse cookies to get the token which i did set from my login api Route. I used querystring module from nodejs default modules to parse it. Node has some very useful modules and they come along with node, so you always have them with you, whether you use them or not.

Anyways long story short, this is what i used to parse query string.

import qs from 'querystring';
Enter fullscreen mode Exit fullscreen mode
const cookies = qs.decode(ctx.req.headers.cookie, "; ")
Enter fullscreen mode Exit fullscreen mode

ctx.req.headers.cookie would have something like this

token: 'token_cookie_value; Proxy_session=e05hujj6o8k6j9r'
Enter fullscreen mode Exit fullscreen mode

so anything, in this form can be parsed with this code and it would look like this after parsing.

{
  token: 'token_cookie_value',
  Proxy_session: 'e05hujj6o8k6j9r'
}
Enter fullscreen mode Exit fullscreen mode

So thats it. Simple and to the point. You can read more about querystring.parse here
https://nodejs.org/api/querystring.html#querystring_querystring_parse_str_sep_eq_options

Take care till next time.

Top comments (0)