The Easiest Way to Bake Auth Into Your Backend-for-Frontend with Clerk and WunderGraph - WunderGraph
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.
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.
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).
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.
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.
- 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.
- Scalability: Auth logic can be iterated upon and scaled independently of the backend. This agility helps accelerate development cycles, and ensures resilience as traffic increases.
- 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.
- Security by obfuscation: 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.
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.
Let’s Explore Clerk Authentication with WunderGraph in our BFF
STEP 1: Set up WunderGraph + NextJS
Open your terminal and run the following commands:
1 2
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.
STEP 2: Sign up for a Clerk.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.
STEP 3: Implementing Clerk Auth in WunderGraph
Now, let’s dive into the code and integrate Clerk authentication into our WunderGraph BFF. First, go to Clerk.com and on the left side menu, select the “JWT Templates” section:
STEP 4: But wait, there is more!
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.