I am very new and migrating to Next.js. Maybe this is a dumb question but I did not find much information on it. So far I have successfully made Next.js work with express but now I want to be able to manage session information. I used to use express-session middleware, which attaches session data to the req
object of express on every HTTP request, but I don't know how to get it works with Next.js.
By the way, please show me how to access to the req
object from a React component also.
By the way, please show me how to access to the
req
object from a React component also.
You can't, data should be extracted in getInitialProps.
Here's an example on how to do authentication / holding session state: https://github.com/zeit/next.js/tree/canary/examples/with-cookie-auth
I am very new and migrating to Next.js. Maybe this is a dumb question but I did not find much information on it. So far I have successfully made Next.js work with express but now I want to be able to manage session information. I used to use express-session middleware, which attaches session data to the
req
object of express on every HTTP request, but I don't know how to get it works with Next.js.By the way, please show me how to access to the
req
object from a React component also.
Hi, what you have to only do is to pass the cookies to the server so when it again hits the server the session will not be undefined so the cookies you have recieved in your request will be passed to the server by this way. I have implemented it using req object i got in context object so you can try this most probably this works if you code is correct.
```
static async getInitialProps(ctx) {
try{
let url = ctx.req ? ctx.req.protocol + '://' + ctx.req.get('host') : '';
const res = await fetch(url + '/dashboardData/',{
headers: {
cookie: ctx.req ? ctx.req.headers.cookie : null ,
}
})
const json = await res.json()
if (json && json.error) {
return { 'error': 'Something went wrong' }
}
return {
data : json.data
}
}catch(error){
console.log(error);
}
}
@nitin-malhotra you are the hero we don't deserve. Thank you!
@nitin-malhotra with the user data you do so you don't ask for it again and again?
Do you save it in localStorage when you login? or is there some other way?
Since this question is the top result for "nextjs session" on google, I thought I would add that nowadays you have multiple solutions for handling sessions in Next.js:
Good luck!
Most helpful comment
Since this question is the top result for "nextjs session" on google, I thought I would add that nowadays you have multiple solutions for handling sessions in Next.js:
Good luck!