The Easiest Way to Bake Auth Into Your Backend-for-Frontend with Clerk and WunderGraph
We're hiring!
We're looking for Golang (Go) Developers, DevOps Engineers and Solution Architects who want to help us shape the future of Microservices, distributed systems, and APIs.
By working at WunderGraph, you'll have the opportunity to build the next generation of API and Microservices infrastructure. Our customer base ranges from small startups to well-known enterprises, allowing you to not just have an impact at scale, but also to build a network of industry professionals.
The Easiest Way to Bake Auth Into Your Backend-for-Frontend with Clerk and WunderGraph
A true match made in heaven, learn how to implement authentication in your BFF architecture in minutes!

In the web development field, auth (authentication + authorization) plays a vital role in securing user access and protecting sensitive data. Authentication involves verifying the userâs identity, and Authorization is about granting them appropriate access to the applicationâs resources.
That said, itâs not easy. Implementing auth solely in the frontend is easy, but is usually a terrible idea. Even when done in the backend, it can have its drawbacks.
This article explores these limitations and presents a compelling third alternative: the Backends-for-Frontends (BFF) pattern.
By adopting this approach, developers can enhance security, improve performance, and achieve greater flexibility in their authentication implementation. Essentially, itâs the perfect pattern for this problem.
Additionally, weâll examine how WunderGraph simplifies the process of implementing auth with a BFF.
So letâs get going!
We're hiring!
We're looking for Golang (Go) Developers, DevOps Engineers and Solution Architects who want to help us shape the future of Microservices, distributed systems, and APIs.
By working at WunderGraph, you'll have the opportunity to build the next generation of API and Microservices infrastructure. Our customer base ranges from small startups to well-known enterprises, allowing you to not just have an impact at scale, but also to build a network of industry professionals.
Why Frontend Auth Falls Short
Letâs first clear the air and analyze why doing front-end auth is such a bad idea (because, letâs face it, it might seem easy, but itâs a terrible way to implement it).
Too Exposed
Frontend auth involves embedding auth logic in the client-side code, making it vulnerable to inspection by malicious actors.
With access to the JS bundle, anyone can analyze and exploit potential weaknesses, jeopardizing the security of the system.
Yes, you can obfuscate the code, minimize it and make it literally unreadable by humans. But anyone with enough free time and a Developerâs Console (which is on every major browser) can break your logic and âhackâ your auth.
Messy Frontend Code
Handling auth logic in the frontend increases the burden on frontend teams, leading to slower development cycles.
Moreover, frontend code becomes tightly coupled with the auth implementation, hindering scalability and adaptability.
In other words, youâre adding code where you shouldnât, and that only plays against you and your team.
Multiple Clients Complexity
What if your back-end can be used by different clients (e.g., desktop, mobile app, gaming consoles)?
In that case, every different client will have to re-implement the entire auth logic. Does that sound reasonable to you?
Even worse, what if youâre developing a platform that can be used by anyone? Then youâll have countless client applications having to re-invent the authentication wheel.
Madness! MADNESS I SAY!
The âPrevent Trackingâ Option
Enabling privacy features that aim to prevent user tracking might unintentionally interfere with auth, causing third-party cookies or auth tokens to be dropped, and eventually disrupting the authentication process.
In a typical frontend auth setup, the authentication process involves the frontend obtaining an auth token or cookie from the backend upon successful login.
This token is then used to authenticate subsequent requests. But when the âprevent trackingâ option is activated, the frontend may be prevented from storing or sending these tokens or cookies. As a result, the authentication flow is disrupted, and users may find themselves unable to access protected resources or perform authenticated actions.
The implications of the âprevent trackingâ option on on the authentication flow underline the need for alternative approaches. By moving the auth logic to the backend or adopting other patterns (more on this in a second), developers can mitigate these challenges.
So, letâs ditch the frontend and focus on the backend!
I mean, it only makes sense right? If implementing the auth flow on the front-end alone makes no sense (and weâve seen many reasons why that is), then logic dictates we should move it to the back-end. Right?
Not exactly.
While moving the authentication flow to the backend is a step in the right direction, there is a hidden third option that literally lies in the middle of both alternatives: the Backend-for-frontend, also known as BFF (sounds funny, I know).
Letâs review what the BFF pattern is, and why implementing the auth layer in the Backend for Frontend (BFF) makes even more sense!
The Power of Backends-for-Frontends (BFF) and WunderGraph
The Backends-for-Frontends (BFF) pattern acts as a dedicated mini-backend layer owned by the frontend team, created to cater specifically to the needs of that particular frontend or client. It serves as the only âbackendâ that frontend app can see, hiding the actual backend from it. This BFF serves as the intermediary between the frontend and the real backend.
Think about it this way. Have you ever been part of a project where :
- The backend wants to develop the services one way and the frontend complains thatâs not useful for them? And then each develops and deploys their part independently, having to spend weeks re-adjusting and re-factoring later to sync up and match expectations?
- One where you have multiple, diverse clients that need to consume the same service (most commonly, when you start offering a mobile app in addition to a web app), leading to complex, chatty (either via overfetching or underfetching) frontend code that results in increased network overhead and slower response times, and becomes harder to maintain and scale?
- Or simply one where changes in one component had unintended effects on the other, because the frontend and backend were tightly coupled?
Who hasnât right? Well, with the BFF pattern, frontend developers can have more control over the data they need and their interactions with the backend, and each can develop, evolve, and deploy their services independently, without being tightly coupled and stepping on each othersâ toes.
Check out the following diagram to make more sense of it:

