I'm currently working on a dashboard for our team's bot that utilizes next.js and iron-session.
However, I've run into an issue where req.session.user is showing up as undefined when I try to save the session. How can I go about fixing this error?
Below is the snippet of code where the error occurs:
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))
}