Seamless Token Refresh: Backend vs Frontend Strategies for JWT Authentication

This article explains why seamless token refresh prevents sudden logouts, compares backend automatic token renewal with frontend dual-token (access/refresh) approaches, provides Java JWT implementation code with expiration calculations, and discusses handling edge cases like long-form submissions where no requests are sent before token expiry.

Architect's Guide
Architect's Guide
Architect's Guide
Seamless Token Refresh: Backend vs Frontend Strategies for JWT Authentication

Why Seamless Token Refresh Is Needed

A common issue: users performing business operations suddenly get logged out and redirected to the login page. The system uses Redis to cache user IDs and token information. The root cause is token expiration leading to identity invalidation.

Backend Automatic Token Refresh Solution

The backend checks a token's expiration time during validation. If the token is about to expire, the backend generates a new token and places it in the response header. The frontend intercepts the response, compares the new token with the stored one, and updates local storage if they differ.

Implementation Example (Java + JWT)

Dependencies used:

<dependency>
  <groupId>cn.hutool</groupId>
  <artifactId>hutool-all</artifactId>
  <version>5.5.1</version>
</dependency>
<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>fastjson</artifactId>
  <version>1.2.33</version>
</dependency>
<dependency>
  <groupId>io.jsonwebtoken</groupId>
  <artifactId>jjwt</artifactId>
  <version>0.9.1</version>
</dependency>
JwtUtil

class provides methods to create JWTs with HS256 signing, configurable TTL (default 24 hours), and parsing. Key constants:

public static final Long JWT_TTL = 60 * 60 * 1000 * 24; // 24 hours
public static final String JWT_KEY = "qx";

Token creation uses Jwts.builder() with UUID as ID, subject as payload, issuer "sg", issued-at timestamp, and expiration date.

Unit Test & Expiration Calculation

@Test
void test() throws Exception {
  String token = JwtUtil.createJWT("1735209949551763457");
  Date tokenExpirationDate = getTokenExpirationDate(token);
  long exp = tokenExpirationDate.getTime();
  long cur = System.currentTimeMillis();
  System.out.println(exp - cur); // ~86398965 ms
}

The test shows the token's expiration timestamp (e.g., 1703651262000) minus current time (1703564863035) yields ~86,398,965 ms, close to one day (86,400,000 ms). During validation, if (expiration - now) < threshold, a new token is generated from the old token's claims and returned in the response header.

Frontend Token Renewal (Dual-Token Approach)

This solution shifts expiration monitoring to the frontend. The frontend and backend agree on a token-renewal endpoint. When the frontend detects the access token (AT) is near expiry, it sends the refresh token (RT) to the backend, which extends the AT's validity.

Token roles:

Access Token (AT): Short expiry, sent with every request. Higher exposure → shorter TTL reduces hijack risk.

Refresh Token (RT): Long expiry, only used against the auth service to obtain new ATs. Lower exposure → longer TTL increases convenience.

The author notes this is a standard security pattern, analogous to HTTPS over HTTP.

Edge Case: Long-Idle Form Submission

If a user spends a long time filling a form without sending requests, the token may expire. When the user finally submits, the backend returns 401. Since the backend can only refresh tokens on incoming requests, it cannot proactively detect this idle expiration.

Proposed Solutions

Backend-centric approach: On 401, the frontend saves form data to local storage, redirects to login, and after successful login restores the form data from storage.

Frontend-centric approach: Monitor the refresh token's expiration; proactively request RT renewal before it expires, or refresh periodically. Additionally, implement a draft-saving (auto-save) feature for forms to preserve user input.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaSpring BootSecurityAuthenticationJWTAccess TokenRefresh TokenToken RefreshFrontend-Backend Integration
Architect's Guide
Written by

Architect's Guide

Dedicated to sharing programmer-architect skills—Java backend, system, microservice, and distributed architectures—to help you become a senior architect.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.