今日已更新 177 条资讯 | 累计 42235 条内容
关于我们

Using Next.js as a Backend for Frontend (BFF)

Abanoub Kerols 2026年09月12日 05:34 3 次阅读 来源:Dev.to

When building a modern web application, the frontend often needs to communicate with multiple backend services: Browser │ ├── Auth Service ├── Product Service ├── Order Service └── Notification Service This works, but it makes the frontend tightly coupled to the backend architecture. A better approach in some systems is to introduce a Backend for Frontend (BFF) . Browser │ ▼ Next.js BFF │ ├── Auth Service ├── Product Service ├── Order Service └── Notification Service What is a BFF? A BFF is a backend layer specifically designed for a particular frontend. Instead of exposing all backend services directly to the browser, the frontend communicates with the BFF, and the BFF communicates with the internal services. This gives us a place to handle: Authentication Authorization Request validation API aggregation Response transformation Caching Hiding internal service URLs Next.js as a BFF Next.js can implement a BFF using Route Handlers . For example: app/ └── api/ └── products/ └── route.ts // app/api/products/route.ts export async function GET () { const response = await fetch ( ` ${ process . env . PRODUCT_SERVICE_URL } /products` ); if ( ! response . ok ) { return Response . json ( { message : " Failed to fetch products " }, { status : 500 } ); } const products = await response . json (); return Response . json ( products ); } Now the browser calls: GET /api/products Instead of directly calling: GET http://product-service:3002/products The architecture becomes: Browser │ │ GET /api/products ▼ Next.js BFF │ │ GET /products ▼ Product Service The internal service URL remains server-side. API Aggregation One of the most useful BFF features is aggregation . Imagine a dashboard needs data from four different services: User Service Order Service Notification Service Recommendation Service Instead of making four requests from the browser: Browser ├── GET /users/me ├── GET /orders ├── GET /notifications └── GET /recommendations The BFF can expose a single endpoint: GET /api/das

本文内容来源于互联网,版权归原作者所有
查看原文