Reading and Setting Cookies and Headers

Cookies and headers are fundamental parts of HTTP. Cookies commonly represent browser state, while headers communicate metadata such as authorization, content type, locale, and caching information.

Server code can read request information, while response logic can set cookies or headers when appropriate.

Cookie domain, path, Secure, HttpOnly, SameSite, and expiration settings must be considered carefully when building authentication across domains or subdomains.

Reading a Cookie
import { cookies } from 'next/headers';

export async function getCurrentSession() {
  const cookieStore = await cookies();
  const session = cookieStore.get('session');

  return session?.value;
}
💡 Server-side code can read request cookies through the framework cookie API.
Key Takeaways
  • Cookie behavior depends on domain, path, SameSite, Secure, and browser rules.
  • HttpOnly cookies cannot be read by normal browser JavaScript.
  • Cross-subdomain authentication requires deliberate cookie-domain design.