Better Auth Validation Plugin

1.3.4 · active · verified Wed Apr 22

The `validation-better-auth` package provides a flexible and extensible validation plugin specifically designed for the `better-auth` framework. It enables developers to integrate API request validation using various schema definition libraries such as Zod, Valibot, and ArkType. It also supports Yup by internally wrapping Yup schemas to a standard format. This package is currently at version 1.3.4 and shows an active development cadence with frequent patch releases addressing build, module, and type resolution issues. Its key differentiator is its tight integration with `better-auth` and its adapter pattern, allowing for broad compatibility with different validation schema libraries rather than enforcing a specific one.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to integrate the `validation-better-auth` plugin into the `better-auth` framework, using Zod schemas for request body validation on specific API paths, including `before` and `after` hooks.

import { betterAuth } from "better-auth";
import { validator, StandardAdapter } from "validation-better-auth";
import { z } from 'zod'; // Assuming Zod is used for SignupSchema and SignInSchema

// Define your schemas (e.g., using Zod)
const SignupSchema = z.object({
    email: z.string().email(),
    password: z.string().min(8),
    confirmPassword: z.string()
}).refine(data => data.password === data.confirmPassword, {
    message: "Passwords don't match",
    path: ["confirmPassword"],
});

const SignInSchema = z.object({
    email: z.string().email(),
    password: z.string().min(8)
});

export const auth = betterAuth({
    appName: "My Validation App",
    plugins: [
        validator(
            [
                {
                    path: "/sign-up/email",
                    schema: SignupSchema,
                    before: (ctx) => {
                        console.log('Before signup validation:', ctx.payload);
                    },
                    after: (ctx) => {
                        console.log('After signup validation:', ctx.payload);
                    }
                },
                {
                    path: "/sign-in/email",
                    schema: SignInSchema,
                    before: (ctx) => {
                        console.log('Before signin validation:', ctx.payload);
                    },
                    after: (ctx) => {
                        console.log('After signin validation:', ctx.payload);
                    }
                }
            ]
        )
    ]
});

// In a real application, 'auth' would then be used to configure your authentication routes.
// For demonstration, we'll just log its presence.
console.log('Better Auth instance configured with validation plugin.');

view raw JSON →