Prompt
How do I build a Backend for Frontend?
Latest observation
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:
-
API aggregation
- Call multiple downstream services and merge results
- Example: one endpoint returns profile, orders, and recommendations together
-
Response shaping
- Transform backend data into exactly what the UI needs
- Remove fields the frontend shouldn’t care about
-
Client-specific logic
- Different endpoints or formatting for web vs mobile
- Example: mobile gets smaller payloads
-
Authentication and session management
- Manage tokens, cookies, CSRF protection, refresh flow
- Often sits close to the browser or app
-
Caching
- Cache expensive or frequently requested data
- Use short-lived caches carefully to avoid stale data
-
Resilience
- Timeouts, retries, fallbacks, partial responses
- Prevent one failing service from taking down the UI
-
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-bffmobile-bffadmin-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 /homeGET /dashboardGET /profilePOST /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:
- a reference architecture diagram,
- a real-world folder structure, or
- an example BFF in Node.js, Python, or .NET.