Designed Authentication for a MERN Application
Designing Robust and Secure Authentication for a MERN Application
How I Designed Authentication for a MERN E-commerce Application
When I started building my e-commerce application, authentication seemed straightforward: accept an email and password, verify the credentials, and return a token.
As the application grew, I realized that login was only one part of the problem.
I also needed to decide where credentials should live in the browser, how users would remain authenticated, what should happen when a token expired, and how the server could revoke a session.
Refresh tokens introduced more questions. What happens after a refresh token is used? What if an old token appears again? How should the application distinguish suspicious reuse from duplicated requests?
The resulting architecture uses:
- Short-lived JWT access tokens
- Refresh tokens with rotation
- HttpOnly authentication cookies
- Redis-backed session tracking
- CSRF protection for sensitive operations
This article explains how those pieces fit together, why I chose them, and the tradeoffs I encountered.
The Requirements
Before choosing an authentication approach, I wrote down the behavior the application needed.
The application includes customer-facing features and an administration dashboard. Authentication therefore needed to support ordinary browsing as well as sensitive administrative operations.
My main requirements were:
- Users should remain logged in without repeatedly entering their password.
- Access tokens should have a relatively short lifetime.
- Authentication tokens should not be directly accessible to client-side JavaScript.
- Expired access tokens should be refreshed without unnecessarily interrupting the user.
- A refresh token should become invalid after successful rotation.
- The server should be able to revoke refresh sessions.
- Logout should invalidate the associated server-side session.
- The system should detect reuse of previously consumed refresh tokens.
- Cookie-based authentication should include CSRF protection.
These requirements shaped the architecture more than the choice of any individual library.
My Initial Mental Model
My first understanding of JWT authentication looked like this:
Rendering diagram...
The server can verify a JWT's signature and inspect its claims when an authenticated request arrives.
That makes the basic request flow easy to understand. However, I still needed to choose how long the token should remain valid.
A long-lived token reduces login interruptions, but a stolen token may remain useful for longer.
A short-lived token reduces that window, but it creates a usability problem if every expiration sends the user back to the login page.
I addressed that tradeoff by separating access tokens from refresh tokens.
Access Tokens and Refresh Tokens
An access token is short-lived and accompanies requests to protected resources.
A refresh token has a longer lifetime and is used to obtain new credentials when the access token expires.
The simplified lifecycle looks like this:
Rendering diagram...
This allows access tokens to expire relatively quickly without requiring the user to enter their password every time.
However, a refresh token is still a powerful credential. Someone who obtains a valid refresh token may be able to exchange it for new access tokens.
That led to the next part of the design: refresh-token rotation.
Refresh-Token Rotation
With rotation, the same refresh token is not accepted repeatedly throughout the session.
After a successful refresh, the server invalidates the presented refresh token and issues a replacement.
The refresh operation conceptually performs these steps:
- Validate the refresh token.
- Check its associated server-side session.
- Confirm that the token is still expected to be valid.
- Invalidate the consumed refresh token.
- Create a new access token and refresh token.
- Return the new credentials to the browser.
A series of rotations looks like this:
Rendering diagram...
The important property is that token A should no longer be accepted after the session has moved to token B.
If token A appears again, the server can identify it as a previously consumed credential.
That gives the system more information than a simple expiration check.
It does not automatically prove that an attacker stole the token. It does indicate that the request needs to be evaluated against the session's recorded state.
Why Redis Became Part of the Architecture
JWT authentication is often described as stateless because the server can validate a token without looking up a traditional session.
My requirements included several features that depend on server-side state:
- Session revocation
- Refresh-token tracking
- Token-family tracking
- Refresh-token reuse detection
- Forced termination of refresh sessions
I use Redis to maintain that temporary authentication state.
MongoDB remains responsible for persistent application data, including user accounts.
The separation looks like this:
Rendering diagram...
Redis is useful here because the application needs fast lookups and expiration for temporary records.
This makes the overall authentication architecture stateful, even though it uses JWT access tokens.
That is an intentional tradeoff.
The additional state gives the server more control over refresh sessions, but it also adds infrastructure and consistency concerns.
Where Should Tokens Be Stored?
Another important decision was where authentication tokens should live in the browser.
One common approach is storing an access token in localStorage:
const token = localStorage.getItem("accessToken");This is convenient because application JavaScript can retrieve the token and attach it to requests.
However, JavaScript access also means that malicious JavaScript running in the application may be able to retrieve it.
For this application, I chose HttpOnly cookies for authentication tokens.
An HttpOnly cookie cannot normally be read through browser JavaScript. The browser can still include it in requests to the appropriate destination.
The cookie attributes each serve a different purpose:
| Attribute | Purpose |
| --- | --- |
| HttpOnly | Prevents ordinary browser JavaScript from reading the cookie |
| Secure | Restricts cookie transmission to HTTPS |
| SameSite | Controls when the browser includes the cookie in cross-site requests |
This reduces direct token exposure to JavaScript.
It does not eliminate the impact of XSS. Malicious code running inside the application may still be able to perform actions through the user's browser.
Cookie storage also introduces another consideration: CSRF.
Cookie Authentication and CSRF
Browsers may automatically attach authentication cookies to requests.
That behavior makes cookie-based authentication convenient, but it also means the application needs to consider requests initiated from another website.
A simplified CSRF scenario looks like this:
Rendering diagram...
The attacker does not necessarily need to read the authentication cookie.
Under vulnerable conditions, causing the browser to send an authenticated request can be enough.
For sensitive admin operations, I added CSRF protection using a double-submit approach.
The client supplies a CSRF value through the x-admin-csrf-token request header, and the server validates the CSRF proof alongside authentication.
The request carries both pieces:
Rendering diagram...
The goal is to require more than an automatically attached authentication cookie for protected state-changing operations.
Authentication and CSRF validation answer different questions:
- Authentication establishes which user or session is making the request.
- CSRF protection checks the additional proof required for that cookie-authenticated operation.
What Happens When the Access Token Expires?
Short-lived access tokens create a frontend problem.
A user might be browsing products or editing something in the admin dashboard when the current access token expires.
If the refresh session is still valid, the application should be able to obtain new credentials and continue the operation.
The simplified request lifecycle looks like this:
Rendering diagram...
When refresh succeeds, the user can continue without manually logging in again.
When the refresh token or its session is invalid, the application requires authentication again.
This also introduced a concurrency concern.
Several API requests can fail around the same time because they share the same expired access token. If each request independently attempts a refresh, the client may submit the same refresh token more than once.
Refresh coordination therefore becomes part of the frontend design.
Logout Is More Than Clearing a Cookie
It is easy to think of logout as a client cleanup operation:
clearCookie();Clearing a cookie removes the browser's copy of that credential.
Once the server maintains refresh-session state, logout also needs to invalidate the corresponding session.
My logout flow therefore includes both operations:
Rendering diagram...
These operations address different parts of the system.
Clearing cookies removes the credentials from the browser. Invalidating the refresh session prevents that session from issuing new credentials.
There is also an important distinction between refresh-session revocation and access-token validity.
An already issued access token may remain valid until it expires unless protected requests also check server-side revocation state. Revoking the refresh session alone does not change the signature or expiration of an existing JWT.
Handling Refresh-Token Reuse
Refresh-token reuse was one of the more interesting parts of the design.
Consider a session that has already rotated from token A to token B:
Rendering diagram...
The server should no longer accept token A as the current refresh credential.
However, an old token appearing again can have several explanations:
- The token was copied or stolen.
- A request was duplicated.
- Multiple client requests attempted to refresh concurrently.
- A retry submitted a credential that had already been consumed.
Because of this, I treat reuse detection as a signal that needs a deliberate policy.
A reuse event should not automatically be described as proof of an attack.
In my implementation, refresh tokens belong to a tracked session or token family. That state gives the server enough context to determine whether a presented token is still expected to be valid.
Redis supports that tracking, while the application defines what action to take when the recorded state and presented credential do not agree.
Thinking About the Authentication Lifecycle
The largest change in my understanding was learning to think about authentication as an ongoing lifecycle.
Login creates credentials and session state. After that, the system still needs to manage expiration, refresh, rotation, logout, and failures.
The broader lifecycle looks like this:
Rendering diagram...
Thinking about this lifecycle helped me identify questions that a login endpoint alone would not answer:
- How does the session continue after an access token expires?
- Which credentials are rotated?
- What server-side state must be updated?
- What happens when refresh fails?
- How does logout affect the browser and server?
- How are reused credentials handled?
- What happens when requests arrive concurrently?
- How are authentication failures communicated to the frontend?
Those questions shaped both the backend and the client behavior.
The Tradeoffs
This architecture gives the application more control over authentication, but that control has a cost.
Redis adds an infrastructure dependency
The application now relies on Redis for refresh-session and token state.
That means another service to configure, monitor, and operate.
Rotation adds consistency requirements
A refresh operation changes which credential the server accepts.
Duplicated or concurrent requests can interact with that transition, so rotation needs careful coordination.
Cookie authentication requires CSRF consideration
HttpOnly cookies reduce direct token exposure to JavaScript, but automatically attached cookies make CSRF protection relevant.
Cookie attributes and request validation need to work together.
Automatic refresh adds frontend complexity
The frontend needs to handle expired credentials, refresh failures, and concurrent requests.
It also needs to communicate clearly when the user must log in again.
JWTs do not remove every need for server-side state
The access token can carry verifiable claims, while session revocation and refresh-token tracking still depend on server-maintained records.
For this application, that combination matched the requirements.
For a smaller application, a traditional server-side session might provide the needed behavior with fewer moving parts.
What I Learned
The most useful lesson was seeing how authentication decisions influence one another.
Choosing short-lived access tokens created a need for refresh.
Introducing refresh tokens created a need to think about credential lifetime and rotation.
Rotation introduced token tracking and reuse detection.
Those requirements led to server-side session state in Redis.
Choosing HttpOnly cookies reduced direct token exposure to JavaScript, while also making CSRF protection part of the design.
The relationship between those decisions looks like this:
Rendering diagram...
Each decision addressed a requirement while introducing another responsibility.
I also learned to think about authentication through a small set of questions:
Is this credential valid?
Does its session still exist?
Is this refresh token still the expected credential?
Has it already been consumed?
Should this request be allowed to continue?
Those questions gave me a more useful way to reason about the system than focusing only on token generation.
Final Architecture
At a high level, the system consists of a React client, an Express and TypeScript API, MongoDB for persistent account data, and Redis for temporary authentication state.
Rendering diagram...
The API includes the authentication capabilities shown above; individual routes use the checks and operations relevant to their purpose.
The final system has more moving parts than the login flow I originally imagined.
Building it taught me how credential expiration, browser storage, server-side state, request validation, and frontend behavior interact.
The lesson I will carry into my next backend project is to define the authentication lifecycle early, understand what each mechanism guarantees, and choose the smallest design that satisfies the application's requirements.