Attach a bearer token to an API request
A signed-in React frontend needs to call a protected backend API.
Kinde · Function
getAccessToken() asynchronously reads Kinde’s cached raw access-token JWT for use in API requests. It does not refresh the token and can return undefined or an expired token.
Call the method to read the access-token JWT currently held in session storage. It returns the cached value without refreshing it, so callers should handle an absent token and understand that the returned token may already be expired.
const token = await getAccessToken();Promise<string | undefined> — the cached raw access-token JWT, or undefined if no token is stored.
import { useKindeAuth } from "@kinde-oss/kinde-auth-react";
export async function callApi() {
const { getAccessToken } = useKindeAuth();
const token = await getAccessToken();
if (!token) return;
const response = await fetch("https://api.example.com/data", {
headers: { Authorization: `Bearer ${token}` },
});
return response.json();
}Reads the cached token and sends it to an API as a bearer token.
A signed-in React frontend needs to call a protected backend API.
An application needs to determine whether a cached access token exists.
A caller needs a newly refreshed credential.
getAccessToken() returns a Promise<string | undefined>. It reads the raw cached access-token JWT from session storage and returns undefined when no token is stored.
Follow-up: How would you obtain a fresh token? Call refreshToken() first, then call getAccessToken() to read the refreshed value.
No. The method only reads the cached token and does not call Kinde’s token endpoint. The returned JWT may therefore be expired.
Follow-up: Why might a subsequent call return a newer token? The SDK can refresh silently in the background, after which getAccessToken() reads the updated cached value.
Use the value as a bearer credential in the Authorization header when calling an API. Check for undefined before constructing the request, because signed-out users may have no stored token.
Follow-up: What should the API do with the bearer token? Validate the JWT server-side before authorizing the request.
useKindeAuthrefreshTokengetTokenAuthorization bearer token