The above setup shows a classic client-server setup, while the bottom version shows the BFF pattern being implemented by WunderGraph.
Sounds like overengineering, but hereâs why BFF is superior to both the frontend and the backend for implementing auth:
- Middleware: Within the BFF, developers can implement various security measures like IP whitelisting/blacklisting, rate limiting, request validation and more. They can use any middleware they want for it and these robust options safeguard backend services from problems like DDoS attacks, ensuring that incoming requests undergo the necessary security checks before reaching your backend.
- Potential Performance Gains: The BFF pattern allows developers to add a cache for auth tokens, manage session states efficiently, and aggregate data from multiple downstream backend services. Think about it, you can do anything you want in this layer to save time and avoid unnecessary requests to the actual backend of the application. That of course, translates into a more efficient service and potentially a better user experience.
- Scalability: Auth logic can be iterated upon and scaled independently of the backend, since youâre literally not touching it. This agility helps accelerates development cycles, and ensures resilience as traffic increases through horizontal scaling (adding more servers to the auth-backend).
- Separation of Concerns for the team: With the frontend team also owning the BFF, they can iterate on the user interface and authentication flows independently. Through techniques such as request-mocking, they can move forward with the entire development process while the backend team focuses on developing the core business logic. Granted, eventually both teams will have to âtalk to each otherâ, but this process allows for a safer and more flexible way to work independently from each other.
- Security by obfuscation: Remember what I said earlier about how a developer with a Dev Console could be a potential problem to a full-frontend implementation? Well, this is one way to solve those problems. With the BFF pattern, developers canât really see the actual log-in logic, they can only see how the frontend reacts to certain responses and thatâs IT. In the end, more than âsecurity by obfuscationâ, this is more like âsecurity by hiding the logic away from the developerâ, but that was too long to use as a bullet point.
Alright, by now you should be thinking something like âRight, OK, Iâm sold, how do I implement my first BFF?â right?
Well, thatâs not a trivial task, which is why weâll use other tools to assist us and help with the process. Thatâs where WunderGraph comes into play.
What is WunderGraph?
WunderGraph, the Backend for Frontend (BFF) Framework, streamlines API composition with its intuitive approach.
By combining APIs seamlessly and treating them as dependencies, WunderGraph enables developers to build applications that rely on data from multiple sources. With native support for GraphQL Subscriptions and a virtual graph layer for cross-source joins, WunderGraph empowers real-time functionality and simplified data integration.
With its open-source nature, WunderGraph aims to make utilizing APIs quick and effortless.
You can check out WunderGraph's GitHub here .
Letâs Explore Clerk Authentication with WunderGraph in our BFF
I always like to say: show me a practical example!
So enough with the crazy theory and the list of benefits and letâs get this show on the road. Letâs build something using Wundergraph and the BFF pattern.
Actually, weâll use that AND NextJS as the framework and weâll also throw in a little bit of Clerk to handle the auth process.
STEP 1: Set up WunderGraph + NextJS
To get started, letâs set up WunderGraph with NextJS. Open your terminal and run the following commands:
If you see something like this after the first line, it means everything was installed correctly:

