How Authentication Works in Production

14 min read
•Venkat Nithin
AuthSecurityJWTNext.jsWeb Security

When you build your first app, authentication seems simple: take an email and a password, check if it matches what is in your database, and let the user in.

Once you start building real applications, you run into basic questions:

  • What rules should we put on passwords, and how do we check them?
  • How do we safely save passwords in the database?
  • What is hashing, and what is salting?
  • Why did people move from sessions to tokens?
  • Why do we need two tokens (Access and Refresh) instead of just one?
  • What is middleware, and how does it protect routes?
  • How do we safely log someone out?

Here is a straightforward guide to how all of this works, explained simply from the ground up.


Table of Contents


01. Password Constraints & Input Validation

When someone creates an account, why can't they just use 123456 or cat?

Because if a password is too short or too common, anyone can guess it in seconds. Password constraints are simply the rules we set to keep passwords safe:

  • Minimum length: Usually at least 8 characters. Length matters more than complex symbols because every extra letter makes guessing exponentially harder.
  • Maximum length: We usually cap passwords at around 128 characters. Why? Because checking a password takes computer power. If a bad actor sends a password that is 50,000 characters long, your server will freeze trying to process it.

Why Must We Validate on the Server?

You might check password rules in the browser with JavaScript so the user gets helpful error messages. But you can never trust the browser alone.

Anyone can open a terminal and send an HTTP request directly to your API endpoint, completely skipping your frontend forms. If you do not validate on the server, someone could send an empty password or bad data straight into your database.

Using a validation library like Zod lets you define these rules cleanly on the backend:

import { z } from "zod";

export const RegisterSchema = z.object({
  email: z.string().trim().email("Please provide a valid email address"),
  password: z
    .string()
    .min(8, "Password must be at least 8 characters")
    .max(128, "Password must not exceed 128 characters"),
});

Interactive Zod Validation DemoPLAYGROUND

At least 8 characters
Contains uppercase letter
Contains lowercase letter
Contains a number
Contains special character

02. Storing Passwords: What is Hashing & Salting?

The golden rule of web security is simple: never save passwords as plain text in your database. If your database is ever leaked or seen by someone, every user's password would be exposed.

Instead, we store a scrambled version. But how?

What is Hashing?

Hashing is a one-way scramble. You put a password in, and the computer turns it into a scrambled string:

"mysecretpassword" ──> [ Hash Function ] ──> "5e884898da28047151d0e56f8..."

What makes it special is that it only goes one way:

  • It is easy to turn a password into a hash.
  • It is impossible to turn the hash back into the password.

When the user comes back to log in later, the server takes their input, runs it through the same hash function, and checks: Does this new scrambled string match the scrambled string we saved in the database? If yes, the user is logged in.

Why Do Old Hash Functions (MD5, SHA-256) Fail?

Algorithms like MD5 or SHA-256 were built to be fast. They were designed to check file downloads quickly.

Because they are fast, modern computers and graphics cards can calculate billions of guesses every second. If an attacker gets your database, they can run through billions of common words in minutes until they find what matches your hashes.

What is Salting, and Why Do We Need It?

Standard hashing has another problem: it always produces the exact same scrambled output for the same input.

If ten different users choose password123, all ten will have the exact same hash in your database. Attackers take advantage of this by creating giant lists of common words and their hashes (called Rainbow Tables). They don't even have to guess—they just look up the hash in their list like a dictionary.

The Fix: Salting A salt is just a unique, random string generated for every single user before hashing their password:

Password ("hello") + Random Salt ("x9#k2") ──> Hash Function ──> Unique Hash

We save the salt alongside the hash in the database. Because every user has a different random salt:

  • Two users with the exact same password end up with completely different hashes.
  • Rainbow lookup tables are rendered completely useless.

What We Use in Production: Slow Hashing (bcrypt)

In real apps, we use hashing tools like bcrypt or argon2:

  • They add the salt automatically.
  • They are deliberately made to run slow (taking around 100 to 200 milliseconds per check).

A human logging in once will never notice a 150-millisecond delay. But an automated script trying to guess a million passwords gets slowed down to weeks of waiting.

import bcrypt from "bcrypt";

// When registering: scramble with salt
const hashedPassword = await bcrypt.hash(rawPassword, 12);

// When logging in: check if the guess matches
const isCorrect = await bcrypt.compare(candidatePassword, user.hashedPassword);

03. Sessions vs. Tokens: Stateful vs. Stateless

Once the password is verified, how does the server remember that this user is logged in when they click around the app?

