1. Authentication v0 → localStorage

The authentication that we have used till now is jwt and additionally to store it locally we used localStorage but the issue in localStorage is that it can be exploited in the browser.

Everytime we need to use the variables in the localStorage, we need to define them / pass them in the headers.

In NextJS, when the primary code runs → it runs on the server-side and not the client-side and the localStorage is present on the client side and as it is not present, localStorage will not work with NextJS.

There are various reasons as to why we use cookies over localStorage and I’ll mention them below.

2. Authentication v1 → cookies

Cookies in web-dev are small packets sent from a website and stored on the user’s computer by the user’s web-browser while the user is browsing. They are used to be a reliable mechanism for websites to remember things (very similar to localStorage).

They are mainly used for three things,

  1. Session Management → Cookies allow websites to track user session states across multiple pages or visits.
  2. Personalization → These cookies are used by google-ads, etc to deliver personalized ads and content.
  3. Tracking → Cookies can track users across websites, providing insights about browsing behavior which can be used for analytics and targeted advertising.
  4. Security → Secure cookies can be used for enhancing security of a website by ensuring that the transmission of information is only done over an encrypted connection, helping to prevent unauthorized access to user data.

3. cookies over localStorage

feature cookies localStorage
1. exists on server yes → can be read by SSR (NextJS) nope 💩
2. automatically sent with HTTP request yes (unless blocked) nope 💩
3. can be http only (js cannot read it) yes nope 💩
4. can be accessed by a secure flag only yes nope 💩
5. max storage size ~4KB ~5-10MB
6. ideal usage auth-tokens / session-ids UI, theme setters, etc
7. vulnerable to CSRF potentially yess unless secured no (as it is not sent automatically)
8. lifecycle controlled by backend / server frontend
9. accessed by nextJS server yes cookie() API nope browser API only
10. expiry cookies provide an expiry period out of the box. cannot have expiry period / manually write logic

4. Authentication with cookies

You don’t need to explicitly set the cookie header in the browser. It’s automatically set by the browser in every request

4.1 System design for signup

image.png

4.2 System design for signin