Prompt

How do I build a Backend for Frontend?

Technology / Developer Tools4 observationsLast seen Nov 25, 2026

Latest observation

Nov 25, 2026OpenAI APIWeb search: off

A Backend for Frontend (BFF) is a thin backend layer tailored to a specific client experience—like web, mobile, or admin UI. Its job is to make the frontend simpler by handling API orchestration, aggregation, auth/session handling, and response shaping close to the client’s needs.

When you should build one

Use a BFF when:

  • You have multiple frontends with different data needs
  • Your frontend has to call many backend services
  • You need to hide backend complexity from the UI
  • You want client-specific auth/session logic
  • You need to reduce round trips or improve performance

Don’t build one if:

  • Your app is small and a direct API is enough
  • The frontend can already consume your API cleanly
  • You’re just trying to “move logic out of the frontend” without a clear reason

Core responsibilities of a BFF

A good BFF typically handles:

  1. API aggregation

    • Call multiple downstream services and merge results
    • Example: one endpoint returns profile, orders, and recommendations together
  2. Response shaping

    • Transform backend data into exactly what the UI needs
    • Remove fields the frontend shouldn’t care about
  3. Client-specific logic

    • Different endpoints or formatting for web vs mobile
    • Example: mobile gets smaller payloads
  4. Authentication and session management

    • Manage tokens, cookies, CSRF protection, refresh flow
    • Often sits close to the browser or app
  5. Caching

    • Cache expensive or frequently requested data
    • Use short-lived caches carefully to avoid stale data
  6. Resilience

    • Timeouts, retries, fallbacks, partial responses
    • Prevent one failing service from taking down the UI
  7. Security

    • Keep secrets off the client
    • Enforce authorization and rate limits

Recommended architecture

A common setup:

  • Frontend app → BFF → downstream services
  • BFF is usually one per client type:
    • web-bff
    • mobile-bff
    • admin-bff

This avoids forcing one backend contract to satisfy every client.


How to build one step by step

1. Define the frontend use cases

Start from screens, not services. For each page or flow, list:

  • What data is needed?
  • What actions does the user take?
  • Which backend services are involved?
  • What can be loaded lazily?

This helps you design BFF endpoints around user journeys.


2. Design BFF endpoints around UI needs

Don’t mirror microservices directly. Instead, make endpoints like:

  • GET /home
  • GET /dashboard
  • GET /profile
  • POST /checkout

Each endpoint should return exactly what the frontend needs.

Example:

{
  "user": {
    "name": "Ada",
    "membership": "Gold"
  },
  "orders": [
    { "id": "123", "status": "Shipped" }
  ],
  "recommendations": [
    { "id": "a1", "title": "Wireless Mouse" }
  ]
}

3. Orchestrate downstream calls

The BFF calls internal services in parallel when possible.

Example flow:

  • Call user service for profile
  • Call orders service for recent orders
  • Call recommendations service
  • Merge responses
  • Return a single response

Use:

  • Async I/O
  • Request timeouts
  • Circuit breakers where appropriate

4. Handle auth properly

Common patterns:

  • Browser authenticates with the BFF using cookies/session
  • BFF exchanges or forwards tokens to downstream APIs
  • BFF validates user identity and permissions

Be careful with:

  • Token storage
  • CSRF if using cookies
  • Scope/claim propagation
  • Least privilege

5. Add caching and performance controls

Useful caching options:

  • In-memory cache for short-lived data
  • Redis for shared cache
  • HTTP caching headers when relevant

Also:

  • Set strict timeouts
  • Use pagination
  • Avoid overfetching
  • Batch requests where helpful

6. Add observability

You’ll want:

  • Structured logs
  • Distributed tracing
  • Metrics on latency and error rate
  • Correlation IDs across services

This is especially important because a BFF often hides multiple downstream failures.


7. Keep the BFF thin

A BFF should not become a “mini monolith.” Avoid putting:

  • Business rules that belong in domain services
  • Database access to unrelated systems
  • Shared logic used by many clients

The BFF should mostly:

  • compose
  • transform
  • secure
  • optimize for the frontend

Example implementation idea

Node.js/Express example

import express from "express";
import fetch from "node-fetch";

const app = express();

app.get("/dashboard", async (req, res) => {
  const userId = req.headers["x-user-id"];

  const [profileRes, ordersRes] = await Promise.all([
    fetch(`http://user-service/users/${userId}`),
    fetch(`http://order-service/orders?userId=${userId}&limit=5`)
  ]);

  const profile = await profileRes.json();
  const orders = await ordersRes.json();

  res.json({
    user: {
      name: profile.name,
      membership: profile.membership
    },
    recentOrders: orders.items.map(o => ({
      id: o.id,
      status: o.status
    }))
  });
});

app.listen(3000);

This is the essence of a BFF: one frontend-friendly endpoint that composes multiple backend calls.


Best practices

  • Build a separate BFF per major client type
  • Design endpoints from UI requirements
  • Keep BFF logic simple and compositional
  • Use DTOs/view models, not raw backend objects
  • Apply auth, rate limiting, and input validation
  • Set timeouts on every downstream call
  • Use retries carefully, only for safe operations
  • Monitor latency and downstream dependency health

Common mistakes

  • Making the BFF a second backend monolith
  • Mirroring microservices one-to-one
  • Putting business logic in the BFF
  • Ignoring auth/token propagation
  • Not handling partial failures
  • Returning too much data to the client

A good rule of thumb

If a frontend developer says, “I need three APIs and have to join them myself for this screen,” that’s a strong sign a BFF would help.

If you want, I can also show:

  1. a reference architecture diagram,
  2. a real-world folder structure, or
  3. an example BFF in Node.js, Python, or .NET.

Observation history

How did Obsurfable measure this prompt?

Obsurfable records AI answers to buyer-style prompts in its research corpus (4 observations for this page). Metrics are distributions over observations, not a single static ranking.

Which AI systems does Obsurfable collect answers from?

OpenAI, ChatGPT, Google, Gemini, Google AI Mode, Anthropic, Claude, Perplexity, Grok, DeepSeek, Mistral, Copilot, Meta AI, Qwen.

How can brands improve their AEO?

Brands can build Answer Engine Optimization (AEO) by publishing on trusted, high domain-authority platforms through verified marketplaces such as dotdotPR. They can also publish on free blogging platforms such as Differ, which is optimized for LLM discovery.

Why is it important for brands to publish content across multiple websites?

Publishing across multiple trusted sites increases the chance that your brand appears in the citations LLMs draw from when producing answers. Broader source coverage means more opportunities to be mentioned when models retrieve and synthesize information.

Want this interpreted for your brand?

Explorer is the free public corpus. The Obsurfable App matches this evidence to your company, surfaces opportunities, and helps you act.