Xero Node.js SDK (OAuth 2.0 Client)

15.0.0 · active · verified Sun Apr 19

The xero-node SDK provides a comprehensive client for interacting with the Xero APIs (Accounting, Assets, Bankfeeds, Files, Projects, Payroll AU/NZ/UK) using Node.js. It facilitates OAuth 2.0 authentication and API requests, simplifying integration for developers building applications that connect with Xero accounting data. The library is currently in its 15.0.0 major version, with frequent updates (multiple minor/patch releases per month, and major releases roughly every few months) to reflect changes in the underlying Xero API and add new features. Key differentiators include full API coverage across multiple Xero API sets and robust TypeScript support, making it suitable for enterprise-grade integrations requiring strong typing and reliability.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates initializing the XeroClient, managing an access token (refreshing if expired), and making a basic API call to fetch contacts. Requires valid Xero API credentials and an existing tenant ID.

import { XeroClient, Contact, Contacts } from 'xero-node';
import { Response } from 'node-fetch';

const client_id = process.env.XERO_CLIENT_ID ?? '';
const client_secret = process.env.XERO_CLIENT_SECRET ?? '';
const redirect_uri = process.env.XERO_REDIRECT_URI ?? 'http://localhost:3000/callback';
const scopes = ['accounting.contacts.read', 'offline_access'];

const xero = new XeroClient({
  clientId: client_id,
  clientSecret: client_secret,
  redirectUris: [redirect_uri],
  scopes: scopes,
});

async function authenticateAndFetchContacts() {
  if (!client_id || !client_secret) {
    console.error('XERO_CLIENT_ID and XERO_CLIENT_SECRET environment variables must be set.');
    return;
  }

  // In a real application, you would store and retrieve tokens securely.
  // This is a simplified example to get a token via a mock code (requires a valid initial auth flow).
  // For a real-world scenario, you'd perform the OAuth2 dance.
  // For demonstration purposes, we assume a refresh token is available or use a pre-authorized token.
  
  // Example of setting a token from a previous authorization (replace with actual token management)
  xero.setTokenSet({
    access_token: process.env.XERO_ACCESS_TOKEN ?? 'YOUR_INITIAL_ACCESS_TOKEN',
    refresh_token: process.env.XERO_REFRESH_TOKEN ?? 'YOUR_INITIAL_REFRESH_TOKEN',
    expires_at: Date.now() / 1000 + 3600 // Example: expires in 1 hour
  });

  try {
    // Ensure token is fresh
    if (await xero.apiClient.checkTokenSet() && xero.apiClient.tokenSet.expired()) {
        console.log('Access token expired, attempting to refresh...');
        await xero.apiClient.refreshToken();
        console.log('Token refreshed successfully.');
    }

    console.log('Fetching contacts...');
    const contactsResponse = await xero.accountingApi.getContacts(xero.tenantIds[0]);
    const contacts = contactsResponse.body.contacts;
    
    if (contacts && contacts.length > 0) {
      console.log(`Found ${contacts.length} contacts. First contact: ${contacts[0].name}`);
    } else {
      console.log('No contacts found.');
    }
  } catch (error) {
    console.error('Error fetching contacts:', error);
    if (error instanceof Response) {
      const errorBody = await error.text();
      console.error('API Error Response:', errorBody);
    }
  }
}

authenticateAndFetchContacts();

view raw JSON →