Minimal token auth wrapper for Node.js: authenticate, refresh and retry on 401 errors.
Node.js
Category: Code Library • Tags: nodejs, betfair, auth • Published: PUBLISH_DATE Contents
Problem
Long-running clients need a simple pattern for token refresh and retry logic to avoid downtime when tokens expire.
Solution — copyable code
Copy// index.js - minimal token auth wrapper (Node.js)
// Replace identity endpoints and API_KEY with real provider values.
const fetch = require('node-fetch');
let token = null;
let tokenExpires = 0;
async function authenticate(apiKey) {
const res = await fetch('https://identity.example.com/token', {
method: 'POST',
headers: { 'X-API-Key': apiKey, 'Content-Type': 'application/json' }
});
if (!res.ok) throw new Error(`Auth failed: ${res.status}`);
const json = await res.json();
token = json.token;
tokenExpires = Date.now() + (json.expires_in || 3600) * 1000;
return token;
}
async function withAuth(apiKey, fn) {
if (!token || Date.now() > tokenExpires - 60000) {
await authenticate(apiKey);
}
try {
return await fn(token);
} catch (err) {
if (err && err.status === 401) {
await authenticate(apiKey);
return await fn(token);
}
throw err;
}
}
module.exports = { withAuth };
Usage notes
- Store API keys securely (env vars or secret manager).
- Add backoff/rate-limit handling for production-grade usage.
- Do not log secrets or tokens in plaintext.
License: MIT
