0
votes

After reading the following post, https://dev.to/chrsgrrtt/easy-user-authentication-with-next-js-18oe and consulting the following question Using next-iron-session's "withIronSession" with Next.JS to perform simple authentication, I am still unable to access the session using req.session.get('user'). Below is my implementation in a Next.js project:

Create a util

import {withIronSession} from 'next-iron-session';

const cookie = {
    cookieName: process.env.COOKIE_NAME,
    password: process.env.COOKIE_SECRET,
    cookieOptions: {secure: process.env.NODE_ENV === 'production'},
};

export const guard = (handler) => {
    return withIronSession(handler, cookie);
};

export default cookie;

Create an API endpoint

const zlib = require('zlib');
import cookie from '@/utils/cookie';
const fetch = require('node-fetch');
import {withIronSession} from 'next-iron-session';

export default withIronSession(
    async (req, res) => {
        if (req.method === 'POST') {
            try {
                const request = await fetch(
                    process.env.NEXT_PUBLIC_API_BASE_URL + '/api/login',
                    {
                        method: 'post',
                        body: req.body,
                        headers: {
                            'Content-Type': 'application/json',
                            'Origin': req.headers.host || req.headers.origin,
                        },
                    }
                );

                const response = await request.text();
                const {success, data, message} = JSON.parse(response);

                // set JWT in session
                compressor(data, (x) => req.session.set('user', x));

                // persist session value
                await req.session.save();

                // console.log(req.session.get('user'));
                return res.status(201).json({success, message});
            } catch (error) {
                console.log(error);
            }
        }

        return res.status(404).json('Not found');
    },
    cookie
);

Access session data in a page

export const getServerSideProps = guard(async (ctx) => {
    const {req} = ctx;

    const session = req.session.get();

    console.log({session});

    return {redirect: {destination: '/sign-in', permanent: false}};
});

The above terminal log gives an empty object. Is there something am doing wrong??

1
In your API route, where is compressor coming from? If you log req.session.get("user") to the console right after await req.session.save(); what do you get?juliomalves
The compressor is a function that zips using Node's built-in Zlib library the string & later trigger the provided callback. I get the value saved in the session within the user key.mnengwa
@mnengwa did you find an answer?deadcoder0904

1 Answers

0
votes

Try the following:

export const getServerSideProps = guard(async function ({
  req,
  res,

  query,
}) {
//Assuming you have "user" session object
const user = req.session.get("user");
...
});

Harel