| name | better-auth-security-best-practices |
| description | This skill provides guidance for implementing security features that span across Better Auth, including rate limiting, CSRF protection, session security, trusted origins, secret management, OAuth security, IP tracking, and security auditing. These topics are not covered in individual plugin skills. |
Secret Management
The auth secret is the foundation of Better Auth's security. It's used for signing session tokens, encrypting sensitive data, and generating secure cookies.
Configuring the Secret
import { betterAuth } from 'better-auth';
export const auth = betterAuth({
secret: process.env.BETTER_AUTH_SECRET,
});
Better Auth looks for secrets in this order:
options.secret in your config
BETTER_AUTH_SECRET environment variable
AUTH_SECRET environment variable
Secret Requirements
Better Auth validates your secret and will:
- Reject default/placeholder secrets in production
- Warn if the secret is shorter than 32 characters
- Warn if entropy is below 120 bits
Generate a secure secret:
openssl rand -base64 32
Important: Never commit secrets to version control. Use environment variables or a secrets manager.
Rate Limiting
Rate limiting protects your authentication endpoints from brute-force attacks and abuse.
By default, rate limiting is enabled in production but disabled in development. To explicitly enable it, set rateLimit.enabled to true in your auth config.
Better Auth applies rate limiting to all endpoints by default.
Each plugin can optionally have it's own configuration to adjust rate-limit rules for a given endpoint.
Default Configuration
import { betterAuth } from 'better-auth';
export const auth = betterAuth({
rateLimit: {
enabled: true,
window: 10,
max: 100,
},
});
Storage Options
Configure where rate limit counters are stored:
rateLimit: {
storage: "database",
}
memory: Fast, but resets on server restart (default when no secondary storage)
database: Persistent, but adds database load
secondary-storage: Uses configured secondary storage like Redis (default when available)
Note: It is not recommended to use memory especially on serverless platforms.
Custom Storage
Implement your own rate limit storage:
rateLimit: {
customStorage: {
get: async (key) => {
},
set: async (key, data) => {
},
},
}
Per-Endpoint Rules
Better Auth applies stricter limits to sensitive endpoints by default:
/sign-in, /sign-up, /change-password, /change-email: 3 requests per 10 seconds
Override or customize rules for specific paths:
rateLimit: {
customRules: {
"/api/auth/sign-in/email": {
window: 60,
max: 5,
},
"/api/auth/some-safe-endpoint": false,
},
}
CSRF Protection
Better Auth implements multiple layers of CSRF protection to prevent cross-site request forgery attacks.
How CSRF Protection Works
- Origin Header Validation: When cookies are present, the
Origin or Referer header must match a trusted origin
- Fetch Metadata: Uses
Sec-Fetch-Site, Sec-Fetch-Mode, and Sec-Fetch-Dest headers to detect cross-site requests
- First-Login Protection: Even without cookies, validates origin when Fetch Metadata indicates a cross-site navigation
Configuration
import { betterAuth } from 'better-auth';
export const auth = betterAuth({
advanced: {
disableCSRFCheck: false,
},
});
Warning: Only disable CSRF protection for testing or if you have an alternative CSRF mechanism in place.
Fetch Metadata Blocking
Better Auth automatically blocks requests where:
Sec-Fetch-Site: cross-site AND
Sec-Fetch-Mode: navigate AND
Sec-Fetch-Dest: document
This prevents form-based CSRF attacks even on first login when no session cookie exists.
Trusted Origins
Trusted origins control which domains can make authenticated requests to your Better Auth instance. This protects against open redirect attacks and cross-origin abuse.
Configuring Trusted Origins
import { betterAuth } from 'better-auth';
export const auth = betterAuth({
baseURL: 'https://api.example.com',
trustedOrigins: ['https://app.example.com', 'https://admin.example.com'],
});
Note: The baseURL origin is automatically trusted.
Environment Variable
Set trusted origins via environment variable (comma-separated):
BETTER_AUTH_TRUSTED_ORIGINS=https://app.example.com,https://admin.example.com
Wildcard Patterns
Support for subdomain wildcards:
trustedOrigins: [
'*.example.com',
'https://*.example.com',
'exp://192.168.*.*:*/*',
];
Dynamic Trusted Origins
Compute trusted origins based on the request:
trustedOrigins: async (request) => {
const tenant = getTenantFromRequest(request);
return [`https://${tenant}.myapp.com`];
};
What Gets Validated
Better Auth validates these URL parameters against trusted origins:
callbackURL - Where to redirect after authentication
redirectTo - General redirect parameter
errorCallbackURL - Where to redirect on errors
newUserCallbackURL - Where to redirect new users
origin - Request origin header
- and more...
Invalid URLs receive a 403 Forbidden response.
Session Security
Sessions control how long users stay authenticated and how session data is secured.
Session Expiration
import { betterAuth } from 'better-auth';
export const auth = betterAuth({
session: {
expiresIn: 60 * 60 * 24 * 7,
updateAge: 60 * 60 * 24,
},
});
Fresh Sessions for Sensitive Actions
The freshAge setting defines how recently a user must have authenticated to perform sensitive operations:
session: {
freshAge: 60 * 60 * 24,
}
Use this to require re-authentication for actions like changing passwords or viewing sensitive data.
Session Caching Strategies
Cache session data in cookies to reduce database queries:
session: {
cookieCache: {
enabled: true,
maxAge: 60 * 5,
strategy: "compact",
},
}
compact: Base64url + HMAC-SHA256 (smallest, signed)
jwt: HS256 JWT (standard, signed)
jwe: A256CBC-HS512 encrypted (largest, encrypted)
Note: Use jwe strategy when session data contains sensitive information that shouldn't be readable client-side.
Cookie Security
Better Auth uses secure cookie defaults but allows customization for specific deployment scenarios.
Default Cookie Settings
secure: true when baseURL uses HTTPS or in production
sameSite: "lax" (prevents CSRF while allowing normal navigation)
httpOnly: true (prevents JavaScript access)
path: "/" (available site-wide)
- Prefix:
__Secure- when secure is enabled
Custom Cookie Configuration
import { betterAuth } from 'better-auth';
export const auth = betterAuth({
advanced: {
useSecureCookies: true,
cookiePrefix: 'myapp',
defaultCookieAttributes: {
sameSite: 'strict',
path: '/auth',
},
},
});
Per-Cookie Configuration
Customize specific cookies:
advanced: {
cookies: {
session_token: {
name: "auth-session",
attributes: {
sameSite: "strict",
},
},
},
}
Cross-Subdomain Cookies
Share authentication across subdomains:
advanced: {
crossSubDomainCookies: {
enabled: true,
domain: ".example.com",
additionalCookies: ["session_token", "session_data"],
},
}
Security Note: Cross-subdomain cookies expand the attack surface. Only enable if you need authentication sharing and trust all subdomains.
OAuth / Social Provider Security
When using social login providers, Better Auth implements industry-standard security measures.
PKCE (Proof Key for Code Exchange)
Better Auth automatically uses PKCE for all OAuth flows:
- Generates a 128-character random
code_verifier
- Creates a
code_challenge using S256 (SHA-256)
- Sends
code_challenge_method: "S256" in the authorization URL
- Validates the code exchange with the original verifier
This prevents authorization code interception attacks.
State Parameter Security
The state parameter prevents CSRF attacks on OAuth callbacks:
import { betterAuth } from 'better-auth';
export const auth = betterAuth({
account: {
storeStateStrategy: 'cookie',
},
});
State tokens:
- Are 32-character random strings
- Expire after 10 minutes
- Contain callback URLs and PKCE verifier (encrypted)
Encrypting OAuth Tokens
Encrypt stored access and refresh tokens in the database:
account: {
encryptOAuthTokens: true,
}
Recommendation: Enable this if you store OAuth tokens for API access on behalf of users.
Skipping State Cookie Check
For mobile apps or specific OAuth flows where cookies aren't available:
account: {
skipStateCookieCheck: true,
}
Warning: Only use this for mobile apps that cannot maintain cookies across redirects.
IP-Based Security
Better Auth tracks IP addresses for rate limiting and session security.
IP Address Configuration
import { betterAuth } from 'better-auth';
export const auth = betterAuth({
advanced: {
ipAddress: {
ipAddressHeaders: ['x-forwarded-for', 'x-real-ip'],
disableIpTracking: false,
},
},
});
IPv6 Subnet Configuration
For rate limiting, IPv6 addresses can be grouped by subnet:
advanced: {
ipAddress: {
ipv6Subnet: 64,
},
}
Smaller values group more addresses together, which is useful when users share IPv6 prefixes.
Trusted Proxy Headers
When behind a reverse proxy, enable trusted headers:
advanced: {
trustedProxyHeaders: true,
}
Security Note: Only enable this if you trust your proxy. Malicious clients could spoof these headers otherwise.
Database Hooks for Security Auditing
Use database hooks to implement security auditing and monitoring.
Setting Up Audit Logging
import { betterAuth } from 'better-auth';
export const auth = betterAuth({
databaseHooks: {
session: {
create: {
after: async ({ data, ctx }) => {
await auditLog('session.created', {
userId: data.userId,
ip: ctx?.request?.headers.get('x-forwarded-for'),
userAgent: ctx?.request?.headers.get('user-agent'),
});
},
},
delete: {
before: async ({ data }) => {
await auditLog('session.revoked', { sessionId: data.id });
},
},
},
user: {
update: {
after: async ({ data, oldData }) => {
if (oldData?.email !== data.email) {
await auditLog('user.email_changed', {
userId: data.id,
oldEmail: oldData?.email,
newEmail: data.email,
});
}
},
},
},
account: {
create: {
after: async ({ data }) => {
await auditLog('account.linked', {
userId: data.userId,
provider: data.providerId,
});
},
},
},
},
});
Blocking Operations
Return false from a before hook to prevent an operation:
databaseHooks: {
user: {
delete: {
before: async ({ data }) => {
if (protectedUserIds.includes(data.id)) {
return false;
}
},
},
},
}
Background Tasks for Timing Attack Prevention
Sensitive operations should complete in constant time to prevent timing attacks.
Configuring Background Tasks
import { betterAuth } from 'better-auth';
export const auth = betterAuth({
advanced: {
backgroundTasks: {
handler: (promise) => {
waitUntil(promise);
},
},
},
});
This ensures operations like sending emails don't affect response timing, which could leak information about whether a user exists.
Account Enumeration Prevention
Better Auth implements several measures to prevent attackers from discovering valid accounts.
Built-in Protections
- Consistent Response Messages: Password reset always returns "If this email exists in our system, check your email for the reset link"
- Dummy Operations: When a user isn't found, Better Auth still performs token generation and database lookups with dummy values
- Background Email Sending: Emails are sent asynchronously to prevent timing differences
Additional Recommendations
For sign-up and sign-in endpoints, consider:
import { betterAuth } from 'better-auth';
export const auth = betterAuth({
emailAndPassword: {
enabled: true,
},
});
Return generic error messages like "Invalid credentials" rather than "User not found" or "Incorrect password".
Complete Security Configuration Example
import { betterAuth } from 'better-auth';
export const auth = betterAuth({
secret: process.env.BETTER_AUTH_SECRET,
baseURL: 'https://api.example.com',
trustedOrigins: ['https://app.example.com', 'https://*.preview.example.com'],
rateLimit: {
enabled: true,
storage: 'secondary-storage',
customRules: {
'/api/auth/sign-in/email': { window: 60, max: 5 },
'/api/auth/sign-up/email': { window: 60, max: 3 },
},
},
session: {
expiresIn: 60 * 60 * 24 * 7,
updateAge: 60 * 60 * 24,
freshAge: 60 * 60,
cookieCache: {
enabled: true,
maxAge: 300,
strategy: 'jwe',
},
},
account: {
encryptOAuthTokens: true,
storeStateStrategy: 'cookie',
},
advanced: {
useSecureCookies: true,
cookiePrefix: 'myapp',
defaultCookieAttributes: {
sameSite: 'lax',
},
ipAddress: {
ipAddressHeaders: ['x-forwarded-for'],
ipv6Subnet: 64,
},
backgroundTasks: {
handler: (promise) => waitUntil(promise),
},
},
databaseHooks: {
session: {
create: {
after: async ({ data, ctx }) => {
console.log(`New session for user ${data.userId}`);
},
},
},
user: {
update: {
after: async ({ data, oldData }) => {
if (oldData?.email !== data.email) {
console.log(`Email changed for user ${data.id}`);
}
},
},
},
},
});
Security Checklist
Before deploying to production: