Node Integration
Better Auth can be integrated with node based backed frameworks. The guide below will show you how to integrate Better Auth with express.
Before you start, make sure you have a Better Auth instance configured. If you haven't done that yet, check out the installation.
Note that CommonJS (cjs) isn't supported. Use ECMAScript Modules (ESM) by setting "type": "module"
in your package.json
or configuring your tsconfig.json
to use ES modules.
Mount the handler
To enable Better Auth to handle requests, we need to mount the handler to an API route. Create a catch-all route to manage all requests to /api/auth/*
(or any other path specified in your Better Auth options).
Don’t use express.json()
before the Better Auth handler. Use it only for other routes, or the client API will get stuck on "pending".
After completing the setup, start your server. Better Auth will be ready to use. You can send a GET
request to the /ok
endpoint (/api/auth/ok
) to verify that the server is running.
Cors Configuration
To add CORS (Cross-Origin Resource Sharing) support to your Express server when integrating Better Auth, you can use the cors
middleware. Below is an updated example showing how to configure CORS for your server:
Getting the User Session
To retrieve the user's session, you can use the getSession
method provided by the auth
object. This method requires the request headers to be passed in a specific format. To simplify this process, Better Auth provides a fromNodeHeaders
helper function that converts Node.js request headers to the format expected by Better Auth (a Headers
object).
Here's an example of how to use getSession
in an Express route: