Node.js Foundations·From script to service

Sessions, validation and security

Authentication answers who; authorization answers what they may do.

Intermediate 15 min read Lesson 10 of 300 Challenge included
What you will be able to do
  • Never log passwords, tokens or full request bodies with credentials.
  • Set secure cookie flags in production and rotate sessions on login.
  • Add security headers and rate limits on authentication endpoints.

In plain English

Hash passwords with a slow, salted algorithm such as argon2 or bcrypt. Store sessions in secure, httpOnly, sameSite cookies. Validate and authorize every request on the server; never trust a hidden field or a client-side role.

session.jsJavaScript
import argon2 from 'argon2'

const hash = await argon2.hash(password)
const valid = await argon2.verify(hash, candidate)

if (!valid) {
  response.status(401).json({ error: 'INVALID_CREDENTIALS' })
  return
}

response.cookie('session', token, {
  httpOnly: true,
  secure: process.env.NODE_ENV === 'production',
  sameSite: 'lax',
  maxAge: 1000 * 60 * 60,
})
Your turn

Harden a session cookie

Medium

Set a session cookie with httpOnly, sameSite lax, secure in production and a one-hour max age.

JS · starter
response.cookie('session', token)
Check your understanding before moving on.
Knowledge checkQuestion 1

Which cookie flag prevents JavaScript from reading a session cookie?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Lesson 10 of 300 · 0% of course