Skip to main content

Better Auth with Neon DB + Drizzle ORM

Minimal, customizable authentication for Next.js using Better Auth, Neon DB & Drizzle ORM

Updated 14 min readMarkdown
Better Auth with Neon DB + Drizzle ORM

Over the past two years I’ve used Supabase for almost every project — it made building apps fast and effortless. I didn’t have to worry about sessions, token exchange/refresh, or other auth details: copy-paste a few snippets and things worked in hours. The only limitation was Supabase’s free tier, which caps you at two projects, so I started looking for alternatives that allow unlimited projects. I discovered Neon and Drizzle, but then I ran into authentication: because Supabase had handled auth for me, I hadn’t implemented it manually and had forgotten some MERN-stack techniques. Next.js also differs from the MERN workflow, so I wasn’t sure how to proceed. I could have used Clerk, but this is a small hobby project and I wanted a minimal UX. That’s when I found Better Auth — a flexible, customizable auth provider that’s easy to implement. In this post I’ll share what I learned and how I integrated Better Auth with Neon and Drizzle in a Next.js app.

Requirements

For this project I chose Next.js so I’ll cover the entire logic within its Next.js implementation.

  • Next.js

  • Neon Project

  • Drizzle ORM ( optional but recommended )

  • Shadcn ( for ready-made components )

Installation

npx create-next-app@latest

You can use above command to install the next project but since we’re using Shadcn also I personally recommend that use shadcn’s create project command:

Link: https://ui.shadcn.com/create

Here, you’ve to choose the shadcn theme and also you can customize it as you want. There’s also one random option just click R key and it’ll generate random style. Just choose one of them and copy the command below is the default start command which also works.

npx shadcn@latest create --preset "https://ui.shadcn.com/init?base=radix&style=nova&baseColor=neutral&theme=neutral&iconLibrary=lucide&font=inter&menuAccent=subtle&menuColor=default&radius=default&template=next&rtl=false" --template next

This will be your project structure, ignore the drizzle.config.ts we’ll comeback to it.

Now to get started with Better Auth we need a database to store the user's data for this I'll be using Neon DB with Drizzle ORM(for type safety).

The drizzle docs can be little bit tricky b'coz their docs aren't aligning exactly with our project structure so we needed to change some configs.

Neon Database

So first we need to get the Database URL from Neon. Go to the Neon and do sign up then create a project. In the project dashboard you'll find a connect button click on it and get the database URL. Put it inside your .env file with DATABASE_URL .

Drizzle ORM

Install Drizzle:

npm i drizzle-orm
npm i -D drizzle-kit

Create a /db folder inside /lib. Now inside /db folder create index.ts this file will contain our db related configurations. You can also give a different name if you want but using "index" name as a file we don't need to write that in import path. This will also work fine:

import { db } from "@/lib/db";

Since this project is deployed on Vercel using the default Node.js runtime, I’m using the postgres-js driver:

// /lib/db/index.ts:

import { drizzle } from "drizzle-orm/postgres-js";
export const db = drizzle(process.env.DATABASE_URL!);

If you want to use Neon-HTTP:

You’re deploying to platforms like Cloudflare Workers or other edge/serverless runtimes

npm i @neondatabase/serverless
// /lib/db/index.ts:

import { neon } from '@neondatabase/serverless';
import { drizzle } from 'drizzle-orm/neon-http';

const sql = neon(process.env.DATABASE_URL!);
const db = drizzle({ client: sql });

const result = await db.execute('select 1');
❗
I haven't used this method so do some research from side also. You can learn more about this here.

Drizzle Configuration: drizzle.config.ts

Create this file at the root of your project. This will help us to generate and migrate database schema to the Neon DB. As you can in the schema field the path includes schema.ts inside the /lib/db so you to create it for now keep it empty. But in next section we'll import schema generated through better auth cli generate command.

import { defineConfig } from "drizzle-kit";
import * as dotenv from "dotenv";

dotenv.config({ path: ".env" });

export default defineConfig({
  out: "./migrations",
  schema: "./lib/db/schema.ts",
  dialect: "postgresql",
  dbCredentials: {
    url: process.env.DATABASE_URL!,
  },
});

Generate Better Auth Schemas:

