Backend
Better Auth
Better Auth best practices for authentication, session security, and authorization boundaries.
Better Auth
What it is
Better Auth is an authentication framework for modern TypeScript applications, focused on practical auth flows and session handling.
Best practices
Why we use it
- Provides structured authentication primitives with less custom boilerplate.
- Supports scalable session and provider-based auth strategies.
- Keeps auth workflow explicit and auditable.
Setup in this repo
- Integrate Better Auth in backend app entrypoint.
- Connect to selected database/session adapter.
- Keep secrets and provider configs environment-driven and validated.
Team conventions
- Keep auth configuration centralized and environment-driven.
- Separate authentication concerns from business domain routes.
- Enforce explicit authorization checks per protected route.
- Use least-privilege defaults for roles and scopes.
Error handling and reliability
- Return safe auth error messages without leaking sensitive internals.
- Handle token/session expiry paths explicitly.
- Ensure logout/session invalidation behavior is deterministic.
Testing and validation
- Test login/logout/session refresh flows end-to-end.
- Validate role/permission checks for protected endpoints.
- Add regression tests for auth middleware and adapters.
Abstractions and anti-patterns
- Avoid coupling domain service logic directly to auth provider APIs.
- Avoid spreading auth checks ad hoc across handlers; centralize policies.
- Avoid hard-coded auth secrets or provider values in source.
Example
export const authConfig = {
baseURL: process.env.AUTH_BASE_URL,
secret: process.env.AUTH_SECRET,
};Common pitfalls
- Mixing authentication and authorization logic in the same middleware without clear boundaries.
- Missing required environment variables across environments.
- Missing revocation/expiry handling in session-protected routes.