Access cookies in NextJS from server side
Accessing cookies in nextjs from server side can be tricky. In this blog you will learn how to do that
If you want to set an authentication system like jwt, then you have to store your token inside the client(browser). You store them either in localStorage or as a cookie. But when you perform any kind of server-side operation, then you don't have access to the client. So you can't access the cookies from the server-side. Then what is the solution?
The solution.
1import { GetServerSideProps } from 'next'23export const getServerSideProps: GetServerSideProps = async (ctx) => {4 const { req, res } = ctx56 const {cookies} = req78 return { props: { } }9}
I have created a YouTube video about this. You can check that out. If you like this video, please like and subscribe to my channel.
You can access the cookies from the request object inside the getServerSideProps
data fetching method. You can learn about data fetching methods of nextjs from here .
getServerSideProps
method takes context as a parameter. A context is a giant object. Request and Response object is inside the context object.
1const { req, res } = ctx
In the request
object you'll find a cookies
object.
1const { cookies } = req
All your cookies will be inside the cookies
object.
So that's it for this blog.
Shameless Plug
I have made a video about how to build a carousel postcard with React, Material-UI, and Swiper.js. If you are interested you can check the video.
You can also demo the application form here
Please like and subscribe to Cules Coding. It motivates me to create more content like this.
If you have any questions, feel free to contact me on any social media as @thatanjan. Stay safe. Goodbye.
Shameless Plug
I have made an Xbox landing page clone with React and Styled components. I hope you will enjoy it. Please consider like this video and subscribe to my channel.
That's it for this blog. I have tried to explain things simply. If you get stuck, you can ask me questions.
Contacts
- Email: thatanjan@gmail.com
- LinkedIn: @thatanjan
- Portfolio: anjan
- Github: @thatanjan
- Instagram : @thatanjan
- Twitter: @thatanjan
Blogs you might want to read:
- Eslint, prettier setup with TypeScript and react
- What is Client-Side Rendering?
- What is Server Side Rendering?
- Everything you need to know about tree data structure
- 13 reasons why you should use Nextjs
- Beginners guide to quantum computers
Videos might you might want to watch: