Better Auth Custom Credentials Plugin

0.1.8 · active · verified Wed Apr 22

This package provides a plugin for the `better-auth` library, enabling highly customizable credentials-based authentication. It allows developers to integrate `better-auth` with virtually any backend authentication system, such as Rails, Django, custom APIs, or LDAP, while leveraging `better-auth`'s existing session management infrastructure. Currently at version 0.1.8, the library is in active development, meaning minor versions may introduce breaking changes to its API. Key differentiators include the ability to define flexible input schemas using Zod for robust validation, store arbitrary custom data (like JWTs or permissions) directly within `better-auth` sessions, configure auto sign-up features, and set custom session expiry per authentication method. It offers a comprehensive solution for adapting diverse authentication logic to the `better-auth` ecosystem.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates client-side setup for `better-auth-custom-credentials`, including extending the auth client, signing in with custom credentials, and retrieving session data.

import { createAuthClient } from 'better-auth/react';
import { extendAuthClientWithCredentials } from 'better-auth-custom-credentials';

// Create a basic Better Auth client, ensuring credentials are included for session management.
// This client will interact with your server-side Better Auth setup.
export const authClient = extendAuthClientWithCredentials(
  createAuthClient({
    fetch: (url, init) => {
      return fetch(url, {
        ...init,
        credentials: 'include', // Important: Ensures cookies are sent with requests
        cache: 'no-store',
      });
    },
  })
);

async function authenticateAndGetSession() {
  console.log('Attempting to sign in with credentials...');
  // Sign in using the credentials method. The input object must match the server-side Zod schema.
  const result = await authClient.signIn.credentials({
    email: 'user@example.com',
    otp: '123456',
    rememberMe: true,
  });

  if (result.ok) {
    console.log('Sign in successful!');
    // Retrieve the session data after successful authentication.
    const { data: session } = await authClient.getSession();
    const jwt = session?.data?.jwt;
    const permissions = session?.data?.permissions;

    console.log('Session Data:', session);
    console.log('JWT:', jwt);
    console.log('Permissions:', permissions);
  } else {
    console.error('Sign in failed:', result.reason);
  }
}

// Example call (in a real app, this would be triggered by a form submission or similar event)
// authenticateAndGetSession();

view raw JSON →