The Backend-for-Frontend pattern using NextJS A Step-by-Step Guide
Editor's Note: While this post offers valuable insights and focuses on the WunderGraph SDK, our main focus is WunderGraph Cosmo , designed to revolutionize API and GraphQL management. As our flagship product, Cosmo empowers teams by streamlining and elevating their API workflows, making it an essential solution for modern GraphQL Federation. If you're exploring GraphQL Federation solutions, explore the key features of WunderGraph Cosmo to see how it can transform your approach.
The BFF (Backend for Frontend) pattern, originally pioneered by SoundCloud , has had its era, much like SoundCloudâs own evolution. Today, SoundCloud stands as a proud customer and power user of WunderGraph Cosmo. If you're interested in learning how they transitioned from the BFF pattern to a federated GraphQL approach, weâd be happy to chatâbook a time with us!
Introducing WunderGraph Hub: Rethinking How Teams Build APIs
WunderGraph Hub is our new collaborative platform for designing, evolving, and shipping APIs together. Itâs a design-first workspace that brings schema design, mocks, and workflows into one place.
The Backend-for-Frontend pattern using NextJS: A Step-by-Step Guide
The Backends-for-Frontends pattern might be exactly what you need to avoid monolithic Backend APIs and Frontends bloated with business logic. Letâs implement one in Next.js, using WunderGraph as a BFF framework.
Picture this: youâve just developed and deployed your dream app. (Congratulations!) To serve your desktop/web browser UI, youâve probably built some sort of backendâŚbut what happens when you grow, and perhaps start offering a mobile app to serve your growing userbase? That backend now has to be jury-rigged to become more of a general-purpose solution, serving more than one platform (or more accurately, user experience).
Now, things get a little less fun, for both devex and developer velocity in your org:
- Your mobile app has needs and requirements that are significantly different from your desktop app, to the point where your backend is now flooded with competing requirements.
- To ease some of the pressure on the backend team, you end up writing complex business logic in the frontend, tightly coupling your UI layer to it. The result? Messy codebases that are difficult to read and to maintain.
- Sure, separate UI/UX teams working on each frontend will speed up developmentâŚuntil both find that the backend team is the bottleneck, not being able to come up with feature adds/refactors/bugfixes that balance requirements of both platforms without breaking functionality for both user bases.
- You also end up with overfetching/underfetching issues on at least some of your supported platforms. The mobile UI/UX doesnât need the data that your desktop app does, but processing and sending out bespoke data for each client on the backend layer isnât an option â thatâs going to slow things down further.
At this point, youâre probably thinking something along these lines:
Ugh, this wouldnât be a problem if I could just have a separate âbackendâ for each of my frontends! Perhaps one such API per frontend, tailor made for it, and maintained by the team working on that frontend so they have full control over how they consume data internally.
Congratulations, youâve just described the Backends-for-Frontends (BFF) pattern!
Pioneered by SoundCloud , it makes developing for varied user experiences (a desktop/web browser, a mobile app, a voice-based assistant, a smartwatch, and so on.) much more manageable in terms of orchestrating and normalizing data flows, without your backend services becoming inundated with requests or your frontend code having to include complex business logic and in-code data JOINs.
For this tutorial, letâs build a simple Dashboard for an eCommerce that weâll implement using the BFF pattern. Weâll use Next.js as our frontend, two simple microservices for our data, and WunderGraph as our Backend-for-Frontend.


