Most login tutorials stop at "return a token". Real apps need two more things: a way to keep people signed in for weeks, and a way to survive a request that fails halfway because the connection dropped.
This post builds that setup with NestJS on the server and Flutter with Dio on the phone. The two rules that matter most are in the last section.
The design in one paragraph
The server issues two tokens at login. The access token lives for about 15 minutes and is sent with every request. The refresh token lives for weeks, is sent only to one endpoint, and is replaced every time it is used. If the access token expires, the app quietly exchanges the refresh token for a new pair and repeats the failed request.
NestJS: issuing and rotating tokens
Install the JWT module and sign the two tokens with different secrets, so a leaked access secret cannot mint refresh tokens.
// auth.service.ts
import { createHash } from "node:crypto";
import { Injectable, UnauthorizedException } from "@nestjs/common";
import { JwtService } from "@nestjs/jwt";
const sha256 = (value: string) =>
createHash("sha256").update(value).digest("hex");
@Injectable()
export class AuthService {
constructor(
private jwt: JwtService,
private users: UsersService, // your own user store
) {}
async login(email: string, password: string) {
const user = await this.users.validateCredentials(email, password);
if (!user) throw new UnauthorizedException();
return this.issueTokens(user.id);
}
async refresh(refreshToken: string) {
let payload: { sub: string };
try {
payload = await this.jwt.verifyAsync(refreshToken, {
secret: process.env.JWT_REFRESH_SECRET,
});
} catch {
throw new UnauthorizedException();
}
const stored = await this.users.getRefreshHash(payload.sub);
if (!stored || stored !== sha256(refreshToken)) {
throw new UnauthorizedException(); // old, reused or revoked token
}
return this.issueTokens(payload.sub); // rotation: the old token is now dead
}
async logout(userId: string) {
await this.users.setRefreshHash(userId, null);
}
private async issueTokens(userId: string) {
const payload = { sub: userId };
const accessToken = await this.jwt.signAsync(payload, {
secret: process.env.JWT_ACCESS_SECRET,
expiresIn: "15m",
});
const refreshToken = await this.jwt.signAsync(payload, {
secret: process.env.JWT_REFRESH_SECRET,
expiresIn: "30d",
});
await this.users.setRefreshHash(userId, sha256(refreshToken));
return { accessToken, refreshToken };
}
}
Three details are easy to get wrong:
- Store a hash, not the token. If the database leaks, stored refresh tokens should be useless.
- Hash with SHA-256, not bcrypt. bcrypt only reads the first 72 bytes of its input, and every JWT from one server starts with the same header, so two different tokens can produce the same bcrypt hash. SHA-256 is fine here because a refresh token is long and random, unlike a password.
- This stores one refresh token per user. Signing in on a second phone replaces the first. If users have several devices, store one row per session instead.
Protect normal routes with a guard that verifies the access token (@nestjs/passport with passport-jwt is the usual choice), and expose refresh and logout as plain POST endpoints.
Flutter: store tokens safely
Keep both tokens in flutter_secure_storage, not in shared_preferences. Secure storage uses the Keychain on iOS and encrypted storage on Android.
// token_store.dart
import 'package:dio/dio.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
class TokenStore {
TokenStore(this._baseUrl);
final String _baseUrl;
final _storage = const FlutterSecureStorage();
Future<String?> get access => _storage.read(key: 'access');
Future<void> save(String access, String refresh) async {
await _storage.write(key: 'access', value: access);
await _storage.write(key: 'refresh', value: refresh);
}
Future<void> clear() => _storage.deleteAll();
/// Uses a plain Dio with no interceptors, so a refresh can never trigger another refresh.
Future<void> refresh() async {
final refresh = await _storage.read(key: 'refresh');
final res = await Dio(BaseOptions(baseUrl: _baseUrl)).post(
'/auth/refresh',
data: {'refreshToken': refresh},
);
await save(res.data['accessToken'], res.data['refreshToken']);
}
}
Flutter: refresh once, then retry
This interceptor adds the token to each request. When a request fails with 401, it refreshes and repeats that request once.
// auth_interceptor.dart
import 'package:dio/dio.dart';
class AuthInterceptor extends QueuedInterceptor {
AuthInterceptor(this._plain, this._tokens);
final Dio _plain; // a Dio with the same baseUrl and no interceptors, used to retry
final TokenStore _tokens;
@override
Future<void> onRequest(
RequestOptions options, RequestInterceptorHandler handler) async {
final token = await _tokens.access;
if (token != null) options.headers['Authorization'] = 'Bearer $token';
handler.next(options);
}
@override
Future<void> onError(DioException err, ErrorInterceptorHandler handler) async {
final req = err.requestOptions;
if (err.response?.statusCode != 401 || req.extra['retried'] == true) {
return handler.next(err);
}
try {
// Another request may already have refreshed while this one waited in the queue.
final sent = req.headers['Authorization'];
if (sent == 'Bearer ${await _tokens.access}') await _tokens.refresh();
req.extra['retried'] = true;
req.headers['Authorization'] = 'Bearer ${await _tokens.access}';
handler.resolve(await _plain.fetch(req));
} on DioException catch (e) {
// Only a rejected refresh means the session is really over.
if (e.requestOptions.path == '/auth/refresh' &&
e.response?.statusCode == 401) {
await _tokens.clear();
}
handler.next(err);
}
}
}
QueuedInterceptor handles one error at a time, so five screens that all hit an expired token cause one refresh, not five. Retrying through a separate Dio instance avoids a known deadlock when a queued interceptor retries through its own client.
The two rules for unreliable networks
Mobile data in Nepal can be slow, can switch between networks, and can drop inside buildings or outside the main cities. That makes these rules more important, not less.
- Only sign the user out when the server says so. A timeout, a dropped connection or a 5xx error is not a logout. Only a 401 from the refresh endpoint means the refresh token is dead. In the code above, a network failure leaves the tokens in place and the user stays signed in.
- Never retry a request that is not safe to repeat. The interceptor repeats the request that failed on 401, which the server rejected before doing any work. Do not add blanket retries on timeouts for requests like "place order" or "pay": the first attempt may have worked. Use an idempotency key for those.
Checklist before you ship
- Access token 15 minutes or less, refresh token rotated on every use.
- Refresh tokens stored hashed with SHA-256, one row per device if you support several.
- Tokens in secure storage, never in plain preferences or logs.
- Logout clears the server hash and the phone's storage.
- Tested with airplane mode and a throttled connection: the user stays signed in and sees an offline message.
Takeaways
- Two tokens: a short access token and a rotating refresh token, signed with separate secrets.
- Hash stored refresh tokens with SHA-256 (not bcrypt, which cuts input at 72 bytes).
- One queued interceptor refreshes once and retries once.
- A bad network is not a logout.
Related
Building an app that needs login and a backend? See Services or get in touch. Also in the Outbox: Flutter apps for slow networks and server-driven UI in Flutter. See the work: Chynabazar and Najik Services.