Get and cache an M2M access token with OAuth client credentials in Node.js
To call an API as a service, POST your client ID and secret to the authorization server's token endpoint with grant_type=client_credentials, then keep the access token in memory and reuse it until shortly before expires_
To call an API as a service, POST your client ID and secret to the authorization server's token endpoint with grant_type=client_credentials, then keep the access token in memory and reuse it until shortly before expires_in runs out. The parts most examples skip are what make it hold up in production: one shared in-flight request so parallel calls don't stampede the token endpoint, and a single retry with a fresh token when the API answers 401.
This post builds that in under 100 lines of plain Node.js with no dependencies, tests it, and then points the same cache at Frontegg's client credentials endpoint. Disclosure: I work at Frontegg. The first two thirds of the post work with any OAuth 2.0 server.
What you'll build
callApi() ββgetToken()βββΆ token provider ββ(cache miss, once)βββΆ token endpoint
β β cached token + renewAt (client_credentials)
ββββββββββ token βββββββββββ
βββBearer tokenβββΆ your API
ββββ 401? ββ invalidate(token), getToken(), retry once
Four small files:
-
token-provider.js: caches one token and shares one in-flight request -
client-credentials.js: the standard RFC 6749 token request -
call-api.js: adds the token to requests and retries once on401 -
frontegg.js: the same token request shape for Frontegg
Tested on Node.js 22.23.4. Everything uses the built-in fetch, so there's nothing to install.
Step 1: Request a token the standard way
The client credentials grant is defined in RFC 6749 section 4.4. It's for confidential clients only, meaning code that can keep a secret: a backend, a worker, a cron job. Never a browser or mobile app.
The request is a form-encoded POST with grant_type=client_credentials and an optional scope. The client authenticates with HTTP Basic. One detail that trips people up: section 2.3.1 says the client ID and secret are form-encoded before they're Base64-encoded, so a secret with +, / or spaces needs escaping first.
// RFC 6749 section 4.4 token request with HTTP Basic client authentication.
const formEncode = (value) => new URLSearchParams({ v: value }).toString().slice(2);
export function clientCredentials({ tokenUrl, clientId, clientSecret, scope }) {
// RFC 6749 section 2.3.1: form-encode the id and secret before Base64.
const basic = Buffer
.from(`${formEncode(clientId)}:${formEncode(clientSecret)}`)
.toString('base64');
return async function fetchToken() {
const body = new URLSearchParams({ grant_type: 'client_credentials' });
if (scope) body.set('scope', scope);
const res = await fetch(tokenUrl, {
method: 'POST',
headers: {
authorization: `Basic ${basic}`,
'content-type': 'application/x-www-form-urlencoded',
accept: 'application/json',
},
body,
signal: AbortSignal.timeout(10_000),
});
const json = await res.json().catch(() => ({}));
if (!res.ok) {
// Log the status and OAuth error code, never the credentials.
throw new Error(`Token request failed: ${res.status} ${json.error ?? ''}`.trim());
}
return { accessToken: json.access_token, expiresIn: json.expires_in };
};
}
The response is JSON with access_token, token_type and usually expires_in, the lifetime in seconds. RFC 6749 only marks expires_in as RECOMMENDED, so the cache below has a fallback for servers that leave it out or send something unusable. There's no refresh token here: section 4.4.3 says the server SHOULD NOT issue one for this grant, because the client can simply authenticate again.
Step 2: Cache the token, and share the request
The naive cache is if (!token || expired) token = await fetchToken(). It works in a demo and breaks under load: if 50 requests arrive while the cache is empty, all 50 see "no token" and all 50 hit the token endpoint. That's 50 identical requests where one would do, and a token endpoint with rate limits may start rejecting them.
The fix is to cache the promise of the request while it's running. Everyone who arrives during a renewal awaits the same promise.
// Caches one access token and shares a single in-flight request.
export function createTokenProvider({
fetchToken, // async () => ({ accessToken, expiresIn })
skewSeconds = 60, // renew this long before the token expires
defaultExpiresIn = 300, // used if expires_in is missing or invalid
now = () => Date.now(),
}) {
let cached = null; // { accessToken, renewAt }
let inFlight = null; // Promise<string> while a request is running
async function renew() {
const { accessToken, expiresIn } = await fetchToken();
if (!accessToken) throw new Error('Token response has no access_token');
const lifetime = Number(expiresIn) > 0 ? Number(expiresIn) : defaultExpiresIn;
// Never let the skew eat the whole lifetime of a short-lived token.
const skew = Math.min(skewSeconds, lifetime / 2);
cached = { accessToken, renewAt: now() + (lifetime - skew) * 1000 };
return accessToken;
}
return {
async getToken() {
if (cached && now() < cached.renewAt) return cached.accessToken;
inFlight ??= renew().finally(() => { inFlight = null; });
return inFlight;
},
// Drop the cached token, but only if it is the one that was rejected.
invalidate(rejectedToken) {
if (cached && cached.accessToken === rejectedToken) cached = null;
},
};
}
A few choices worth calling out:
-
Expiry is computed from your clock when the response arrives, as
now + expires_in. You don't need to decode the JWT or trust that your server's clock matches the issuer's. -
The skew (60 seconds by default) renews early, so a token doesn't expire between
getToken()and the moment the API checks it. For tokens shorter than two minutes, the skew is capped at half the lifetime, otherwise you'd fetch a new token on every call. -
A failed request isn't cached. The
finallyclearsinFlight, so the next call tries again instead of reusing a rejected promise. -
invalidate()only drops the token that was rejected. When 20 parallel requests all get401for the same old token, the first one renews and the other 19 don't throw away the new token.
This cache lives in one process. If you run many short-lived processes (serverless functions, for example), each one fetches its own token. A shared cache such as Redis can help there, at the cost of storing a bearer token outside your process.
Step 3: Retry once on 401
Even with a valid expiry, an API can reject a token: it was revoked, the signing key rotated, or clocks disagree. Treat a 401 as "this token is no good", get a new one, and retry exactly once. A second 401 is a real authorization problem, so return it instead of looping.
// Calls an API with the cached token and retries once on 401.
// Pass a string or Buffer body: a stream can't be sent twice.
export async function callApi(tokens, url, init = {}) {
for (let attempt = 1; ; attempt++) {
const token = await tokens.getToken();
const headers = new Headers(init.headers);
headers.set('authorization', `Bearer ${token}`);
const res = await fetch(url, { ...init, headers });
if (res.status !== 401 || attempt === 2) return res;
tokens.invalidate(token); // revoked or expired early: get a new one
}
}
Putting it together:
import { createTokenProvider } from './token-provider.js';
import { clientCredentials } from './client-credentials.js';
import { callApi } from './call-api.js';
const tokens = createTokenProvider({
fetchToken: clientCredentials({
tokenUrl: process.env.TOKEN_URL,
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
scope: 'invoices:read',
}),
});
// Ten parallel calls, one token request.
const results = await Promise.all(
Array.from({ length: 10 }, () => callApi(tokens, `${process.env.API_URL}/invoices`)),
);
console.log(results.map((r) => r.status));
$ node src/example.js
[
200, 200, 200, 200,
200, 200, 200, 200,
200, 200
]
Ten parallel API calls, one token request. That's the behavior the tests below check.
Step 4: Test it without a real authorization server
I tested everything against a local mock server (Node's http module) that implements a token endpoint, a protected API that can revoke tokens, and an endpoint shaped like Frontegg's documented API. No real credentials are involved. The tests use node:test:
test('50 concurrent getToken calls make one token request', async () => {
const m = await startMock();
const tokens = createTokenProvider({ fetchToken: clientCredentials(creds(m.url)) });
const all = await Promise.all(Array.from({ length: 50 }, () => tokens.getToken()));
assert.equal(new Set(all).size, 1);
assert.equal(m.stats.tokenCalls, 1);
await tokens.getToken();
assert.equal(m.stats.tokenCalls, 1, 'cached token reused');
await m.close();
});
test('renews skewSeconds before expiry (fake clock)', async () => {
let clock = 0; let n = 0;
const tokens = createTokenProvider({ fetchToken: async () => ({ accessToken: `t${++n}`, expiresIn: 3600 }), skewSeconds: 60, now: () => clock });
assert.equal(await tokens.getToken(), 't1');
clock = (3600 - 60) * 1000 - 1; assert.equal(await tokens.getToken(), 't1');
clock = (3600 - 60) * 1000; assert.equal(await tokens.getToken(), 't2');
});
There are 16 tests in all. The others cover the form-encoded secret, the skew cap for short-lived tokens, a missing or invalid expires_in, a failed token request that isn't cached, the 401 retry, a persistent 401 that doesn't loop, a stale 401 that doesn't evict a newer token, parallel 401s that trigger a single renewal, caller headers passed as a Headers object, the Frontegg adapter, and both example scripts end to end. Injecting now makes the expiry tests instant instead of waiting an hour.
Step 5: The same cache with Frontegg
If your service authenticates against Frontegg, the cache and retry code stay the same. Only fetchToken changes. Frontegg's Authenticate using API token endpoint takes a JSON body with clientId and secret (generated in the Admin Portal under API Tokens) and returns access_token, refresh_token, expires_in and expires:
// Exchanges a Frontegg client ID and secret for an access token.
// baseUrl is your environment's own Frontegg domain, without a trailing slash.
export function fronteggClientCredentials({ baseUrl, clientId, secret }) {
return async function fetchToken() {
const res = await fetch(`${baseUrl}/identity/resources/auth/v2/api-token`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ clientId, secret }),
signal: AbortSignal.timeout(10_000),
});
if (!res.ok) throw new Error(`Frontegg token request failed: ${res.status}`);
const json = await res.json();
return { accessToken: json.access_token, expiresIn: json.expires_in };
};
}
baseUrl is your environment's own Frontegg domain, such as https://{your-subdomain}.frontegg.com, without the /identity path that the API reference shows. Do not use the regional api.frontegg.com hosts from the API reference here: they reject this call unless you also send a vendor JWT, which a customer's service won't have. Plug it in:
import { createTokenProvider } from './token-provider.js';
import { fronteggClientCredentials } from './frontegg.js';
import { callApi } from './call-api.js';
const tokens = createTokenProvider({
fetchToken: fronteggClientCredentials({
baseUrl: process.env.FRONTEGG_BASE_URL,
clientId: process.env.FRONTEGG_CLIENT_ID,
secret: process.env.FRONTEGG_SECRET,
}),
});
const res = await callApi(tokens, `${process.env.API_URL}/invoices`);
console.log(res.status);
Two Frontegg-specific details make the cache matter even more:
- Each authentication issues a refresh token, and they're capped. Refresh token rotation is on by default, and each API token can have at most 100 active refresh tokens. Authenticating a 101st time invalidates the oldest one. A service that authenticates on every request would keep churning through that list. With the cache, it authenticates once per token lifetime.
-
Token lifetime is an environment setting. JWT expiration is configured for the whole environment under Security β JWT, so read
expires_infrom the response instead of hard-coding a lifetime.
Send the token as Authorization: Bearer <token>, which is what callApi already does (M2M token management). Frontegg also supports refreshing with the returned refresh token (Refresh API token); this post sticks to re-authenticating because the cache already keeps that rare.
For a wider look at service-to-service options (API keys, client credentials, mTLS) and when each fits, see Frontegg's guide to M2M authentication.
Hardening checklist
- [ ] Use client credentials only from code that can keep a secret.
- [ ] Load the client ID and secret from a secret manager or environment, never from source control, and never log them or the token.
- [ ] Form-encode the client ID and secret before Base64 for HTTP Basic.
- [ ] Cache the token in memory and compute expiry from
expires_inwhen the response arrives. - [ ] Renew early (a skew of about a minute), capped for short-lived tokens.
- [ ] Share one in-flight token request across concurrent callers.
- [ ] Don't cache failures; let the next call retry.
- [ ] On
401, invalidate that token and retry once. Never loop. - [ ] Ask for the narrowest
scopethe job needs. RFC 9700 section 2.3 recommends least privilege and audience-restricted tokens. - [ ] If your server supports it, consider asymmetric client authentication (mTLS or
private_key_jwt), which RFC 9700 section 2.5 recommends over shared secrets.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.