Quick Start: Connect to FXMacroData with Node.js banner image

By Language

Quick Start Guides

Quick Start: Connect to FXMacroData with Node.js

Get up and running with FXMacroData in Node.js in minutes. Covers the built-in fetch API, async/await patterns, multi-indicator requests, and a ready-to-run script for pulling central bank data.

The FXMacroData REST API is designed to be consumed from any language that can make an HTTP GET request. Node.js ships with a built-in fetch implementation from v18 onwards, so there is nothing extra to install for basic usage — just your API key and a few lines of JavaScript. This guide walks you from zero to a working multi-indicator script in under ten minutes.

What You Will Build

A self-contained Node.js script that authenticates against the FXMacroData REST API, fetches policy rate and inflation data for multiple G10 currencies in parallel, and prints a clean summary table to the console — ready to drop into any backend, serverless function, or automation pipeline.

Prerequisites

  • Node.js 18 or later — v18 introduced the global fetch API; v20+ is recommended for production
  • npm (bundled with Node.js) — only needed if you choose to add optional packages
  • A FXMacroData API key — sign up at /subscribe and copy your key from the dashboard

Check your Node.js version:

node --version   # should print v18.x.x or later

Step 1 — Store Your API Key Safely

Never hard-code an API key in source files that could be committed to version control. The simplest safe approach is an environment variable read at runtime.

On Linux / macOS, add to your shell profile (~/.bashrc or ~/.zshrc):

export FXMD_API_KEY="your_actual_api_key_here"

On Windows (PowerShell):

$env:FXMD_API_KEY = "your_actual_api_key_here"

For Node.js projects, a .env file with the dotenv package is a popular alternative — see Step 6 for that setup.

Step 2 — Understand the API Shape

Every FXMacroData indicator endpoint follows the same pattern, which makes it straightforward to build a generic fetch helper. Here is the base structure:

GET https://fxmacrodata.com/api/v1/announcements/{currency}/{indicator}?api_key=YOUR_API_KEY

The response is JSON with a top-level data array. Each element carries a date, a numeric val, and (for most indicators) an announcement_datetime that pinpoints the second the value was released:

{
  "data": [
    { "date": "2025-03-19", "val": 4.25, "announcement_datetime": "2025-03-19T18:00:00Z" },
    { "date": "2025-01-29", "val": 4.25, "announcement_datetime": "2025-01-29T19:00:00Z" },
    { "date": "2024-12-18", "val": 4.25, "announcement_datetime": "2024-12-18T19:00:00Z" }
  ]
}

This clean, consistent structure requires almost no transformation before use in business logic, databases, or downstream APIs.

Step 3 — Your First Fetch Call

Create a file called fxmd.js and add the following. This fetches the US Federal Reserve policy rate for the last two years using Node.js's built-in fetch:

// fxmd.js  —  requires Node.js 18+
const API_KEY = process.env.FXMD_API_KEY;
const BASE    = "https://fxmacrodata.com/api/v1";

async function getIndicator(currency, indicator, startDate) {
  const url = new URL(`${BASE}/announcements/${currency}/${indicator}`);
  url.searchParams.set("api_key", API_KEY);
  if (startDate) url.searchParams.set("start", startDate);

  const res = await fetch(url.toString());
  if (!res.ok) {
    throw new Error(`API error ${res.status}: ${await res.text()}`);
  }
  const json = await res.json();
  return json.data ?? [];
}

// Fetch the Fed policy rate
const data = await getIndicator("usd", "policy_rate", "2023-01-01");
console.log(`Latest USD policy rate: ${data[0]?.val}% on ${data[0]?.date}`);

Run it:

FXMD_API_KEY=your_key node fxmd.js

Top-level await — the example above uses top-level await. This works in .mjs files or when "type": "module" is set in your package.json. For CommonJS modules wrap the calls in an async function and call it immediately (see the complete example in Step 5).

Step 4 — Fetch Multiple Indicators in Parallel

Promise.all fires all requests concurrently, so fetching a dozen indicators takes roughly the same wall-clock time as fetching one. Here is a reusable pattern for pulling several currencies and indicators at once:

const CURRENCIES  = ["usd", "eur", "gbp", "aud", "jpy"];
const INDICATORS  = ["policy_rate", "inflation"];
const START       = "2024-01-01";

// Build a flat list of [currency, indicator] pairs
const pairs = CURRENCIES.flatMap(c => INDICATORS.map(i => [c, i]));

// Fire all requests in parallel
const results = await Promise.all(
  pairs.map(([currency, indicator]) =>
    getIndicator(currency, indicator, START)
      .then(data => ({ currency, indicator, latest: data[0] ?? null }))
      .catch(err => ({ currency, indicator, latest: null, error: err.message }))
  )
);

// Print a quick summary
for (const row of results) {
  if (row.error) {
    console.log(`${row.currency.toUpperCase()} ${row.indicator}: ERROR — ${row.error}`);
  } else if (row.latest) {
    console.log(
      `${row.currency.toUpperCase()} ${row.indicator}: ${row.latest.val} (${row.latest.date})`
    );
  }
}

The .catch per request means a single bad response does not abort the whole batch — useful when running nightly jobs where partial data is still actionable.

Step 5 — Complete Production-Ready Script

Below is a full CommonJS-compatible script with proper error handling, configurable currency and indicator lists, and output formatted for logging or downstream processing:

// macro-snapshot.js  —  CommonJS, Node.js 18+
"use strict";

const API_KEY = process.env.FXMD_API_KEY;
const BASE    = "https://fxmacrodata.com/api/v1";

