Use next cookies to use token in getserversideprops

next-cookies is not just an npm package. It’s a life saviour. This package solved a big problem that NextJS developer faced. Browser storage in all SSR, SSG functions. The most common use case for accessing cookies in getServerSideProps is when you want to fetch data from an API that requires token.

In order to give token to a page you can pass it in query but that not secure. If you store it in localStorage you can’t access it in getServerSideProps. But, if you store the token in cookies using next-cookies you can access it everywhere in your app. Let’s write a few lines of code

npm i -g next-cookies
import cookies from 'next-cookies'
Const {token} = cookies(context)
document.cookie = `foo=bar; path=/`;

First line you will write in terminal to install the package. Second line to import the cookies function wherever required. And third is in getserversideprops you pass context and you destructure the token from it. Use 4th line to set cookie. And if you wish to delete a cookie just set Max age 0.

That’s it for today’s lesson. Checkout the official documentation for more detailed reference

manorinfinity Written by:

Complex Problem Solver, Outloud Thinker, An Outstanding Writer, and a very curious human being

Be First to Comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.