DEV Community

Jitesh Dhamaniya
Jitesh Dhamaniya

Posted on

4 2

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.

Image of Wix Studio

2025: Your year to build apps that sell

Dive into hands-on resources and actionable strategies designed to help you build and sell apps on the Wix App Market.

Get started

Top comments (0)

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay