Video thumbnail

    Authentication in React with Better Auth (+ own back-end with Bun)

    Valuable insights

    1.Self-Hosted Authentication with BetterAuth: BetterAuth enables comprehensive self-hosted authentication, providing features like social login, multi-factor authentication, RBAC, and payment gateway integrations directly within your application.

    2.React Frontend & Bun Backend Integration: This video demonstrates integrating the BetterAuth client-side library into a React frontend, paired with a custom backend built using Bun and Eliia for robust authentication.

    3.Rapid React Project Setup with Vite: Utilize Vite for fast and efficient scaffolding of React applications. This setup facilitates rapid development and straightforward configuration of essential tools like Tailwind CSS.

    4.Efficient Form Handling with React Hook Form: Leverage React Hook Form for streamlined form management and validation. It integrates seamlessly with schema validation libraries like Zod, simplifying user input handling.

    5.Session-Based Authentication and CORS Management: BetterAuth employs session-based authentication using cookies. The tutorial addresses common CORS issues and demonstrates how to configure both backend and frontend for smooth communication.

    6.Securely Fetching Authenticated User Data: Authenticated requests automatically include session cookies, enabling secure fetching of protected backend data. Configuring fetch requests with credentials ensures proper authorization.

    7.Enhanced Functionality with BetterAuth Hooks & Plugins: Explore BetterAuth's extensive hooks and plugins, which simplify complex authentication features. These tools streamline tasks such as session management, organization handling, and custom data integration.

    Welcome: What is BetterAuth?

    Welcome to this tutorial, where we'll dive into BetterAuth, a powerful tool for handling authentication within your applications. You've expressed significant interest in this library, and its capabilities are truly impressive. BetterAuth allows you to manage authentication entirely on your own infrastructure, moving away from relying on external providers. This video focuses on integrating the BetterAuth client-side library with a React frontend, complemented by a self-hosted backend solution built using the Bun runtime.

    Why use BetterAuth for authentication?

    The primary advantage of using BetterAuth lies in its ability to keep your authentication logic and data within your own application's boundaries. Unlike external authentication providers such as Clerk or Auth0, BetterAuth allows you to maintain full control. This approach is particularly valuable for developers seeking greater customization, data privacy, or a unified development experience without relying on third-party services.

    What features does BetterAuth offer?

    BetterAuth doesn't compromise on functionality despite offering a self-hosted solution. It provides essential authentication features that are crucial for modern applications. This allows you to implement sophisticated security measures and user management directly within your project, enhancing both user experience and control.

    • Social login capabilities
    • Passkeys support
    • One-Time Password (OTP) and two-factor authentication
    • Role-Based Access Control (RBAC) for managing roles, organizations, and teams
    • Invitation systems for onboarding users
    • Integration with payment gateways like Stripe and Polar to adjust user roles post-payment

    How to configure the backend with BetterAuth?

    We'll begin by setting up the backend infrastructure using Bun and the Eliia framework. BetterAuth can automatically generate necessary routes, simplifying the setup process. For demonstration, we'll use Docker Compose to bring up the database and then run the backend development server with Bun. This backend will serve as the API that our React frontend will communicate with for authentication purposes.

    How to start a React project with Vite?

    To kickstart the frontend development, we'll create a new React project using Vite. Vite offers a significantly faster development experience compared to traditional build tools. For this tutorial, we are opting for Vite to keep the setup simple and functional, ensuring that the concepts demonstrated can be easily adapted to various project environments or frameworks.

    What is the new React Compiler?

    Vite is also introducing a new compiler for React, which promises significant performance improvements. This compiler is designed to optimize the transformation of code, specifically from TypeScript to JavaScript, making the development process even more efficient. While not the primary focus of this video, it's an exciting development in the React ecosystem worth noting.

    How to run the React app locally?

    After initializing the React project with Vite, the next step is to run it locally. We can use Bun to install project dependencies. The development server starts quickly, providing a responsive environment. For a cleaner start, we'll perform some basic cleanup within the main `App.tsx` file, removing default boilerplate code to prepare for our authentication components.

    How to configure Tailwind CSS in React?

    To enhance the styling of our React application, we will integrate Tailwind CSS. This involves installing Tailwind CSS and its associated Vite plugin. We'll then configure the `tailwind.config.js` file and import the necessary CSS into our project's entry point. A basic dark theme setup using `BGZinc-950` and `text-white` will be applied to the main layout for better visibility.

    How to integrate BetterAuth in the frontend?

    Now, we proceed to integrate BetterAuth into our React frontend. This involves installing the BetterAuth client library. The integration process allows for flexibility, especially since we've set up a separate backend. This approach ensures that the frontend remains decoupled from the backend authentication logic, promoting better maintainability and scalability.

    How to initialize the BetterAuth Client?

    We create a `lib` folder and an `auth.ts` file to initialize the BetterAuth client. The core of this initialization is the `createAuth` function, specifically the React version. A crucial parameter here is the `baseURL`, which must point to your backend API's address (e.g., `http://localhost:333`). Additionally, we can pass various plugins, such as `anonymous` for guest access or `organization` for multi-tenancy features, to extend BetterAuth's capabilities.

    How to create the login component?

    We'll start building the user interface by creating a dedicated login component, `SignIn.tsx`. This component will house the form elements necessary for users to enter their credentials. We'll also be setting up the form structure and validation logic to ensure a smooth and secure login process for users interacting with our application.

    Validate forms with React Hook Form?

    For robust form management in our React application, we will integrate React Hook Form. This library simplifies handling form state, validation, and submission. It's highly efficient and works well with schema declaration libraries like Zod, which we'll use to define the expected structure and types for our login form data.

    How to structure the login form?

    The login form will consist of input fields for email and password, along with a submit button. We'll configure React Hook Form to manage these inputs using the `register` function. For validation, we define a `signInSchema` with Zod, specifying that the email must be a valid email format and the password must have a minimum length of three characters. Error messages will guide users on correcting invalid inputs.

    • `register`: Binds input fields to the form state.
    • `handleSubmit`: Handles form submission and passes validated data.
    • `formState`: Provides submission status like `isSubmitting` for disabling the button.

    Style form with Tailwind CSS?

    To improve the visual appeal of the login form, we apply Tailwind CSS classes. This includes adding padding and margin to the form container, styling the input fields with background colors, rounded corners, and padding, and styling the submit button with a distinct background color, rounded corners, and a semi-bold font weight. These styles make the form more user-friendly and aesthetically pleasing.

    How to test the form submission?

    Before integrating with BetterAuth, it's essential to test the form submission logic. We'll temporarily log the form data to the console upon submission. This allows us to verify that React Hook Form is correctly capturing the email and password entered by the user and that the validation rules are working as expected, ensuring data integrity.

    How to perform login with BetterAuth?

    With the form structured and validated, we can now integrate BetterAuth's login functionality. We import the initialized `auth` object from our `lib/auth.ts` file. The `auth.signIn` method is used, accepting either email or social login options. We provide the user's email and password, along with a `callbackURL` to redirect them after successful authentication. Error handling is implemented using the `onError` callback to display user-friendly messages.

    Resolve CORS errors on the backend?

    During the initial login test, a CORS (Cross-Origin Resource Sharing) error occurred, indicating a communication issue between the frontend and backend. This is a common problem when dealing with separate domains or ports. To resolve this, we need to configure the CORS middleware on the backend. We'll install the `eligia-cors` package to handle these settings properly.

    How to configure BetterAuth for CORS?

    Proper CORS configuration is vital for seamless communication. In the Eliia backend, we enable CORS using the `useCors` middleware. Critically, we must specify the allowed origins, including our frontend's URL (`http://localhost:5173`). Additionally, enabling `credentials` and allowing the `Authorization` header are necessary for BetterAuth's session cookies to be sent and accepted correctly by the backend.

    How to create the signup component?

    Next, we create the user signup component, `SignUp.tsx`. This component is similar to the login form but includes an additional field for the user's name. We'll adapt the Zod schema to include this new field and use BetterAuth's `auth.signUp` method to register new users. This involves passing the email, password, and name to the backend for account creation.

    How to display login and signup?

    To provide users with options, we'll render both the login and signup forms within our main `App.tsx` component. We'll use headings like 'Login' and 'Cadastro' (Signup) to clearly differentiate between the two forms. This setup allows users to choose whether they want to sign in or create a new account upon visiting the application's authentication pages.

    How to test user signup?

    Testing the signup functionality is crucial. We input user details, including name, email, and password. The system should provide immediate feedback on validation errors, such as a password being too short or a user already existing in the database. We simulate these scenarios to ensure the error handling and validation messages are accurate and informative.

    How to confirm signup and login?

    After successful signup and validation, we can proceed to log in with the newly created credentials. The system confirms the login and redirects the user to the specified `callbackURL`, demonstrating the complete authentication flow. This successful redirection signifies that both the signup and login processes are functioning correctly.

    How does session authentication work?

    BetterAuth utilizes a session-based authentication mechanism, which relies on secure cookies stored in the user's browser. Once a user logs in, BetterAuth automatically sets a session cookie. This cookie is then included in subsequent requests to the backend, allowing the server to identify and authenticate the user without requiring explicit token management on the client-side. This stateful approach has its own set of advantages and considerations compared to stateless JWT authentication.

    How to fetch authenticated user data?

    With authentication established, we can now fetch protected data from the backend. We'll demonstrate this using TanStack Query (formerly React Query) for efficient data fetching. A new component, `Profile.tsx`, will be created to make a request to a backend endpoint, such as `/users/1`. This request will automatically include the session cookie, authorizing access to the user's data.

    How to send credentials in requests?

    When making requests to protected backend resources, it's crucial to ensure that credentials, specifically the session cookies managed by BetterAuth, are sent along with the request. For the `fetch` API, this is achieved by setting the `credentials` option to `'include'`. This instructs the browser to automatically attach relevant cookies, facilitating seamless authenticated communication with the server.

    Client vs server-side authentication?

    Understanding the difference between client-side and server-side authentication is key. In a client-side setup like this Vite-based React app, cookies are managed automatically. For server-side rendered applications, such as those built with Next.js, you would typically need to manually import and attach headers, often derived from request cookies, to ensure authenticated requests are correctly processed by the server.

    BetterAuth Hooks and plugins?

    BetterAuth provides a rich ecosystem of hooks and plugins that significantly simplify complex authentication workflows. For instance, hooks like `useSession` grant easy access to the currently logged-in user's data, while plugins enable features such as organization management. You can even extend the data models for sessions or organizations using utilities like `inferAdditionalFields`, showcasing the library's flexibility and extensibility. The library is continuously updated with new hooks and features.

    Next steps with BetterAuth?

    BetterAuth is a rapidly evolving project with a strong development trajectory. While its current volatility means features can change, its potential is undeniable. We encourage you to experiment with BetterAuth in your own projects and share your feedback. Your insights are invaluable for the project's growth and for guiding future content development on related tools and techniques.

    Useful links

    These links were generated based on the content of the video to help you deepen your knowledge about the topics discussed.

    This article was AI generated. It may contain errors and should be verified with the original source.
    VideoToWordsClarifyTube

    © 2025 ClarifyTube. All rights reserved.