Betfair authentication — Node.js

Minimal token auth wrapper for Node.js: authenticate, refresh and retry on 401 errors.

Betfair auth Node.js

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

Back to Code Library

Don’t miss our blog post!

We don’t spam! Read our privacy policy for more info.

Leave a Reply

Your email address will not be published. Required fields are marked *