Currently, I am utilizing NextJS for server-side rendering and looking to secure certain "admin" pages where CRUD operations on my DB can be performed.
After successfully implementing authentication on my website using passport and next-connect based on a tutorial from here, I now want to prevent any unauthorized "edit" operations.
I believe the most effective way to achieve this is by checking if req.user exists in my /page/API files, but it's not functioning as expected. At present, req.user returns undefined, despite the cookie being stored on my device after successful login.
I have encountered similar issues on Stackoverflow, albeit few related to Nextjs, and none of them provided a solution that worked for me, possibly due to my limited experience in JS and authentication.
Upon logging in through the auth API, req.user exists and the cookie is successfully stored:
/pages/api/auth
req.user => OK
import nextConnect from 'next-connect';
import middleware from '../../middleware/middleware';
import passport from '../../lib/passport';
import { extractUser } from '../../lib/api-helpers';
const handler = nextConnect();
handler.use(middleware);
handler.post(passport.authenticate('local'), (req, res) => {
res.json({ user: extractUser(req.user) });
console.log(req.user) // IT WORKS
});
export default handler;
However, when logged in and fetching data through any API, req.user is returned as undefined.
An example of one of my API file:
/page/api/getList.js
import nextConnect from 'next-connect';
import middleware from '../../middleware/middleware';
const handler = nextConnect();
handler.use(middleware);
handler.post(async (req, res) => {
console.log(req.user) // UNDEFINED
// operation to perform if req.user exists
});
export default handler;
If necessary, here are snippets of my session middleware :
middleware/session.js
import session from 'express-session';
import connectMongo from 'connect-mongo';
import * as uuid from 'uuid';
const MongoStore = connectMongo(session);
export default function sessionMiddleware(req, res, next) {
const mongoStore = new MongoStore({
client: req.dbClient,
stringify: false,
});
return session({
secret: "this gonna rocks !",
store: mongoStore,
resave: true,
saveUninitialized: true,
cookie: {
maxAge: (1000 * 60 * 100)
}
})(req, res, next);
}
and my common middleware :
import nextConnect from 'next-connect';
import passport from 'passport';
import database from './database';
import session from './session';
const middleware = nextConnect();
middleware
.use(database)
.use(session)
.use(passport.initialize()) // passport middleware handles authentication, populating req.user
.use(passport.session());
export default middleware;
I'm unsure where I might be going wrong. Can someone guide me on how to verify user authentication before performing any DB operation?
Many thanks!