I’m working on a project that uses Next.js for the frontend and Express.js for the backend. I’m trying to set up authentication but I’m having some issues with cookies. Here are the problems I’m facing:
- The frontend can’t access the cookies
- Logging out doesn’t clear the cookies like it should
- The Next.js middleware can’t see the cookies for authentication
Does anyone have experience with this setup? How can I make sure the cookies are handled correctly between Next.js and Express.js? I’m especially concerned about making this work in a production environment. Any tips or best practices would be really helpful. Thanks!
For managing cookies between Next.js and Express.js, I’ve found that using a library like js-cookie on the frontend and cookie-parser on the backend works well. Ensure that you set the httpOnly and secure flags when creating cookies on the server. For cross-domain setups, properly configure CORS and use the sameSite attribute. For authentication, consider implementing a JWT strategy, storing the token in an HTTP-only cookie while using a separate cookie for frontend access. For logout, clear cookies on both sides using res.clearCookie in Express and js-cookie.remove in Next.js. Finally, ensure that Next.js middleware parses cookies correctly, possibly by using a package like next-cookies.
ooh, cookies between next.js and express? sounds tricky! have u tried using httpOnly cookies for auth? they’re super secure. what about setting SameSite attribute? i’m curious, whats ur current setup look like? maybe we can brainstorm some ideas together? let me kno if u want to chat more about it!
hey, i’ve dealt with this before. try using the ‘next-iron-session’ package. it handles cookies securely for both client and server. for logout, make sure to destroy the session on both ends. also, check ur cors settings - they can cause headaches with cookies. hope this helps!