I have a Next js application as a frontend application for backend i am using node js express js application . Here i implemented JWT token base authentication and authorization . So i am setting the httpOnly jwt token from the backend server . In the frontend server i am accessing the token . If i can access the token from next js app then i permit user to access private routes. So my Problem is when i am runing my applications locally it was running well and i had not faced any issues but after deployment it has been setting cookies into the frontend browser well but it can’t sending cookies when i am trying to access private routes from the frontend . In middleware js can not access the cookies .
middleware.js in next js application :
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;
index.js cors in 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 in express js application :
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 : Here my Next js and backend are in different domain backend and frontend are running in https.
How can it be run without issue after deployment and middleware js will access the cookie into the next js application after deployment?
is there any solution ?
Thank you so much .