Cookies
Cookies
Cookies persist authentication.
- cookie is just a small string (each domain has own).
- cookie is sent in a header.
Cookies are issues by the backend server to the client browser.
Cookies may be disabled in browser, no matter if the browser is running on PC or mobile.
// server-side res.cookie() // is used to set cookie res.cookie('username', 'somename') res.cookie('password', 'ihavepw') const cookieParser = require('cookie-parser') app.use(cookieParser()); // client-side app.get('/secret', (req, res) => { console.log(req.cookies) // undefined in terminal (only available in header) res.locals.cookies = req.cookies // using cookie })
- persistent: tracking cookies, lasts longer than the browsing session
- secure: can only be transferred over HTTPS
- HTTP only: only the servers can access (XSS attacks prevented)
limitation
multiple browsers have their own cookies and can't be accessed from a different browser
Third Party Cookies
- cookie that track users for advertising
- iframe is used to embed a 3pty ad site
- this is loaded from different domain
- Ads do not know who you are, but they know pieces of information about you
SSR and First Party Cookies
When you serve a HTML file from backend server to the front end client in the same application, the cookies generated are considered a first party cookie.
CORS also does not get applied in case of first party network requests.
Cons
client > server > DB
---------------------
login > query > create record in session_table
session_table (DB) sends back session_id to client
client, when making permissioned request, must send session_id
server then takes session_id and checks the DB's session_table for presence of session_id
Every device or re-login needs to create another session_id for a single unique user
Every cookie request
need to be verified against the DB's session table
to be authenticated on an action every time.
- Computationally and Network heavy
If you have many users, session table
could have millions of dynamic rows and operations for everyday actions.
- Storage heavy
vs JWT
JWT removes the need for session_table
and extra calls to the DB.
Upon client logging in, server generates the JWT with payload and secret key which is sent back to the client.
Client then stores this in cookies or localStorage.
This JWT is then sent with subsequent request to the server which the server alone can decode and verify the validity (no need to interact with the DB)