Below command will generate schema inside schema.ts which we created before.

npx @better-auth/cli@latest generate --output lib/db/schema.ts

Now this schema is not actual schema which we can send to the neon db for we've to use drizzle's cli commands generate and migrate .

npx drizzle-kit generate --name=auth-schema
npx drizzle-kit migrate

generate command will generate schema for your auth related tables and migrate command will push that schema which will create tables inside your neon project's tables tab.

Better Auth Implementation

We will start by creating auth.ts file inside /lib.

// lib/auth.ts:

import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { db } from "./db";
import * as schema from "./db/schema";

export const auth = betterAuth({
  database: drizzleAdapter(db, {
    provider: "pg",
    schema: {
      ...schema
    },
  }),
  emailAndPassword: {
    enabled: true, 
  },
  socialProviders: {
    google: {
      enabled: true,
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
    },
  },
});

In this we're using two auth providers one is email and second one google auth. Of course you need to grab your google client id and secret. If you don't want to use it then just remove it.

Now we've to create an auth client through which we'll make all the auth related calls. Create a auth-client.ts file inside /lib folder. Since we're using next.js we won't be using separate url for backend but in any case if your backend is on different domain/url you need to configure here as baseURL .

// lib/auth-client.ts:

import { createAuthClient } from "better-auth/react"
export const authClient = createAuthClient()

// If your backend is on different domain
export const authClient = createAuthClient({
    baseURL: "https://api.example.com"
})
// I personally suggest to put it inside a env variable instead hard coding it!

Now to make the authentication work we need one last thing to configure which an API route. In better auth they're using different strategy to handle auth api. We need to create an catch-all route inside /app/api/auth .

  • So of course first create /api folder inside /app .

  • Now /auth folder inside /api .

  • Create one more folder with name [...auth] inside /auth and yes this will be our catch-all route. But to implement route we need to create route.ts file inside that catch-all route folder.

// app/api/auth/[...auth]/route.ts

import { auth } from "@/lib/auth"; // path to your auth file
import { toNextJsHandler } from "better-auth/next-js";

export const { POST, GET } = toNextJsHandler(auth);

Now it's time for frontend side

Create a /auth folder inside /app (of course you can create inside app directory directly but creating auth folder separation is my way). Now create /login and /signup folders inside /auth folder and also create page.tsx file inside each of them.

Make sure to install bellow libraries, this will useful for creating login form. I personally used React Hook Form here but from shadcn ;).

npm i zod react-hook-form @hookform/resolvers lucide-react

Components to add:

npx shadcn@latest add card button sonner spinner field separator input-group input

Don't forget to add Toaster component inside layout.tsx of root.

// layout.tsx:

import { Toaster } from "sonner";

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>
          {children}
          <Toaster richColors />
      </body>
    </html>
  );
}

Login Form:

"use client";

