Token Refresh
How refresh works
Section titled “How refresh works”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.
Automatic refresh with RequireAuth
Section titled “Automatic refresh with RequireAuth”RequireAuth handles refresh automatically. When a user navigates to a protected route with an expired token:
- Checks
tokens.expiresAtagainstDate.now() - If expired, calls
actions.refresh() - If refresh succeeds, renders the children with new tokens
- If refresh fails, redirects to login
<RequireAuth> <Dashboard /></RequireAuth>Manual refresh
Section titled “Manual refresh”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>;}Checking token expiry
Section titled “Checking token expiry”The tokens object from useAuth includes expiry information:
const { tokens } = useAuth();
// Millisecond timestamp when the access token expiresconsole.log(tokens.expiresAt);
// Check if expiredconst isExpired = tokens.expiresAt !== null && tokens.expiresAt <= Date.now();Requesting a refresh token
Section titled “Requesting a refresh token”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.