Better Auth
Better Auth is a comprehensive authentication framework designed for TypeScript applications, supporting various authentication methods like OAuth, OIDC, 2FA, and social logins. The current stable version is 1.6.5, with frequent patch and minor releases, alongside active beta development indicating continuous feature enhancements and bug fixes.
Common errors
-
Column 'verified' does not exist on table 'twoFactor'
cause The required `verified` column for the `twoFactor` table, introduced in v1.6.2, is missing from your database schema.fixRun `npx auth@latest generate` to update your ORM client, then apply the schema migration using your ORM's command (e.g., `npx prisma migrate dev` or `npx drizzle-kit push`). -
AuthError: AUTH_SECRET is not defined
cause The `AUTH_SECRET` environment variable is not set, which is critical for encrypting and signing session tokens, making the application insecure.fixDefine the `AUTH_SECRET` environment variable in your application's environment (e.g., `.env` file) with a long, randomly generated string. Do not hardcode secrets in your codebase. -
TypeError: auth.getSession is not a function
cause This error can occur if the `auth` instance is not correctly initialized or if `getSession` is called without the expected request context (e.g., `req`).fixEnsure `auth` is properly instantiated and exported. When calling `getSession` server-side, pass the relevant request object, e.g., `await auth.getSession({ req })`. -
AuthError: Invalid OTP method specified.
cause The `enableTwoFactor` function was called without a valid `method` parameter or with an unsupported method, following the breaking change in `v1.7.0-beta.0`.fixUpdate your `enableTwoFactor` calls to explicitly specify the `method` as either `'otp'` or `'totp'`, e.g., `auth.enableTwoFactor({ method: 'totp' })`.
Warnings
- breaking The `enableTwoFactor` function now requires a `method` parameter (`'otp' | 'totp'`) and returns a discriminated response object with a `method` field. If `method: 'otp'` is used, `otpOptions.sendOTP` must be configured on the server.
- breaking The `twoFactor` database table now requires a `verified` column. Failing to add this column will prevent TOTP enrollment from working correctly and may lead to schema migration errors.
- breaking The `session.freshAge` calculation now aligns with the session's `createdAt` timestamp instead of `updatedAt`. This change impacts how fresh sessions are determined, potentially affecting session validity logic.
- gotcha 2FA enforcement scope was temporarily reverted in `v1.6.4` to apply only to credential sign-in paths. This meant magic link, email OTP, OAuth, SSO, and passkey flows would bypass 2FA challenges in that version.
Install
-
npm install better-auth -
yarn add better-auth -
pnpm add better-auth
Imports
- Auth
const Auth = require('better-auth');import { Auth } from 'better-auth';
Quickstart
import { Auth } from 'better-auth';
import { PrismaAdapter } from '@better-auth/adapter-prisma';
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
export const auth = new Auth({
adapter: PrismaAdapter(prisma),
secret: process.env.AUTH_SECRET ?? 'super-secret-dev-key', // IMPORTANT: Use a strong, unique secret in production
providers: [], // Configure your authentication providers here
});
// Example usage (e.g., in a Next.js API route):
// import { auth } from './auth'; // Adjust path as needed
// import type { NextApiRequest, NextApiResponse } from 'next';
//
// export default async function handler(req: NextApiRequest, res: NextApiResponse) {
// const session = await auth.getSession({ req });
// if (!session) {
// return res.status(401).json({ message: 'Unauthorized' });
// }
// res.status(200).json({ user: session.user });
// }