import { useState } from "react";
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { toast } from "sonner";
import { Spinner } from "@/components/ui/spinner";
import { authClient } from "@/lib/auth-client";
import z from "zod";
import { Controller, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { Field, FieldError, FieldGroup, FieldLabel, FieldSeparator } from "@/components/ui/field";
import { Separator } from "@/components/ui/separator";
import Link from "next/link";
import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from "@/components/ui/input-group";
import { Eye, EyeOff } from "lucide-react";
import { Input } from "@/components/ui/input";

const formSchema = z.object({
  email: z.email("Invalid email address"),
  password: z.string().min(6, "Password must be at least 6 characters long"),
})

type FormValues = z.infer<typeof formSchema>;

export default function Page() {
  const [showPassword, setShowPassword] = useState(false);
  const [googleSignInLoading, setGoogleSignInLoading] = useState(false);

  const form = useForm<FormValues>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      email: "",
      password: "",
    },
  })

  const onSubmit = async (values: FormValues) => {
    await authClient.signIn.email({
      email: values.email,
      password: values.password,
      callbackURL: "/dashboard",
    }, {
      onSuccess: () => {
        toast.success("User logged in successfully!");
      },
      onError: (error) => {
        console.error(error)
        toast.error(error.error.message)
      }
    })
  };

  const handleGoogleLogin = async () => {
    try {
      setGoogleSignInLoading(true)
      await authClient.signIn.social({
        provider: "google",
        callbackURL: "/dashboard",
        errorCallbackURL: "/auth/login",
      }, {
        onSuccess: () => {
          // toast.success("User logged in successfully!");
        },
        onError: (error) => {
          console.error(error)
          toast.error(error.error.message)
        }
      })
    } catch (error) {
      console.error(error);
      toast.error("Something went wrong!")
    } finally {
      setGoogleSignInLoading(false)
    }
  }

  return (
    <div className="min-h-screen flex justify-center items-center p-4 sm:p-6">
      <Card className="w-full max-w-96">
        <CardHeader>
          <CardTitle>Login Page</CardTitle>
          <CardDescription>
            Login to resume your journey!
          </CardDescription>
        </CardHeader>

        <CardContent>
          <Button
            type="button"
            variant={"outline"}
            className="cursor-pointer"
            disabled={googleSignInLoading}
            onClick={handleGoogleLogin}
          >
            {googleSignInLoading ? <Spinner /> : (
              <>
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                  <path
                    d="M12.48 10.92v3.28h7.84c-.24 1.84-.853 3.187-1.787 4.133-1.147 1.147-2.933 2.4-6.053 2.4-4.827 0-8.6-3.893-8.6-8.72s3.773-8.72 8.6-8.72c2.6 0 4.507 1.027 5.907 2.347l2.307-2.307C18.747 1.44 16.133 0 12.48 0 5.867 0 .307 5.387.307 12s5.56 12 12.173 12c3.573 0 6.267-1.173 8.373-3.36 2.16-2.16 2.84-5.213 2.84-7.667 0-.76-.053-1.467-.173-2.053H12.48z"
                    fill="currentColor"
                  />
                </svg>
                Login with Google
              </>
            )}
          </Button>
          <form onSubmit={form.handleSubmit(onSubmit)} id="login-form">
            <FieldGroup>
              <FieldSeparator className="*:data-[slot=field-separator-content]:bg-card">
                Or Continue with
              </FieldSeparator>
              <Controller
                name="email"
                control={form.control}
                render={({ field, fieldState: { invalid, error } }) => (
                  <Field data-invalid={invalid}>
                    <FieldLabel htmlFor={field.name}>Email</FieldLabel>
                    <Input
                      {...field}
                      id={field.name}
                      name={field.name}
                      type="text"
                      placeholder="mail@site.com"
                    />
                    {invalid && <FieldError errors={[error]} />}
                  </Field>
                )}
              />

              <Controller
                name="password"
                control={form.control}
                render={({ field, fieldState: { invalid, error } }) => (
                  <Field data-invalid={invalid}>
                    <FieldLabel htmlFor={field.name}>Password</FieldLabel>
                    <InputGroup>
                      <InputGroupInput
                        {...field}
                        type={showPassword ? "text" : "password"}
                        id={field.name}
                        placeholder="Enter Password"
                        name={field.name}
                      />
                      <InputGroupAddon align={"inline-end"}>
                        <InputGroupButton
                          type="button"
                          onClick={() => setShowPassword((prev) => !prev)}
                          onMouseDown={(e) => e.preventDefault()}
                          size={"icon-xs"}
                          className="cursor-pointer"
                        >
                          {showPassword ? <EyeOff /> : <Eye />}
                        </InputGroupButton>
                      </InputGroupAddon>
                    </InputGroup>
                    {invalid && <FieldError errors={[error]} />}
                  </Field>
                )}
              />
            </FieldGroup>
            <Link href="/auth/reset-password">
              <div className="w-full text-xs text-right underline-offset-4 hover:underline mt-2 hover:text-primary transition-color duration-300">Forgot password ?</div>
            </Link>
          </form>
        </CardContent>
        <CardFooter className="flex flex-col gap-4">
          <Field orientation={"horizontal"}>
            <Button type="button" variant={"outline"} className="cursor-pointer" onClick={() => form.reset()}>
              Reset
            </Button>
            <Button type="submit" className="cursor-pointer" disabled={form.formState.isSubmitting} form="login-form">
              {form.formState.isSubmitting ? <Spinner /> : "Login"}
            </Button>
          </Field>

          <Separator />

          <span className="text-center">
            Don&apos;t have an account ?
            <Link href="/auth/signup">
              <Button type="button" variant="link" className="cursor-pointer">
                Sign Up
              </Button>
            </Link>
          </span>
        </CardFooter>
      </Card>
    </div>
  );
}

