Skip to content

Token Refresh

When the access token expires, oidc-js uses the refresh token to obtain a new access token without requiring the user to log in again.

RequireAuth handles refresh automatically. When a user navigates to a protected route with an expired token:

  1. Checks tokens.expiresAt against Date.now()
  2. If expired, calls actions.refresh()
  3. If refresh succeeds, renders the children with new tokens
  4. If refresh fails, redirects to login
<RequireAuth>
<Dashboard />
</RequireAuth>

You can also trigger a refresh manually:

import { useAuth } from "oidc-js-react";
function RefreshButton() {
const { actions } = useAuth();
async function handleRefresh() {
try {
await actions.refresh();
} catch (error) {
console.error("Refresh failed:", error);
}
}
return <button onClick={handleRefresh}>Refresh Token</button>;
}

The tokens object from useAuth includes expiry information:

const { tokens } = useAuth();
// Millisecond timestamp when the access token expires
console.log(tokens.expiresAt);
// Check if expired
const isExpired = tokens.expiresAt !== null && tokens.expiresAt <= Date.now();

To receive a refresh token, include offline_access in your scopes:

const config = {
issuer: "https://auth.example.com",
clientId: "my-app",
redirectUri: "http://localhost:5173/callback",
scopes: ["openid", "profile", "email", "offline_access"],
};

Without offline_access, the IdP may not issue a refresh token, and actions.refresh() will throw.