Implementing API Aggregation with Node.js

Aggregate data for an order details page using Express and Promise.all.

🎯 Introduction

Suppose you are building an order details page that displays the total, customer, and product name. The backend exposes this information through three endpoints: the order endpoint provides userId and productId, which the frontend must use to query the user and product.

Without a BFF, the frontend might orchestrate requests like this (error handling is omitted):

const order = await fetch('/orders/o1').then(res => res.json());
const user = await fetch(`/users/${order.userId}`).then(res => res.json());
const product = await fetch(`/products/${order.productId}`).then(res => res.json());

The page must make several requests and understand how the three datasets relate. A BFF moves these steps to the server, leaving the frontend with one aggregated endpoint to call:

const detail = await fetch('/bff/orders/o1').then(res => res.json());

API aggregation means calling multiple data sources through one endpoint and shaping the results for the caller. It reduces the requests the frontend must orchestrate, but does not mean the backend accesses only one data source.

This article uses Node.js, Express, and Promise.all to aggregate order details. You will fetch prerequisite data first, query independent data concurrently, and return JSON the page can use directly.


🧰 Prepare Mock Business APIs

Extract the course example and enter its directory. This article uses Node.js 22 and Express 5.1.0, with dependency versions locked by package-lock.json:

cd backend-architecture-course
node --version
npm ci

We use only data.mjs, mock.mjs, and minimal-bff.mjs. Start with the mock data in data.mjs:

export const users = [{ id: 'u1', name: 'Lin', email: 'lin@example.test' }];
export const products = [{ id: 'p1', name: 'Mechanical Keyboard', priceCents: 29900 }];
export const orders = [{ id: 'o1', userId: 'u1', productId: 'p1', quantity: 2, totalCents: 59800 }];

In order o1, userId: 'u1' refers to Lin and productId: 'p1' refers to the mechanical keyboard. priceCents and totalCents store amounts in fen (hundredths of a yuan): 59800 represents 598 yuan.

Next, use mock.mjs to expose three mock business endpoints:

import express from 'express';
import { users, products, orders } from './data.mjs';

const app = express();

for (const [resource, rows] of Object.entries({ users, products, orders })) {
    app.get(`/${resource}/:id`, (req, res) => {
        const row = rows.find(item => item.id === req.params.id);
        res.status(row ? 200 : 404).json(row ?? { error: 'NOT_FOUND' });
    });
}

app.listen(4100, '127.0.0.1', () => console.log('mock on 4100'));

The loop simply avoids repetitive code. It creates detail routes for users, products, and orders, finds a record using the URL's :id, and returns JSON, or 404 if no record exists.

RequestReturned data
GET /orders/o1Order: user ID, product ID, quantity, total
GET /users/u1User: name, email
GET /products/p1Product: name, unit price

Open terminal A and start the mock backend:

node mock.mjs

Use another terminal to check the order endpoint:

curl http://127.0.0.1:4100/orders/o1

The response body should be:

{
  "id": "o1",
  "userId": "u1",
  "productId": "p1",
  "quantity": 2,
  "totalCents": 59800
}

This endpoint does not yet return the user and product names. The BFF will use the order's two IDs to retrieve the remaining page data.


🛠 Create the BFF and Fetch the Order

Create the BFF in minimal-bff.mjs. Here is the complete code; we will then walk through its execution:

import express from 'express';

const app = express();

async function read(path) {
    const response = await fetch(`http://127.0.0.1:4100${path}`);
    if (!response.ok) throw new Error(`upstream status ${response.status}`);
    return response.json();
}

app.get('/bff/orders/:id', async (req, res) => {
    const order = await read(`/orders/${encodeURIComponent(req.params.id)}`);

    const [user, product] = await Promise.all([
        read(`/users/${encodeURIComponent(order.userId)}`),
        read(`/products/${encodeURIComponent(order.productId)}`),
    ]);

    res.json({
        id: order.id,
        customerName: user.name,
        productName: product.name,
        totalCents: order.totalCents,
    });
});

app.use((error, req, res, next) => {
    res.status(502).json({ error: 'UPSTREAM_ERROR' });
});

app.listen(4000, '127.0.0.1', () => console.log('minimal bff on 4000'));

Open terminal B and run:

node minimal-bff.mjs

Keep both services running: the mock backend listens on 4100, and the BFF on 4000. The frontend requests the BFF, which calls the mock backend over HTTP.