Sign Up Form:

"use client";

import Link from "next/link";
import { useState } from "react";
import { Eye, EyeOff } from "lucide-react";
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  Field,
  FieldError,
  FieldGroup,
  FieldLabel,
} from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import {
  InputGroup,
  InputGroupAddon,
  InputGroupButton,
  InputGroupInput,
} from "@/components/ui/input-group";
import { Button } from "@/components/ui/button";
import { Spinner } from "@/components/ui/spinner";
import { Controller, useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { toast } from "sonner";
import { Separator } from "@/components/ui/separator";
import { authClient } from "@/lib/auth-client";
import { useRouter } from "next/navigation";

const formSchema = z.object({
  name: z.string().min(3, "Name must be at least 3 characters long"),
  email: z.email("Invalid email address"),
  password: z.string().min(6, "Password must be at least 6 characters long"),
  confirmPassword: z.string().min(6, "Confirm password must be at least 6 characters long"),
}).refine((data) => data.password === data.confirmPassword, {
  message: "Passwords do not match",
  path: ["confirmPassword"],
})

type FormValues = z.infer<typeof formSchema>;

export default function Page() {
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const router = useRouter();

  const form = useForm<FormValues>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      name: "",
      email: "",
      password: "",
      confirmPassword: "",
    },
  })

  const onSubmit = async (values: FormValues) => {
    await authClient.signUp.email({
      email: values.email,
      password: values.password,
      name: values.name,
      callbackURL: "/dashboard"
    }, {
      onSuccess: () => {
        toast.success("User registered successfully!")
        router.push("/dashboard");
      },
      onError: (error) => {
        console.error(error)
        toast.error(error.error.message)
      }
    })
  };

  const handleGoogleLogin = () => {
    toast.info("Google auth login clicked!")
  }
  return (
    <div className="min-h-screen flex justify-center items-center p-4 sm:p-6">
      <Card className="max-w-96 w-full">
        <CardHeader>
          <CardTitle>Sign Up Page</CardTitle>
          <CardDescription>Start your journey!</CardDescription>
        </CardHeader>

        <CardContent>
          <form onSubmit={form.handleSubmit(onSubmit)} id="signup-form">
            <FieldGroup>
              <Controller
                name="name"
                control={form.control}
                render={({ field, fieldState: { invalid, error } }) => (
                  <Field data-invalid={invalid}>
                    <FieldLabel htmlFor={field.name}>Name</FieldLabel>
                    <Input
                      {...field}
                      id={field.name}
                      type="text"
                      placeholder="John Doe"
                      aria-invalid={invalid}
                    />
                    {invalid && <FieldError errors={[error]} />}
                  </Field>
                )}
              />

              <Controller
                name="email"
                control={form.control}
                render={({ field, fieldState: { invalid, error } }) => (
                  <Field data-invalid={invalid}>
                    <FieldLabel htmlFor={field.name}>Email</FieldLabel>
                    <Input
                      {...field}
                      id={field.name}
                      type="text"
                      placeholder="mail@site.com"
                      aria-invalid={invalid}
                    />
                    {invalid && <FieldError errors={[error]} />}
                  </Field>
                )}
              />

              <Controller
                name="password"
                control={form.control}
                render={({ field, fieldState: { invalid, error } }) => (
                  <Field data-invalid={invalid}>
                    <FieldLabel htmlFor={field.name}>Password</FieldLabel>
                    <InputGroup>
                      <InputGroupInput
                        {...field}
                        id={field.name}
                        type={showPassword ? "text" : "password"}
                        placeholder="Enter your password"
                        aria-invalid={invalid}
                      />
                      <InputGroupAddon align={"inline-end"}>
                        <InputGroupButton
                          type="button"
                          onClick={() => setShowPassword((prev) => !prev)}
                          onMouseDown={(e) => e.preventDefault()}
                          size={"icon-xs"}
                          className="cursor-pointer"
                        >
                          {showPassword ? <EyeOff /> : <Eye />}
                        </InputGroupButton>
                      </InputGroupAddon>
                    </InputGroup>
                    {invalid && <FieldError errors={[error]} />}
                  </Field>
                )}
              />

              <Controller
                name="confirmPassword"
                control={form.control}
                render={({ field, fieldState: { invalid, error } }) => (
                  <Field data-invalid={invalid}>
                    <FieldLabel htmlFor={field.name}>Confirm Password</FieldLabel>
                    <InputGroup>
                      <InputGroupInput
                        {...field}
                        id={field.name}
                        type={showConfirmPassword ? "text" : "password"}
                        placeholder="Re-enter your password"
                        aria-invalid={invalid}
                      />
                      <InputGroupAddon align={"inline-end"}>
                        <InputGroupButton
                          type="button"
                          onClick={() => setShowConfirmPassword((prev) => !prev)}
                          onMouseDown={(e) => e.preventDefault()}
                          size={"icon-xs"}
                          className="cursor-pointer"
                        >
                          {showConfirmPassword ? <EyeOff /> : <Eye />}
                        </InputGroupButton>
                      </InputGroupAddon>
                    </InputGroup>
                    {invalid && <FieldError errors={[error]} />}
                  </Field>
                )}
              />
            </FieldGroup>
          </form>
        </CardContent>
        <CardFooter className="flex flex-col gap-2">
          <Field orientation={"horizontal"}>
            <Button type="button" variant={"outline"} onClick={() => form.reset()} className="cursor-pointer">
              Reset
            </Button>
            <Button type="submit" form="signup-form" disabled={form.formState.isSubmitting} className="cursor-pointer">
              {form.formState.isSubmitting ? <Spinner /> : "Sign Up"}
            </Button>
          </Field>

          <Separator className="my-4" />

          <span className="text-sm">
            Already have an account ?
            <Link href="/auth/login">
              <Button variant={"link"} className="cursor-pointer">Login</Button>
            </Link>
          </span>
        </CardFooter>
      </Card>
    </div>
  );
}

