frontend - How to Properly Handle Cookies in Next.js (Server-Side) + Express.js Backend? - Stack Overflow

I'm implementing authentication for a Next.js frontend with an Express.js backend, and handling co

I'm implementing authentication for a Next.js frontend with an Express.js backend, and handling cookies in a production environment presented several challenges. Cookies weren't accessible on the frontend, logout didn't clear cookies properly, and cookies were unavailable in Next.js middleware for authentication.

I'm implementing authentication for a Next.js frontend with an Express.js backend, and handling cookies in a production environment presented several challenges. Cookies weren't accessible on the frontend, logout didn't clear cookies properly, and cookies were unavailable in Next.js middleware for authentication.

Share asked Mar 7 at 10:47 Rao ImtinanRao Imtinan 901 silver badge6 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

Setting Cookies in Express.js Backend

When setting a cookie, you must ensure that the domain, security options, and SameSite settings match your frontend setup. If your frontend and backend are on different subdomains, you need to allow cross-site cookies.

const token ='klldfhjsdhfkjdshfkdsfjk'

const cookiesOpts = {
  httpOnly: true,  
  secure: true,   
  sameSite: 'None', 
  maxAge: 24 * 60 * 60 * 1000, // Cookie expires in 1 day
  domain: '.example', // Allows subdomain sharing (e.g., api.example & app.example)
  path: '/',
};

res.cookie('token', token, cookiesOpts);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744935701a4602007.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信