Menu

Authentication Concepts

Lesson 1: Authentication Concepts

What is the difference between authentication and authorisation?

Concept Question it answers Example
Authentication (authn) Who are you? Asha signs in with email and password
Authorisation (authz) What are you allowed to do? Asha can edit her own reviews, not others'
Session How do we remember you between requests? A secure cookie holding a session ID or token

Session strategies

Strategy How it works Pros Cons
Database sessions Cookie holds a random ID; session data lives in the database Easy to revoke (log out everywhere) One database lookup per request
Stateless (JWT) sessions Cookie holds a signed, encrypted token with user data No lookup needed Hard to revoke before expiry

Whichever you choose, the cookie should be set with these attributes:

Attribute Purpose
HttpOnly JavaScript cannot read it (protects against XSS theft)
Secure Sent only over HTTPS
SameSite=Lax Limits cross-site requests (helps against CSRF)
Expires / Max-Age Session ends after a set time

Choosing a solution

Option Type Good for
Better Auth Open-source library, self-hosted Most new Next.js projects; its team also maintains Auth.js
Auth.js (NextAuth.js) Open-source library Existing projects already using it
Clerk Hosted service with UI components Fast setup, organisations, managed user admin
Supabase Auth / Firebase Auth Part of a backend platform Projects already on that platform
Auth0 / WorkOS Hosted, enterprise-focused SSO, SAML, compliance needs

Avoid writing password hashing, OAuth flows, and session rotation yourself unless you have a specific reason. Libraries handle edge cases you are likely to miss.

Common mistakes

Mistake Effect Fix
Storing tokens in localStorage Any XSS bug can steal them Use HttpOnly cookies
Checking login only in the UI (hiding buttons) API and actions remain open Check on the server for every request
Storing plain-text passwords Catastrophic if leaked Use a library that hashes with a slow algorithm

Key takeaways

  • Authentication identifies the user; authorisation decides what they can do.
  • Keep sessions in secure, HttpOnly cookies.
  • Use a well-maintained library or service.

Try it: List every page and action in LearnHub and mark whether it needs sign-in, a specific role, or neither.


Nextjs Tutorial

J

Jebasta





Get in Touch For Details