I'm starting a new project with a React frontend and a Node.js API. I'm confused about the best way to handle authentication. Many tutorials suggest JSON Web Tokens (JWT) stored in LocalStorage, but I've read that this is prone to XSS attacks. Are traditional session cookies still relevant for modern APIs, or is there a more secure middle ground I'm missing?
3 answers
This is a classic debate! If your frontend and backend are on the same top-level domain, HttpOnly Session Cookies are generally more secure. They are immune to JavaScript-based XSS because the script can't actually "read" the cookie. However, if your API needs to be used by mobile apps or third-party developers, JWTs are more flexible because they are stateless and don't require the server to store session data. The "Gold Standard" for security today is using a JWT but delivering it via a Set-Cookie header with the HttpOnly and Secure flags. This gives you the stateless benefits of JWT with the XSS protection of cookies.
If we use JWTs in cookies, do we still need to worry about CSRF (Cross-Site Request Forgery) attacks?
I prefer JWT because it scales better. You don't have to sync session stores across multiple servers, which simplifies the infrastructure significantly.
That's true, Sandra. In a microservices environment, having a self-contained token (JWT) means every service can verify the user without calling a central auth database.
Yes, absolutely, Kenneth. Cookies are automatically sent by the browser with every request, which is exactly what CSRF exploits. To prevent this, you should set the SameSite=Strict or Lax attribute on your cookie. For even better protection, you can implement a custom header check (like X-Requested-With) or a CSRF token. Since malicious cross-site scripts can't easily set custom headers on a request they are forging, this adds a strong secondary layer of defense. Modern frameworks often have middleware that handles this "Double Submit Cookie" pattern automatically for you.