The Traditional Way: Stateful Sessions

In the traditional session approach:

  1. The user logs in.
  2. The server creates a session entry in its database: { sessionId: "xyz123", userId: 42 }.
  3. The server sends xyz123 back to the user's browser in a cookie.
  4. On every single request, the browser sends xyz123.
  5. The server checks the database: "Does session xyz123 exist, and who does it belong to?"

What does "stateful" mean?
It means the server has to keep track of state (remembering active users in its database).

  • The Good Part: It is easy to log someone out. If you want to kick a user out, just delete their session row from the database.
  • The Problem (Database Bottleneck): Every single click, page reload, and API call requires your database to do a lookup. When you have thousands of active users, your database spends massive amounts of power just checking: "Is this person logged in?"

The Modern Way: Stateless Tokens (JWT)

To solve the database bottleneck, the web moved to stateless tokens, most commonly JWTs (JSON Web Tokens).

What does "stateless" mean?
The server stores nothing about the session in its database. Instead, the user carries their own proof of identity.

What is a JWT?

A JWT is simply a string made of three parts separated by dots:

Header . Payload . Signature
  1. Header: Tells the computer what type of token it is.
  2. Payload: Contains basic information, like { "userId": 42, "role": "admin" }. Anyone can decode and read this text.
  3. Signature: The server takes the header and payload, and signs them using a secret password known only to the server.

When the user sends their token with a request, the server does not touch the database. It runs simple math on the signature using its secret key:

  • If the math checks out, the server knows: "We created this token, and nobody altered it."
  • If a user tries to change "role": "user" to "role": "admin", the signature becomes invalid immediately.
  • Result: The server verifies who you are in less than a millisecond without making a single database query.

JWT Decoder SimulationPLAYGROUND

Raw JWT Token

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI1ZjhmYWU0Y2EyMTk0Iiwicm9sZSI6InBob3RvZ3JhcGhlciIsImlhdCI6MTcxNjM5ODQwMCwiZXhwIjoxNzE2NDA1NjAwfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

04. Why We Need Dual Tokens: Access & Refresh Tokens

Stateless tokens have one big catch: because the server doesn't check the database, a token cannot be easily cancelled once it is created.

If you give a user a token that lasts for 30 days, and someone manages to steal that token, the thief has 30 days of full access. But if you make the token expire in 10 minutes for safety, the user would have to type their password every 10 minutes!

To solve this, production apps use two tokens:

1. Access Token:   Lasts 15 minutes. Used for everyday API calls.
2. Refresh Token:  Lasts 7 days. Stored safely to renew the 15-minute token.

Where Do We Store Them?

  • localStorage is unsafe: Any JavaScript code running on your webpage can read localStorage. If an attacker slips a malicious script into your site (an XSS attack), they can steal the token instantly.
  • httpOnly Cookies are safe: A cookie marked httpOnly cannot be read by JavaScript. The browser sends it automatically with requests, but no script can ever access it.
// Storing the Refresh Token in a safe cookie
res.cookie("refreshToken", refreshToken, {
  httpOnly: true, // JavaScript cannot read this
  secure: process.env.NODE_ENV === "production", // Sent only over HTTPS
  sameSite: "lax", // Protects against unauthorized cross-site requests
  path: "/api/auth/refresh", // Sent only to the refresh endpoint
  maxAge: 7 * 24 * 60 * 60 * 1000, // 7 days
});

How the Renewal Works:

  1. The user browses the app using their short 15-minute Access Token.
  2. After 15 minutes, the Access Token expires, and the backend returns 401 Unauthorized.
  3. The frontend catches this error and quietly calls /api/auth/refresh.
  4. The browser automatically includes the safe httpOnly Refresh Token cookie.
  5. The backend checks the refresh cookie and hands back a fresh 15-minute Access Token.
  6. The frontend retries the user's action. The user never notices a pause.

05. Defenses: CSRF Protection & Rate Limiting

Using cookies protects you from scripts stealing your tokens, but it introduces a different risk: CSRF (Cross-Site Request Forgery).

What is CSRF?

Because browsers automatically send cookies to matching websites, imagine this scenario:

  1. You are logged into your bank on Tab 1.
  2. In Tab 2, you click a link to a sketchy website.
  3. That sketchy website secretly sends a form request to yourbank.com/transfer-money.
  4. Your browser sees a request to yourbank.com and automatically attaches your login cookies!

