'next.js iron-session req.session.user is undefined
I'm making a dashboard for my team's bot using next.js and iron-session.
However, when I save the session and check it, req.session.user is undefined.
How can I fix this error???
Here is my code with the error:
page/auth.js:
Auth.getInitialProps = async ({ query }) => {
//console.log(query.code)
const result = await axios.get(`https://lunasite.prnm789.repl.co/api/sign/in?code=${query.code}`)
const { access_token, refresh_token } = await result.data
const newsession = await axios.post(`https://lunasite.prnm789.repl.co/api/session/new`, {
access_token: access_token,
refresh_token: refresh_token
})
...
}
page/api/session/new.js:
import { withIronSessionApiRoute } from 'iron-session/next'
import { sessionOptions } from '../../../lib/config'
export default withIronSessionApiRoute(userRoute, sessionOptions)
async function userRoute(req, res) {
if (req.method == "POST") {
const { access_token, refresh_token } = req.body
...
try {
req.session.user = {
isLoggedIn: true,
access_token: access_token,
refresh_token: refresh_token
}
await req.session.save()
...
} catch(e) {
...
}
} else {
...
}
}
lib/config.js:
export const sessionOptions = {
cookieName: "luna_cookie",
password: process.env.sessionCookiePass,
cookieOptions: {
secure: process.env.NODE_ENV === "production",
maxAge: 604800 - 60
},
}
page/api/session/get.js:
import { withIronSessionApiRoute } from "iron-session/next";
import { sessionOptions } from "../../../lib/config";
export default withIronSessionApiRoute(getRoute, sessionOptions);
function getRoute(req, res) {
res.send(String(req.session.user))
}
Solution 1:[1]
Can you check if your front-end domain and network request url are the same for me? I had this problem which I set baseurl for my request from NEXT_PUBLIC_VERCEL_URL and it was an autogenerated url for that unique deployment, long story short my session was saved on main domain but my requests were on something else. as soon as I replaced it with an absolute path all my problems went away
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Eric Aya |