Next.js › Cookies & Session Management in Next.js

What security settings should always be applied to cookies that store session or authentication information?

Advanced

Answer

Always set the httpOnly flag so client side scripts cannot read the cookie, set the secure flag so it is only sent over HTTPS, choose an appropriate sameSite setting to prevent cross site request forgery, and set a reasonable expiration time so sessions do not last forever.
cookieStore.set('session', token, {
  httpOnly: true,
  secure: true,
  sameSite: 'lax',
  maxAge: 60 * 60 * 24 * 7,
  path: '/'
});
Real-world example An e-commerce platform sets strict cookie security settings on its checkout session cookie, protecting customer payment flows from common attacks like cross site scripting and cross site request forgery.

Common follow-ups: What is the difference between sameSite lax and sameSite strict?;How do these settings affect single sign on flows across subdomains?