if (!API_KEY) {
  console.error("Error: FXMD_API_KEY environment variable is not set.");
  process.exit(1);
}

// ── Configuration ──────────────────────────────────────────────────────────
const CURRENCIES = ["usd", "eur", "gbp", "cad", "jpy", "aud", "nzd", "chf"];
const INDICATORS = ["policy_rate", "inflation", "unemployment"];
const START_DATE = "2024-01-01";
// ───────────────────────────────────────────────────────────────────────────

async function getIndicator(currency, indicator, startDate) {
  const url = new URL(`${BASE}/announcements/${currency}/${indicator}`);
  url.searchParams.set("api_key", API_KEY);
  if (startDate) url.searchParams.set("start", startDate);

  const res = await fetch(url.toString());
  if (!res.ok) {
    const body = await res.text().catch(() => "");
    throw new Error(`HTTP ${res.status}${body ? ": " + body.slice(0, 120) : ""}`);
  }
  const json = await res.json();
  return Array.isArray(json.data) ? json.data : [];
}

async function main() {
  const pairs = CURRENCIES.flatMap(c => INDICATORS.map(i => [c, i]));

  const results = await Promise.all(
    pairs.map(async ([currency, indicator]) => {
      try {
        const data = await getIndicator(currency, indicator, START_DATE);
        return { currency, indicator, latest: data[0] ?? null, error: null };
      } catch (err) {
        return { currency, indicator, latest: null, error: err.message };
      }
    })
  );

  // Group by currency for readable output
  const byCurrency = {};
  for (const row of results) {
    if (!byCurrency[row.currency]) byCurrency[row.currency] = [];
    byCurrency[row.currency].push(row);
  }

  console.log("\n=== FXMacroData Macro Snapshot ===\n");
  for (const [currency, rows] of Object.entries(byCurrency)) {
    console.log(`  ${currency.toUpperCase()}`);
    for (const row of rows) {
      if (row.error) {
        console.log(`    ${row.indicator.padEnd(20)} — error: ${row.error}`);
      } else if (row.latest) {
        console.log(
          `    ${row.indicator.padEnd(20)} ${String(row.latest.val).padStart(8)}  (${row.latest.date})`
        );
      } else {
        console.log(`    ${row.indicator.padEnd(20)} — no data`);
      }
    }
    console.log();
  }
}

main().catch(err => {
  console.error("Fatal:", err.message);
  process.exit(1);
});

Run the script:

FXMD_API_KEY=your_key node macro-snapshot.js

Sample output:

=== FXMacroData Macro Snapshot ===

  USD
    policy_rate             4.25  (2025-03-19)
    inflation               2.40  (2025-04-10)
    unemployment            4.20  (2025-04-04)

  EUR
    policy_rate             2.40  (2025-04-17)
    inflation               2.20  (2025-04-16)
    unemployment            6.10  (2025-03-31)

  GBP
    policy_rate             4.50  (2025-03-20)
    inflation               2.60  (2025-03-26)
    unemployment            4.40  (2025-04-15)
  ...

Step 6 — Using dotenv for Local Development

When building a larger Node.js project it is more convenient to keep your API key in a .env file and load it automatically with the dotenv package:

npm install dotenv

Create a .env file in your project root (add it to .gitignore immediately):

FXMD_API_KEY=your_actual_api_key_here

Add one line to the top of your script:

require("dotenv").config();   // CommonJS
// or
import "dotenv/config";       // ES module

The rest of the script reads process.env.FXMD_API_KEY exactly as before — no other changes needed.

In production (Cloud Functions, AWS Lambda, Vercel, Render, etc.) inject FXMD_API_KEY as a secure environment variable through the platform's secrets manager. Never commit a .env file to source control.

Step 7 — Explore the Full Indicator Catalogue

The macro snapshot above covers three indicators, but FXMacroData exposes more than 80 time series across 14 major currency blocs. The same getIndicator helper works for all of them — just swap the currency and indicator slug. A few high-value examples for FX traders:

  • Real rates — subtract inflation from policy_rate to compute the real rate differential between two currencies, a core driver of medium-term FX direction. See the USD policy rate docs for endpoint details.
  • Labour dataunemployment, non_farm_payrolls, and average_hourly_earnings (USD) give early signals on central-bank reaction functions.
  • Sentimentconsumer_confidence, pmi, and business_confidence lead hard-data indicators by one to two months and can precede currency moves before they appear in rate decisions.
  • Trade flowstrade_balance, exports, and imports link commodity-currency pairs (AUD, NZD, CAD) to terms-of-trade shifts.

Browse the full catalogue for any currency at https://fxmacrodata.com/api/v1/catalogue/{currency}?api_key=YOUR_API_KEY, or explore the interactive docs at api-data-docs.

Summary

You now have everything you need to consume FXMacroData from Node.js:

  • A generic getIndicator(currency, indicator, startDate) helper that handles auth and error checking
  • Parallel multi-indicator requests via Promise.all with per-request error isolation
  • A production-ready script you can schedule, deploy to a serverless function, or integrate into an existing Node.js backend
  • Safe API key management via environment variables or dotenv

Natural next steps: schedule the snapshot script with a cron job or a task runner like n8n, push the results to a database, or feed them into a trading algorithm. The same clean JSON structure the script reads works identically whether you are building a React dashboard, an Express API, or a Cloud Function trigger.

For more language-specific guides see the Quick Start Guides section — the Python and R walkthroughs cover the same indicator set with ecosystem-specific tooling for analysis and visualisation.