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.
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,
| 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 |
You don’t need to explicitly set the cookie header in the browser. It’s automatically set by the browser in every request