Start with this line:

const order = await read(`/orders/${encodeURIComponent(req.params.id)}`);

For /bff/orders/o1, req.params.id is o1. The BFF first calls /orders/o1 on the mock backend to fetch the order. encodeURIComponent encodes the ID for a URL path so special characters do not interfere with its structure.

read(path) is a simple shared request function: fetch sends the request, response.ok checks the HTTP status, and response.json() parses JSON. We only know which user and product to query after receiving the order.


⚡ Fetch the User and Product Concurrently with Promise.all

The order query must finish first because it supplies both IDs. Once those IDs are available, the user and product queries do not depend on each other.

With sequential requests:

const user = await read(`/users/${order.userId}`);
const product = await read(`/products/${order.productId}`);

The second request waits for the first to finish. Replace them with concurrent requests:

const [user, product] = await Promise.all([
    read(`/users/${encodeURIComponent(order.userId)}`),
    read(`/products/${encodeURIComponent(order.productId)}`),
]);

The two read() calls run in sequence, each starting its own request. Promise.all waits for both to succeed, then assigns their results to user and product. Even if the product arrives first, the result array preserves input order: user first, product second.

If the user query takes 100 ms and the product query takes 150 ms, sequential waiting takes about 250 ms, while the concurrent stage usually takes around 150 ms. These are illustrative times; actual timing also depends on the network and servers. The preceding order query still adds its own duration.

Two failure behaviors also matter:

  • If any request in Promise.all fails, the combined wait fails, but other pending requests are not automatically canceled.
  • fetch does not throw solely because it receives HTTP 404 or 500. read() must check response.ok and decide whether to throw.

This article returns order details only when both user and product data load successfully; missing data is not treated as a normal value. See the Node.js documentation for more about fetch.


🧩 Shape the JSON for the Page

The BFF now has all three datasets. Select the fields the page needs:

res.json({
    id: order.id,
    customerName: user.name,
    productName: product.name,
    totalCents: order.totalCents,
});

The final API response is:

{
  "id": "o1",
  "customerName": "Lin",
  "productName": "Mechanical Keyboard",
  "totalCents": 59800
}

Compare this with the original order JSON: userId and productId have been replaced with customerName and productName, which the page can display directly. The total still comes from the order endpoint and needs no recalculation. The user's email is omitted because this page does not need it.

That is the BFF's role here: resolve relationships and compose data on the server so the frontend receives a structure suited to the page.


🧪 Verify Aggregation and Failure Responses

In a third terminal, run:

curl -i http://127.0.0.1:4000/bff/orders/o1

Expect HTTP 200 and the aggregated JSON from the previous section (curl -i also prints response headers). The frontend only calls /bff/orders/o1, instead of making separate order, user, and product requests; the BFF still calls all three business endpoints internally.

Now request an order that does not exist:

curl -i http://127.0.0.1:4000/bff/orders/missing

The mock order endpoint returns 404, and read() throws because response.ok is false. This example's error-handling middleware returns 502 for all such errors, with this body:

{
  "error": "UPSTREAM_ERROR"
}

In Express 5, errors thrown by async routes are automatically passed to error-handling middleware. The four parameters in app.use((error, req, res, next) => ...) identify it as an error handler. Keep next even though it is currently unused.

Returning 502 here is a simplification, not a rule that missing orders should always return 502. A real service must distinguish missing resources from upstream failures and add timeouts and logging. “Handling Service Call Failures” covers those concerns later; this article focuses on aggregation.


❓ Questions and Answers

Q1: Why not put the order, user, and product requests together in Promise.all?

The user and product IDs must first be read from the order. Fetch the order first, then query the independent user and product data concurrently.

Q2: Why not return the entire user object?

The order page only needs the name, not fields such as email. Returning only required fields better matches the page and avoids unintentionally exposing extra information. The next article explores field selection further.


🧪 Exercise

Add order o2 to the orders array in data.mjs, with userId set to u1, productId to p1, quantity to 1, and totalCents to 29900.

After editing, restart only the mock backend, mock.mjs; the BFF does not need restarting. Then run:

curl http://127.0.0.1:4000/bff/orders/o2

Success criteria: the response has id: o2 and totalCents: 29900, with “Lin” and “Mechanical Keyboard” unchanged. Then request a missing order ID and observe why this example returns 502.


🎉 You have aggregated order details using Express and Promise.all!