Verify that everything is working by navigating to localhost:3000
in your browser. If you see this (it takes a while, so give it time), then youâre good:

STEP 2: Sign up for a Clerk<span>.</span>com Account
To proceed with Clerk, youâll need to sign up for a Clerk.com account. This will provide the necessary authentication infrastructure for our implementation.
Once youâve signed up, click on âAdd Applicationâ and start configuring your authentication strategy. As you can see below, you get a nice preview of your log-in screen (right half of the screen) while at the same time, you can configure which auth methods youâll allow (left half of the screen):

For this example, weâll just go with e-mail and Google. Now hit âCreate Applicationâ and let the SaaS do the rest!
Youâll be redirected to a page showing you your new keys and how to configure them on multiple frameworks. The first one is going to be Next and since thatâs what weâre using (coincidence?!), just donât touch anything.
Just click on the âcopyâ button on the top right corner of the keys section (see image below):

And save that on your .env
file (if you donât have one at the root of your project, create one and save the data there).
Youâll also have to install the @clerk/nextjs
package:
STEP 3: Implementing Clerk Auth in WunderGraph
Now, letâs dive into the code and integrate Clerk authentication into our WunderGraph BFF.
For the example, weâll use the default page that was already created by the generator. Weâll add our auth code, and suddenly weâll have to sign in to actually see it.
First, go to Clerk.com and on the left side menu, select the âJWT Templatesâ section:

Add a new one, and fill in a name, letâs call it âwundergraphâ (original, I know), and on the âclaimsâ box, add something like this:
The important bit is youâll also copy the âJWKS Endpointâ:

Then go to .wundergraph/wundergraph.config.ts
and edit the authentication
section to look like this:
Now go to the pages/_app.tsx
file and change it to look like this:
There are several things to note here:
- We created the
useWunderGraphClerk
middleware. - We applied the middleware to the exported component.
- Inside the middleware, weâre referencing the name of the JWT template we created on Clerk (I called it âwundergraphâ you might need to change this value if you used another name).
- I added the
<ClerkProvider>
component around everything. If you donât do this, youâll see an error saying something likeAuth context not found
. - I also added the
SignedIn
andSignedOut
components, which take care of adding logic inside the JSX code to understand what to do if the user is signed in or not.
At this point, when visiting http://localhost:3000
you should see a login screen like this:

And after logging in, youâll be redirected automatically to your homepage.
STEP 4: But wait, there is more!
Yes, youâre done, you can stop reading now, but I wanted to take this a little bit further and show you how cool Clerk is.
Inside your logged-in pages, you can add a user menu icon that by default already shows your avatar. And all of that with a single component.
Simply add the <UserButton />
component inside the pages/index.tsx
file wherever you want and be amazed by the simplicity and power of this component.
Here is mine:

There you have the âSign-outâ link, which is also a common question users ask after setting everything up!
By integrating Clerk authentication into our WunderGraph BFF, we were able to leverage the powerful features and security provided by Clerk.com while benefiting from the simplicity and flexibility of WunderGraph.
This is truly a match made in heaven!
If youâd like to check out the full source code of this example, you have it here , simply clone the repo and go nuts!
That said, I hope you found this step-by-step tutorial interesting! I personally loved the simplicity of integration and how both options simplify different aspects of the development process.
In the end, weâre looking at a flexible and powerful frontend capable of being easily integrated into different backends without affecting the UI. Not only that, but we also saw a very simple way of integrating authentication into an existing application with minimum effort!
Have you used the BFF pattern before? What about Wundergraph or Clerk? Share your experience in the comments, Iâd love to know what you think about this topic!