I'm using googleapi
to login via google.
I'm getting user details and it successfully saving to DB as i wanted.
After getting user it should save cookie
to localhost
(which is frontend) and redirect to homepage
But its not saving cookie to localhost so redirecting to login page.
How can save cookie?
I tried using sameSite: 'lax', and 'none
but still same issue.
URL:
frontend: http://localhost:5173
backend: http://localhost:5000
Here is my route flow
http://localhost:5173/login
https://accounts.google.com/o/oauth2/v2/auth?redirect...........
const accessToken = jwt.sign({ _id: existingUser._id, username: existingUser.username },
process.env.PRIVATE_KEY, { expiresIn: '1h',});
// set cookies
res.cookie('jwtoken', accessToken, {
maxAge: 3600000, // 1 hr
httpOnly: true,
domain: process.env.DOMAIN, // DOMAIN = localhost
path: '/',
sameSite: 'lax',
secure: false,
});
res.redirect(process.env.ORIGIN); // ORIGIN = http://localhost:5173
CodePudding user response:
It sounds like the issue may be related to the fact that the cookie is being set on the backend server (http://localhost:5000) while the frontend is running on a different server (http://localhost:5173).
Cookies can only be accessed by the domain that set them, so the cookie set on the backend server will not be accessible on the frontend server.
One solution to this problem is to set the cookie on the frontend after the redirect from the backend.
Backend (Node.js) code:
app.get('/login', (req, res) => {
// authentication logic here
// ...
const accessToken = jwt.sign({ _id: existingUser._id, username: existingUser.username },
process.env.PRIVATE_KEY, { expiresIn: '1h',});
// redirect to frontend with the access token in the query string
res.redirect(`${process.env.ORIGIN}/home?token=${accessToken}`);
});
Frontend code:
// in the /home route component
const token = new URLSearchParams(props.location.search).get('token');
// set the cookie
document.cookie = `jwtoken=${token}; max-age=3600; path=/;`;
The other solution, setting the cookie on the domain level, such as "localhost
" instead of "http://localhost:5000"
so that it can be accessed on both the frontend and backend server, is a bit more complex, and it could be done by modifying the res.cookie()
options. You can use domain option like this:
res.cookie('jwtoken', accessToken, {
maxAge: 3600000, // 1 hr
httpOnly: true,
domain: 'localhost', // DOMAIN = localhost
path: '/',
sameSite: 'lax',
secure: true,
});
Hope this Helps!!