I have set up a NextJS frontend application with a backend powered by NodeJS and ExpressJS. Authentication and authorization are handled using JWT token-based system, where the backend server sets the token and the frontend server validates it to grant access to private routes. Everything runs smoothly locally, but after deployment, I encountered an issue wherein cookies are not being sent from the frontend to access private routes. The middleware in NextJS cannot seem to access the cookies.
Implementation in middleware.js in NextJS:
import { NextResponse } from 'next/server';
import react from 'react';
const middleware = (req) => {
let verify = req.cookies.get("jwt")
let url = req.url
if (!verify && url.includes("/dashboard")) {
return NextResponse.redirect(`${process.env.NEXT_URL}/login`);
}
};
export default middleware;
Configuration for CORS in index.js of Express application:
if(process.env.NODE_ENV==="Production"){
corsOptions = {
credentials: true, origin:process.env.ORIGIN_URL
};
}else{
corsOptions = {
credentials: true, origin:true
};
}
app.use(cors(corsOptions))
ProtectMiddleware function in Express JS:
const protect = asyncHandler(async (req, res, next) => {
let token;
token=req.cookies?.jwt
console.log(token)
if (token) {
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
console.log(decoded)
req.user = await prisma.user.findFirst({
where: {
email: decoded.email,
},
});
next();
} catch (err) {
res.status(401);
throw new Error(`Not Authorized, Invalid Token`);
}
} else {
res.status(401);
throw new Error(`Not Authorized, No Token`);
}
});
Note: The NextJS frontend and the backend are on different domains and both are running over HTTPS. I need help resolving the cookie access issue in the middleware after deployment. Any solutions would be greatly appreciated. Thank you.