Now to understand more and in detail you go through Better Auth Docs.

Later in future I'll create site where you can find every single thing about auth and its tools, tech etc everything in one place and you don't have to go through different multiple docs. :)

Conclusion

In this post we walked through why I moved from Supabase to a Neon + Drizzle + Better Auth stack for my Next.js projects: to get unlimited projects, fine-grained control over authentication, and a minimal UX without paying for heavyweight third-party auth on hobby builds. Better Auth fills the gap left by moving away from an all-in-one BaaS by providing simple, customizable authentication flows that integrate cleanly with Neon as the database and Drizzle as the ORM (optional but very helpful).

Key takeaways

  • Neon gives you a solid, scalable Postgres foundation with fewer limits than some other hosted DBs.

  • Drizzle ORM makes working with Postgres in Next.js pleasant and type-safe; it’s optional but recommended for maintainability.

  • Better Auth lets you implement session/token handling and UX exactly how you want it, without the friction of rebuilding everything from scratch.

  • Keep security practices in place: use environment variables for keys, protect server-side routes, and validate tokens on the server.

Next steps

  • Finish wiring server-side session checks in your Next.js API or middleware so pages that require auth are protected.

  • Add database migrations and a clear Drizzle schema to map auth-related tables (users, sessions, tokens).

  • Prototype a small, polished auth UI (shadcn components are great for this) and test flows: sign-up, login, token refresh, logout, and role-based access if needed.

  • Read the Better Auth, Neon, and Drizzle docs for advanced features (webhooks, connection pooling, and complex migrations).

Wrap-up If you want control, scalability, and the freedom to run many projects during development, the Neon + Drizzle + Better Auth combo is a pragmatic, developer-friendly choice. It requires a bit more setup than an opinionated BaaS, but the payoff—customization, cost control, and a lean UX—makes it worth the effort for hobby and side projects.

About the author

  • I work as a Full Stack Web Developer. My primary tech stack is Next.js and Supabase, but I can also work with MERN stack. Building meaningful and production ready sites is my end goal in every project. I always curious to learn and try out new things which can improve my skills and performance.

No comments yet. Be the first to comment.