An Auth Story
I love system design. I love thinking about the small decisions that make software great for users.
As an engineer, I care about security. Software is useless if it is unsafe or loses money due to attacks. I want to build products that work every time.
I recently worked on authentication for an AI startup. I used Next.js for the frontend. Next.js is great for small teams because it combines the frontend and backend in one codebase.
During this project, I focused on how to store and protect authentication tokens in the browser. The solution is cookies, specifically HttpOnly cookies.
Why use cookies instead of Local Storage?
Local Storage is easy to use, but it has a risk. JavaScript can read it. This makes it vulnerable to Cross-Site Scripting (XSS) attacks. If a malicious script runs on your site, it can steal your user's token.
Cookies solve this. You can add an HttpOnly flag to a cookie. This tells the browser: "Only send this cookie via HTTP requests. Do not let JavaScript touch it."
If an attacker tries to read the cookie using JavaScript, they see nothing. The cookie remains invisible to them, but the browser still sends it to your server automatically.
To make cookies even safer, I use two other flags:
• Secure: This ensures the cookie only travels over HTTPS. • SameSite=Lax: This helps prevent Cross-Site Request Forgery (CSRF) attacks.
How I implemented this with Next.js:
I wanted to keep my backend (FastAPI) hidden from the browser. I used Next.js as a proxy to create a server-to-server setup.
- The user logs in via a Next.js Server Action.
- The Server Action sends credentials to FastAPI.
- FastAPI returns a token to the Next.js server.
- The Next.js server writes that token into an HttpOnly cookie.
- The browser stores the cookie but cannot read it.
When the user needs data, the Next.js server reads the cookie and talks to the backend for them. The sensitive token never touches the browser's JavaScript environment.
This setup keeps my backend isolated and my users safer.
How do you handle authentication in your Next.js projects? I would love to hear your approach.