The Products pages, using the Products microservice for their data.
The Architecture
Before we start coding, hereâs a quick diagram of our architecture, so you know what youâll be building.
And hereâs what our tech stack will look like:
Express.js
To build our backend as microservices, each an independent API, with its own OpenAPI V3 specification. This is NOT a tutorial about microservices, so to keep things simple for this tutorial, weâll limit our backend to 2 microservices â Products, and Orders â and mock the downstream data calls they make, rather than interfacing with an actual database.
Next.js (with TypeScript)
For our frontend.
WunderGraph as our Backend-for-Frontend server.
You can think of this as an API gateway that serves as the only âbackendâ that your frontend can see, coordinating all calls between the two on a request, transforming data according to unique requirements, and optionally even incorporating auth and middleware, instead of having your frontend be concerned with any of that, or interacting directly with your backend APIs.
WunderGraph works by consolidating data from the datasources that you name in its config file (Databases or API integrations. For this tutorial, itâs microservices as OpenAPI REST) into a unified API layer that you can then use GraphQL queries or TypeScript Operations to get data out of, massage that data as needed for each separate user experience that you want to provide, and deliver it to the Next.js frontend via auto-generated, type-safe data fetching hooks.
TailwindCSS for styling.
Here are the instructions for setting it up for Next.js . Iâm using it because I love utility-first CSS; but you could use literally any styling solution you prefer. Tailwind classes translate quite well because itâs literally just a different way to write vanilla CSS.
Letâs dive right in!
The Code
1. The Backend â Microservices with Express.js
First of all, donât let âmicroservicesâ scare you. This is just an architectural style where a large application (our Express.js backend) is divided into small, independent, and loosely-coupled services (here, one Express.js app for the Product Catalog, and another for Orders). In real world projects, each microservice would be managed by a separate team, often with their own database.
./backend/products.ts
./backend/orders.ts
Each microservice is just an Express app with its own endpoints, each focusing on performing a single specific task â sending the product catalog, and the list of orders, respectively.
The next step would be to include these APIs as data dependencies for WunderGraph. The latter works by introspecting your data sources and consolidating them all into a single, unified virtual graph, that you can then define operations on, and serve the results via JSON-over-RPC. For this introspection to work on a REST API, youâll need an OpenAPI (you might also know this as Swagger) specification for it.
đĄ An OpenAPI/Swagger specification is a human-readable description of your RESTful API. This is just a JSON or YAML file describing the servers an API uses, its authentication methods, what each endpoint does, the format for the params/request body each needs, and the schema for the response each returns.
Fortunately, writing this isnât too difficult once you know what to do, and there are several libraries that can automate it . If youâd rather not generate your own, you can grab my OpenAPI V3 spec for our two microservices, in JSON here , and here . Theyâre far too verbose to be included within the article itself.
Finally, to keep things simple for this tutorial, weâre using mock eCommerce data from the Fake Store API for them rather than making database connections ourselves. If you need the same data Iâm using, here you go .
2. The BFF â WunderGraph
WunderGraphâs create-wundergraph-app
CLI is the best way to set up both our BFF server and the Next.js app in one go, so letâs do just that. Just make sure you have the latest Node.js LTS installed, first.
npx create-wundergraph-app my-project -E nextjs
Then, cd into the project directory, and
npm install && npm start
If you see a WunderGraph splash page pop up in your browser (at localhost:3000
) with data from an example query, youâre good to go!
In your terminal, youâll see the WunderGraph server (WunderNode) running in the background, watching for any new data sources added, or changes made, ready to introspect and consolidate them into a namespaced virtual graph layer that you can define data operations on. Letâs not keep it waiting.
Adding our Microservices as Data Dependencies
Our data dependencies are the two microservices we just built, as Express.js REST APIs. For this. So add them to wundergraph.config.ts
, pointing them at the OpenAPI spec JSONs, and including them in the configureWunderGraphApplication dependency array.
./.wundergraph/wundergraph.config.ts
Once you hit save, the WunderNode will introspect the Products and Orders microservices via their OpenAPI spec, and generate their models. If you want, check these generated types/interfaces at ./components/generated/models.ts. Youâll be able to see the exact shapes of all your data.
Now, you have all the data your services provide at your disposal within the WunderGraph BFF layer, and can write eitherâŚ
- GraphQL queries/mutations, or
- Async resolvers in TypeScript (WunderGraph calls these TypeScript Operations)
⌠to interact with that data.
Choose whichever one youâre familiar with, as ultimately, accessing that data from the frontend is going to be identical. This tutorial is simple enough that we can cover both!
Defining Data Operations on the Virtual Graph
With GraphQL
WunderGraphâs GraphQL Operations are just .graphql
files within ./.wundergraph/operations
.
./.wundergraph/operations/AllProducts.graphql
./.wundergraph/operations/AllOrders.graphql
With TypeScript Operations
TypeScript Operations are just .ts files within ./.wundergraph/operations
, use file-based routing similar to NextJS, and are namespaced. So hereâs what our operations will look like :
./.wundergraph/operations/products/getAll.ts
./.wundergraph/operations/orders/getAll.ts
These TypeScript Operations have one advantage over GraphQL â they are entirely in server-land â meaning you can natively async/await any Promise within them to fetch, modify, expand, and otherwise return completely custom data, from any data source you want.
Letâs go ahead and write operations to get Products and Orders by their respective IDs, too.
./.wundergraph/operations/products/getByID.ts
./.wundergraph/operations/orders/getByID.ts
Note how weâre using Zod as a built-in JSON schema validation tool.
Which one should you use? Well, that depends on your requirements. If your BFF needs to process and massage the data returned by your microservices/other datasources, TypeScript operations will be the way to go, being much more flexible in how you can join cross-API data, process error messages from your backend into something consistent and uniform for your frontend, and use Zod to validate inputs/API responses.
Once you have your data, itâs on to the frontend! When you hit save in your IDE after writing these operations (whichever method youâve chosen), the WunderNode will build the types required for the queries and mutations youâve defined, and generate a custom Next.js client with type-safe hooks you can use in your frontend to call those operations and return data.
3. The Frontend â Next.js + WunderGraphâs Data Fetching Hooks
Essentially, our frontend is just two pages â one to show all the orders, and another to show the Product Catalog. You can lay this out in any way you like; Iâm just using a really basic Sidebar/Active Tab pattern to switch between two display components â <ProductList>
and <OrderList>
â selectively rendering each.
./pages/index.tsx
WunderGraph generates typesafe React hooks for your frontend, every time you define an operation (whether using GraphQL or TypeScript) and hit save. Here, weâre using useQuery, specifying the name of the operation (see how our Operations being namespaced helps?). After that, itâs all home stretch. We just feed the data each hook returns into our components, to render out the data however we want.
With that out of the way, letâs look at those display components (and the basic card-style components they use for rendering individual items)
./components/ProductCard.tsx
./components/ProductList.tsx
./components/OrderCard.tsx
./components/OrderList.tsx
And hereâs the Sidebar component.
./components/Sidebar.tsx
Finally, here are the individual Product/Order pages, as Next.js dynamic routes.
./pages/products/[productID].tsx
./pages/orders/[orderID].tsx
Thatâs everything! Point your browser to http://localhost:3000 if you hadnât already, and you should see the data from our microservices rendered out into cards, based on which tab on the Sidebar youâre on.

The Orders pages, using the Orders microservice for their data.
In SummaryâŚ
The Backend-for-Frontend (BFF) pattern can be an incredibly useful solution when your backend becomes a complex, all-for-one monolithic API, and when you start including business logic in your different frontends to compensate, it matches your backend in complexity and lack of maintainability.
But when you get down to actual development, building BFFs can be difficult. Itâs possible, certainly, but thereâs a massive amount of boilerplate to write every single time, and orchestrating calls between the frontend and the backend services is a pain if rolling your own solution.
As an analogyâŚif you want to get into React, the go-to recommendation is to just pick up Next.js as a framework. But nothing like that existed for BFFsâŚuntil now.
With WunderGraph, building typesafe BFFs with either GraphQL or TypeScript becomes a cakewalk. You cut through all the boilerplate by explicitly defining your data sources â OpenAPI REST/GraphQL APIs, databases like PostgreSQL, MySQL, MongoDB, and even gRPC â and letting WunderGraphâs powerful code generation templates generate a typesafe client for you. All with top notch developer experience from start to finish.