How We Stop CSRF:

  1. SameSite=Lax: Setting this flag on your cookie tells the browser: "Never attach this cookie if the request was started by an external website."
  2. Custom Headers: Real API requests send custom headers (like Authorization: Bearer <token>). Evil websites cannot send custom headers across different domains.

Why Do We Need Rate Limiting?

Remember that password checking (bcrypt) is intentionally slow. It takes computer processing power on purpose.

If someone runs a bot script that sends 1,000 login attempts every second, your server's CPU will get completely overwhelmed verifying passwords and crash.

Rate limiting is simply a rule that says: "If an IP address fails to log in 5 or 10 times in a row, block them from trying again for 15 minutes."

import rateLimit from "express-rate-limit";

export const authLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 10, // Max 10 attempts
  message: { error: "Too many login attempts. Please wait 15 minutes." },
  skipSuccessfulRequests: true, // Don't penalize correct logins
});

06. Route Protection: Middleware & Role-Based Access

Imagine your application has 40 different API routes: /api/profile, /api/orders, /api/settings, /api/admin/users, etc.

If you don't use middleware, you would have to manually copy and paste the same token-checking code at the top of all 40 files:

// Avoid doing this in every single file!
const token = req.cookies.accessToken;
if (!token || !verifyToken(token)) {
  return res.status(401).json({ error: "Please log in first" });
}

If you forget to add that code to just one new file, that route is accidentally open to the whole world.

What is Middleware?

Middleware is a bouncer at the front door of your application. Before any request reaches your actual route files, it must pass through the middleware first:

Incoming Request
       │
       ▼
[ Middleware Bouncer ]
       ├── Public route? (/login, /about) ──> Let in immediately
       ├── Protected route? (/dashboard)  ──> Check token signature. Invalid? Block with 401
       └── Admin route? (/admin)          ──> Check user role. Not admin? Block with 403
// Next.js Edge Middleware example (middleware.ts)
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

export function middleware(req: NextRequest) {
  const token = req.cookies.get("accessToken")?.value;
  const isDashboard = req.nextUrl.pathname.startsWith("/dashboard");

  // Protect private routes
  if (isDashboard && !token) {
    return NextResponse.redirect(new URL("/login", req.url));
  }

  return NextResponse.next();
}

Role-Based Access Control (RBAC)

When a user logs in, we can save their role right inside their token: { "userId": 42, "role": "editor" }.

The middleware checks both:

  1. Are you logged in? (If not $\rightarrow$ 401 Unauthorized).
  2. Do you have permission for this room? If a regular user tries to visit an admin route, the middleware rejects them with 403 Forbidden before your backend code even runs.

07. Token Revocation: How to Safely Log Out Users

Because stateless access tokens are checked with math rather than database lookups, a common question is:

If the server doesn't check the database, how do you safely log someone out?

In production, logout is handled in two simple ways:

1. Normal Logout

When a user clicks "Log Out" on their device:

  1. The server tells the browser to clear the httpOnly Refresh Token cookie (res.clearCookie("refreshToken")).
  2. The browser removes the Access Token from its memory.
  3. Without the refresh cookie, the browser can never ask for a new access token. Once the active 15-minute token expires, the session is dead.

2. Global Logout ("Log Out of All Devices")

What if a user loses their phone, or changes their password, and wants to kick out all logged-in devices right now?

We keep a simple integer called tokenVersion on the user row in the database:

User Record: { id: 42, email: "user@example.com", tokenVersion: 1 }
  • When generating tokens, we include that number in the payload: { "userId": 42, "tokenVersion": 1 }.
  • When the user clicks "Log Out Everywhere", we just add 1 to that number in the database: tokenVersion = 2.
  • The next time an old device tries to renew its token, the server sees that the token says version 1, but the database says version 2. The server refuses to renew it, immediately locking that device out.

Conclusion

Building authentication comes down to straightforward, practical choices:

  1. Password constraints: Keep rules simple and enforce them on the server.
  2. Hashing & salting: Scramble passwords with bcrypt so database leaks can't be decoded.
  3. Tokens over sessions: Use signed tokens so your database isn't flooded with lookup queries.
  4. Dual tokens: Combine 15-minute access tokens with safe HTTP-only refresh cookies.
  5. Middleware: Guard all your routes at the front door.
  6. Token versions: Increment a simple number to log out all devices safely.

Next in this series: Part 2: Modern Authentication Beyond Passwords, covering OAuth, authenticator apps, passkeys, and SSH keys.

Enjoyed this article?

Subscribe to get notified when I publish new content.