What is a BFF? And how to build one?
Who wants to build a monolith nowadays? Microservices are the way to go! But that’s no cheap alternative. It introduces all sorts of complexity. For example: Assume having several user-interface agnostic microservices, how “chatty” will your SPA or mobile app become?
General-purpose APIs might require consumers of APIs to aggregate and filter the responses of various endpoints to render something useful to the end-user.
And how will an architecture of multiple micro-frontends connected to a series of microservices impact maintenance? The promise of microservices is that they will make your application more agile. Create a new microservice as you please and tear one down when need be. But how will this impact the front end?
So, to solve that problem, yet another pattern occurred: The Backend For Frontend. The concept is what you might expect: One backend for every frontend that will act as an interface between a frontend app (SPA/Mobile) and the domain services. It’s an API that queries downstream services and transforms the response(s) to one single response formatted specifically for one specific front end. Schematically, BFFs in a microservice landscape might look somewhat like this:
The BFF concept was first introduced at SoundCloud.
BFF, authentication, and the cookie-less era
You might wonder how that’s relevant to this article. But especially the cookie-less era makes the BFF pattern a little more complex than you would first guess from the picture above.
In many cases, downstream services require authentication. Usually, (access) token-based. The BFF needs to include these tokens in the requests that are forwarded downstream.
It’s a common practice to store access_tokens in the SPA. It includes it in the requests and, a presto, the API knows who’s executing the request. But there is going to be a problem with this approach in general. When a token expires (typically after one hour), SPAs usually, silently renew them. This mechanism is based on third-party cookies and those are not working anymore soon. As a result, silent renews will not work anymore in 2024.