BFF API Adaptation and Responsibility Boundaries

Shape BFF response fields for each page and distinguish API adaptation from core business rules.

🎯 Introduction

In “Implementing API Aggregation with Node.js,” the BFF fetched an order, then its user and product, and combined all three into order details. The frontend no longer had to orchestrate multiple requests.

However, having all the data does not mean every page needs all of it. A mobile order card displays only the order ID, customer name, product name, and total; desktop details also need quantity and a user link. Returning internal objects unchanged gives both clients unnecessary fields and may create dependencies on information that should not be exposed.

We will keep using the same order data, shape BFF responses for different pages, and explain which tasks belong in the BFF and which business decisions belong in business services.


🧱 Why Different Pages Need API Adaptation

For example, the original order endpoint returns:

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

These fields describe the order but omit the user and product names the page displays. The previous article retrieved those through aggregation. Now consider: which fields does each page actually need?

FieldSourceMobile cardDesktop details
idorder.idRequiredRequired
customerNameuser.nameRequiredRequired
productNameproduct.nameRequiredRequired
totalCentsorder.totalCentsRequiredRequired
quantityorder.quantityNot requiredRequired
user.id, user.nameuserNot requiredRequired for the user link

API adaptation means selecting fields, renaming them, or organizing data according to a page's agreement. This agreement is also called an API contract: the frontend and BFF agree in advance on response fields and their meanings.

For example, the business API uses name, while the page expects customerName; the BFF can rename it. If the page does not need the user's email, omit it. Selecting fields reduces unnecessary data and frontend dependencies on internal API structures. However, field selection does not replace authorization checks.


🛠 Implement API Adaptation in the BFF

Continue with the previous project and mock APIs. Ensure mock.mjs is still running on port 4100, then edit minimal-bff.mjs.

We use the view query parameter to select the response a page needs:

  • view=mobile: A mobile card with only the four shared fields.
  • view=desktop: Desktop details with quantity and user information in addition to the shared fields. This is the default when view is omitted.

For any other value, the BFF immediately returns HTTP 400, avoiding business API calls for an invalid request.

Here is the complete updated minimal-bff.mjs, which can replace the previous file:

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) => {
    // 1. Determine which response the page needs.
    const view = req.query.view ?? 'desktop';
    if (!['desktop', 'mobile'].includes(view)) {
        return res.status(400).json({ error: 'INVALID_VIEW' });
    }

    // 2. Aggregate order, user, and product data, as before.
    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)}`),
    ]);

    // 3. Assemble fields shared by both clients.
    const summary = {
        id: order.id,
        customerName: user.name,
        productName: product.name,
        totalCents: order.totalCents,
    };

    // 4. Select the response structure for the page.
    if (view === 'mobile') {
        return res.json(summary);
    }

    res.json({
        ...summary,
        quantity: order.quantity,
        user: { id: user.id, name: user.name },
    });
});

// Keep the previous simplified error handling; real projects need finer error classification.
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'));

The code adds two main behaviors:

  1. Validate view: req.query.view reads the URL query parameter. Invalid values return 400; valid values proceed to the order query.
  2. Return fields for each page: summary holds shared data. Mobile receives it directly; desktop spreads the shared fields with ...summary, then adds quantity and user.

The desktop response contains both customerName and user.name: the first appears in the order summary, while the second is used with user.id for a user link. This is a deliberate contract for this example, not a requirement to duplicate names in every project.

Whichever view is selected, the BFF queries the same order, user, and product data. The response structure changes, not the order itself.


🧪 Verify Responses for Different Pages

Keep the mock backend running and restart the BFF after editing:

node minimal-bff.mjs

Request mobile data from another terminal:

curl 'http://127.0.0.1:4000/bff/orders/o1?view=mobile'

Expected response:

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

Then request desktop data:

curl 'http://127.0.0.1:4000/bff/orders/o1?view=desktop'

Expected response:

{
  "id": "o1",
  "customerName": "Lin",
  "productName": "Mechanical Keyboard",
  "totalCents": 59800,
  "quantity": 2,
  "user": {
    "id": "u1",
    "name": "Lin"
  }
}

Finally, test an invalid parameter:

curl -i 'http://127.0.0.1:4000/bff/orders/o1?view=unknown'

Expect HTTP 400 with this response body:

{
  "error": "INVALID_VIEW"
}

Also omit view and confirm that the default is the desktop structure. Compare the successful responses: mobile receives only four required fields, desktop receives additional details, and neither includes the user's email.

This article uses view to make the responses easy to test. Real projects can use separate routes. Avoid accumulating an unmaintainable set of branches in one endpoint as more pages are added.


⚖️ Responsibility Boundaries Between the BFF and Business Services

Now that the BFF can shape responses, should it also calculate discounted prices or decide whether an order can be canceled?

Do not move core business rules into the BFF merely because it is convenient.

Ask whether the logic only organizes page data or determines whether a business operation is allowed.

OperationAppropriate locationReason
Rename name to customerNameBFFChanges a field's representation
Combine order, user, and product dataBFFBuilds the response needed by a page
Omit fields mobile does not needBFFAdapts the page data structure
Validate coupons and calculate the amount dueBusiness serviceEnforces consistent transaction rules
Decide whether an order can be canceledOrder serviceEnforces consistent order state rules
Check whether a user may act on an orderServer-side authorization logic, enforced by business servicesUI controls or field selection alone cannot protect operations
Display canCancel: false as a disabled buttonFrontend (the BFF may adapt the field)Presents a result already determined by the business service

For example, when the order service returns canCancel: false, the frontend can disable “Cancel order.” The BFF may include that field in the page response, but should not duplicate the order state rules. When the user actually requests cancellation, the business service must check again because the order state may have changed.

Likewise, totalCents uses the amount saved in the order, rather than recalculating it from the product's current price: the amount charged is a transaction rule, not page field adaptation.

In this course's architecture, the BFF retrieves data through business APIs rather than accessing service databases directly. Business services can then change their internal storage without forcing the page adaptation layer to rewrite database queries.


❓ Questions and Answers

Q1: If the frontend can select fields, why adapt them in a BFF?

For simple needs, frontend processing is perfectly reasonable. A BFF lets multiple pages or clients reuse server-side composition logic without sending every internal field to the browser. It also adds maintenance cost, so it is not necessary for every project.

Q2: If the BFF omits sensitive fields, are authorization checks still necessary?

Yes. Field selection decides which fields to return; authorization decides whether this user may access the data or perform an operation. Omitting email does not make it acceptable for anyone to query other people's orders.


🧪 Exercise

Add a new page requirement: an order receipt summary. Support view=receipt in the BFF and return only the order ID, quantity, and total.

Update the allowed view values and add a response branch, preserving the existing mobile, desktop, and default behavior.

Then request:

curl 'http://127.0.0.1:4000/bff/orders/o1?view=receipt'

Expected result:

{
  "id": "o1",
  "quantity": 2,
  "totalCents": 59800
}

Confirm that view=unknown still returns 400. Why must totalCents come from the order rather than be recalculated using the current product price?

The “receipt summary” here is only a field selection exercise, not an official invoice or complete transaction receipt.


🎉 You can now adapt BFF responses for different pages and distinguish presentation logic from core business rules!