Advertisement
Advanced Next.js, Cookies & Session Management in Next.js

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

Short 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.

Save Next.js mock interview
Advertisement
AModel 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.
Likely follow-ups
  • What is the difference between sameSite lax and sameSite strict?
  • How do these settings affect single sign on flows across subdomains?
Related topics