Login Risk Scoring for Better Auth

Add login risk scoring to Better Auth with one plugin, or own the code with before and after hooks. Block risky sign-ins before the session exists.

guidesbetter-auth

Better Auth checks the password. It does not ask whether the login looks right. A correct password from a new country, a Tor exit node, or a bot that tried four thousand other accounts first still gets a session.

Better Auth has a hook system that runs code before and after any endpoint. That is the right place to ask LoginLlama for a risk score. You get the answer before the session exists, so you can refuse the sign-in.

What you need

  • A Better Auth app using email and password sign-in.
  • A LoginLlama API key. New accounts get 100 free checks.

Put the key in your environment:

LOGINLLAMA_API_KEY=your-key-here

The plugin

Install it:

npm install better-auth-loginllama

Add it where you call betterAuth():

import { betterAuth } from 'better-auth';
import { loginLlama } from 'better-auth-loginllama';

export const auth = betterAuth({
  emailAndPassword: { enabled: true },
  plugins: [loginLlama()]
});

That's the whole setup. On the client, a refused sign-in comes back with the error code LOGINLLAMA_RISKY_SIGN_IN, so you can tell the user why:

const { error } = await authClient.signIn.email({ email, password });
if (error?.code === 'LOGINLLAMA_RISKY_SIGN_IN') {
  // Offer a password reset or a support link.
}

The plugin is MIT licensed and on GitHub. Pass loginLlama({ blockAt: 6 }) to change the threshold.

Or write the hooks yourself

The plugin is about 60 lines. If you'd rather own them, this is the same logic as two hooks. It goes in the file where you call betterAuth() and needs no SDK, only fetch.

import { betterAuth } from 'better-auth';
import { APIError, createAuthMiddleware } from 'better-auth/api';

const BLOCK_AT = 8;

type LoginCheck = { risk_score: number; risk_codes: string[] };

async function checkLogin(
  email: string,
  headers: Headers,
  outcome: 'pending' | 'success' | 'failed'
): Promise<LoginCheck | null> {
  const ip = headers.get('x-forwarded-for')?.split(',')[0]?.trim();

  const response = await fetch('https://loginllama.app/api/v1/login/check', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Accept: 'application/vnd.api+json',
      'X-API-KEY': process.env.LOGINLLAMA_API_KEY!
    },
    body: JSON.stringify({
      identity_key: email,
      ip_address: ip,
      user_agent: headers.get('user-agent') ?? undefined,
      authentication_outcome: outcome
    }),
    // A slow check must not hold up your login.
    signal: AbortSignal.timeout(2000)
  }).catch(() => null);

  // Fail open: if LoginLlama is unreachable or errors, let the login through.
  if (!response?.ok) return null;
  return (await response.json()).data.attributes;
}

export const auth = betterAuth({
  hooks: {
    before: createAuthMiddleware(async (ctx) => {
      if (ctx.path !== '/sign-in/email') return;

      const result = await checkLogin(
        ctx.body.email,
        ctx.headers ?? new Headers(),
        'pending'
      );

      if (result && result.risk_score >= BLOCK_AT) {
        throw new APIError('FORBIDDEN', {
          message: 'This sign-in looks risky. Try again from a trusted device.'
        });
      }
    }),

    after: createAuthMiddleware(async (ctx) => {
      if (ctx.path !== '/sign-in/email') return;

      const failed = ctx.context.returned instanceof APIError;
      await checkLogin(
        ctx.body.email,
        ctx.headers ?? new Headers(),
        failed ? 'failed' : 'success'
      );
    })
  }
  // ...your existing Better Auth options
});

How it works

The before hook runs when someone submits the sign-in form. It sends the email, IP address and user agent with authentication_outcome: 'pending'. LoginLlama returns a score from 0 to 10 and a list of reason codes, such as a Tor exit node, a new device or impossible travel. A score of 8 or more throws a FORBIDDEN error, and Better Auth never creates the session.

The after hook tells LoginLlama how the attempt ended. That is how it learns which devices and places are normal for each user, so the next score is better. Each call counts as one check against your plan.

Two choices in the code are yours to change.

The threshold. LoginLlama marks a login as failing above 5. This guide blocks at 8, so you only refuse the clearest cases at first. Lower it once you have watched real scores in the dashboard.

The fail-open rule. If the request errors or takes more than two seconds, the login goes through. A fraud check should never lock out your customers because of an outage on our side or yours.

Step up instead of blocking

A block is blunt. For scores between 5 and 7 you can ask for a second factor instead. Better Auth ships a twoFactor plugin, so a middle band can send the user to that flow and keep the hard block for the top of the range. The detecting suspicious logins without blocking customers guide covers how to choose the bands.

Test it

Sign in as normal and open the LoginLlama dashboard. The attempt shows up within a few seconds with its score and reason codes. To see a block, sign in through a VPN or Tor exit node and watch the score climb.

You can also try single addresses with the free IP reputation checker.

Let your agent do it

If you use Claude Code, Cursor or Codex, paste the install prompt from the docs and tell it you use Better Auth. It will find your auth file and add the hooks.

Create a free account to get an API key.