Next.js Discord

Discord Forum

Can I read a session from getServerSideProps()?

Unanswered
Chinese Alligator posted this in #help-forum
Open in Discord
Chinese AlligatorOP
I set the session using something like this:

interface CustomSession extends IronSession {
  user?: IUser;
}

const handler = async (
    req: NextApiRequest,
    res: NextApiResponse
  ) => {
   (req.session as CustomSession).user = user;
    await req.session.save();
  }

export default withSessionRoute(handler);


where withSessionRoute is:


const withSessionRoute = (handler: NextApiHandler) => {
    return withIronSessionApiRoute(handler, ironOptions);
}


how do I read this session from getServerSideProps?

export const getServerSideProps: GetServerSideProps<{result: IArticleResult}> = async (context) => {
  const { params, req, res } = context;
   // req.session is undefined
  // ...

10 Replies

it’s iron session
it’s kinda light weight Auth.js
iron session is just a wrapper around auth headers / cookies
@Chinese Alligator so you need a work around if you use App Router. some one asked the same question before.
Chinese AlligatorOP
thank you guys managed to do that with:

export const getServerSideProps = withIronSessionSsr(
        async function GetServerSideProps(context: any) {
           
            const { req } = context;
            
            console.log('session = ', req.session);

            return {
                props: {
                result: ''
            }
        }
    },
    ironOptions
)
Chinese AlligatorOP
does this run on _app.tsx? it isn't working over there. I'd like to fetch data and pass to a global menu in the web site
@tafutada777 @Marchy
Chinese AlligatorOP
soemthing similar seems to work on app folder but not page yet https://github.com/vercel/next.js/discussions/10874
Chinese AlligatorOP
since getServerSideProps() doesn't work in _app.tsx and i need to get data from the logged user, to fill a menu in the _app.tsx file (so that that menu is shown everywhere in the web site) the way to go is create a file in /api read the data to session, return a JSON and from the component read this JSON from API using fetch() function. is this the usual approach to do that? is there something better/"elegant"?