change the database adapter on a request basis

Can we change the database adapter dynamically ? I have in a header named "xxx-tenant" that has as a value the name of the tenant the request is coming from. I use a "one database per tenant" setup, so every database is exactly the same in their structure, and all the better-auth instance i have a configured in the same exact way. I'm wondering if, instead of having multiple better-auth instance (which is really hacky), i could have one better-auth instance, and on the request basis change the database address or something like that, so that the db call better-auth does is being sent to the right db. @Better Auth
1 Reply
Better Auth
Better Auth2mo ago
Currently, Better Auth does not provide an out-of-the-box method to change the database adapter dynamically on a per-request basis. The database adapter is configured once when you initialize your Better Auth instance (see [6]), meaning the connection settings cannot be swapped out at runtime based on request headers. That said, if you need a “one database per tenant” setup where each request is directed to a different tenant-specific database, one viable approach is to develop a custom database adapter. Using our custom adapter creation tools (see [3]), you could implement logic that inspects the request context (for example, reading the "xxx-tenant" header) and routes the data operations to the corresponding database connection. This would require a good bit of custom logic and careful testing to ensure that all database operations use the correct connection. Have you had a chance to try creating a custom adapter for this use case, or would you like more details on how to approach building one? Sources: [3] Create a Database Adapter | Better Auth [6] Database | Better Auth — Better Auth is powered by https://clarm.com
Create a Database Adapter | Better Auth
Learn how to create a custom database adapter for Better-Auth
Database | Better Auth
Learn how to use a database with Better Auth.

Did you find this page helpful?