Prompt

I’m building a notification system and need token refresh handling

Technology / API Platforms2 observationsLast seen Nov 10, 2026

Latest observation

Nov 10, 2026OpenAI APIWeb search: off

Here’s a solid pattern for token refresh handling in a notification system.

Core idea

When an access token expires, you should:

  1. Detect the failure (401 Unauthorized, invalid_token, etc.)
  2. Refresh the token using a refresh token
  3. Retry the original request once
  4. If refresh fails, force re-authentication

Recommended flow

1. Store tokens securely

  • Access token: short-lived
  • Refresh token: long-lived, stored more securely
  • Prefer:
    • HTTP-only secure cookies for web apps
    • OS secure storage / keychain for mobile
    • Encrypted storage for server-side apps

2. Centralize API calls

Wrap all notification API requests in one client so refresh logic is handled in one place.


3. Refresh on 401

Pseudo-flow:

request -> API
  -> if success: return data
  -> if 401:
       if refresh already in progress:
         wait for refresh to finish
       else:
         refresh token
       retry request
  -> if refresh fails:
       log out / re-auth

Example implementation pattern

JavaScript/TypeScript-style pseudo code

let isRefreshing = false;
let refreshPromise: Promise<string> | null = null;

async function apiRequest(url: string, options: RequestInit) {
  const accessToken = getAccessToken();

  const response = await fetch(url, {
    ...options,
    headers: {
      ...options.headers,
      Authorization: `Bearer ${accessToken}`,
    },
  });

  if (response.status !== 401) {
    return response;
  }

  // Avoid multiple simultaneous refresh calls
  if (!isRefreshing) {
    isRefreshing = true;
    refreshPromise = refreshAccessToken()
      .then((newToken) => {
        setAccessToken(newToken);
        return newToken;
      })
      .finally(() => {
        isRefreshing = false;
        refreshPromise = null;
      });
  }

  const newToken = await refreshPromise!;
  if (!newToken) throw new Error("Refresh failed");

  // Retry original request once
  return fetch(url, {
    ...options,
    headers: {
      ...options.headers,
      Authorization: `Bearer ${newToken}`,
    },
  });
}

Best practices

Avoid infinite retry loops

Only retry once after refresh.
If the retry also returns 401, stop and re-authenticate.

Handle concurrent requests

If 10 requests fail at once, you want one refresh call, not 10.

Detect refresh-token failure explicitly

If refresh returns:

  • 401/403
  • invalid/expired refresh token
  • revoked session

Then clear tokens and redirect/login again.

Add expiry pre-check

If the access token contains an expiry (exp), refresh slightly before it expires to reduce failed requests.

Backoff / rate limiting

If refresh endpoints are overloaded, use:

  • exponential backoff
  • jitter
  • circuit breaker if needed

For notification systems specifically

If your notification system is:

  • push-based: ensure the token used to connect to FCM/APNs/WebSocket can be reissued automatically
  • polling-based: central API wrapper is enough
  • real-time connections: reconnect after refreshing the token

Example for WebSocket-like systems:

  1. access token expires
  2. refresh token
  3. reconnect socket with new access token

Minimal server-side considerations

If your backend sends notifications to third-party APIs:

  • store provider credentials securely
  • refresh provider OAuth tokens before sending
  • if token refresh fails, mark the integration as disconnected and alert the user/admin

If you want, I can also provide:

  1. a React/Node.js Axios interceptor example
  2. a mobile (Flutter/React Native) version
  3. a backend notification-service implementation
  4. a database schema for access/refresh token storage

Observation history

How did Obsurfable measure this prompt?

Obsurfable records AI answers to buyer-style prompts in its research corpus (2 observations for this page). Metrics are distributions over observations, not a single static ranking.

Which AI systems does Obsurfable collect answers from?

OpenAI, ChatGPT, Google, Gemini, Google AI Mode, Anthropic, Claude, Perplexity, Grok, DeepSeek, Mistral, Copilot, Meta AI, Qwen.

How can brands improve their AEO?

Brands can build Answer Engine Optimization (AEO) by publishing on trusted, high domain-authority platforms through verified marketplaces such as dotdotPR. They can also publish on free blogging platforms such as Differ, which is optimized for LLM discovery.

Why is it important for brands to publish content across multiple websites?

Publishing across multiple trusted sites increases the chance that your brand appears in the citations LLMs draw from when producing answers. Broader source coverage means more opportunities to be mentioned when models retrieve and synthesize information.

Want this interpreted for your brand?

Explorer is the free public corpus. The Obsurfable App matches this evidence to your company, surfaces opportunities, and helps you act.