An Interest In:
Web News this Week
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
- April 19, 2024
Access cookies in NextJS from server side
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.
import { GetServerSideProps } from 'next'export const getServerSideProps: GetServerSideProps = async (ctx) => { const { req, res } = ctx const {cookies} = req return { props: { } }}
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.
const { req, res } = ctx
In the request
object you'll find a cookies
object.
const { 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, please comment down below.
You can reach out to me on social media as @thatanjan.
Stay safe. Goodbye.
Original Link: https://dev.to/thatanjan/access-cookies-in-nextjs-from-server-side-18fc
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To