fix(auth): migrate from next-auth to better-auth (#1453)

This commit is contained in:
dancer 2026-03-13 23:18:01 +00:00 committed by GitHub
parent 453f5bb3e6
commit b4f595a68c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
40 changed files with 668 additions and 390 deletions

View file

@ -1,10 +1,7 @@
"use server";
import { z } from "zod";
import { createUser, getUser } from "@/lib/db/queries";
import { signIn } from "./auth";
import { auth } from "@/lib/auth";
const authFormSchema = z.object({
email: z.string().email(),
@ -25,10 +22,11 @@ export const login = async (
password: formData.get("password"),
});
await signIn("credentials", {
email: validatedData.email,
password: validatedData.password,
redirect: false,
await auth.api.signInEmail({
body: {
email: validatedData.email,
password: validatedData.password,
},
});
return { status: "success" };
@ -61,24 +59,29 @@ export const register = async (
password: formData.get("password"),
});
const [user] = await getUser(validatedData.email);
if (user) {
return { status: "user_exists" } as RegisterActionState;
}
await createUser(validatedData.email, validatedData.password);
await signIn("credentials", {
email: validatedData.email,
password: validatedData.password,
redirect: false,
const result = await auth.api.signUpEmail({
body: {
email: validatedData.email,
password: validatedData.password,
name: validatedData.email,
},
});
if (!result) {
return { status: "failed" };
}
return { status: "success" };
} catch (error) {
if (error instanceof z.ZodError) {
return { status: "invalid_data" };
}
const message = error instanceof Error ? error.message : "";
if (message.includes("already exists") || message.includes("UNIQUE")) {
return { status: "user_exists" };
}
return { status: "failed" };
}
};

View file

@ -1 +0,0 @@
export { GET, POST } from "@/app/(auth)/auth";

View file

@ -1,21 +0,0 @@
import { NextResponse } from "next/server";
import { getToken } from "next-auth/jwt";
import { signIn } from "@/app/(auth)/auth";
import { isDevelopmentEnvironment } from "@/lib/constants";
export async function GET(request: Request) {
const { searchParams } = new URL(request.url);
const redirectUrl = searchParams.get("redirectUrl") || "/";
const token = await getToken({
req: request,
secret: process.env.AUTH_SECRET,
secureCookie: !isDevelopmentEnvironment,
});
if (token) {
return NextResponse.redirect(new URL("/", request.url));
}
return signIn("guest", { redirect: true, redirectTo: redirectUrl });
}

View file

@ -1,14 +0,0 @@
import type { NextAuthConfig } from "next-auth";
export const authConfig = {
basePath: "/api/auth",
pages: {
signIn: "/login",
newUser: "/",
},
providers: [
// added later in auth.ts since it requires bcrypt which is only compatible with Node.js
// while this file is also used in non-Node.js environments
],
callbacks: {},
} satisfies NextAuthConfig;

View file

@ -1,94 +0,0 @@
import { compare } from "bcrypt-ts";
import NextAuth, { type DefaultSession } from "next-auth";
import type { DefaultJWT } from "next-auth/jwt";
import Credentials from "next-auth/providers/credentials";
import { DUMMY_PASSWORD } from "@/lib/constants";
import { createGuestUser, getUser } from "@/lib/db/queries";
import { authConfig } from "./auth.config";
export type UserType = "guest" | "regular";
declare module "next-auth" {
interface Session extends DefaultSession {
user: {
id: string;
type: UserType;
} & DefaultSession["user"];
}
interface User {
id?: string;
email?: string | null;
type: UserType;
}
}
declare module "next-auth/jwt" {
interface JWT extends DefaultJWT {
id: string;
type: UserType;
}
}
export const {
handlers: { GET, POST },
auth,
signIn,
signOut,
} = NextAuth({
...authConfig,
providers: [
Credentials({
credentials: {},
async authorize({ email, password }: any) {
const users = await getUser(email);
if (users.length === 0) {
await compare(password, DUMMY_PASSWORD);
return null;
}
const [user] = users;
if (!user.password) {
await compare(password, DUMMY_PASSWORD);
return null;
}
const passwordsMatch = await compare(password, user.password);
if (!passwordsMatch) {
return null;
}
return { ...user, type: "regular" };
},
}),
Credentials({
id: "guest",
credentials: {},
async authorize() {
const [guestUser] = await createGuestUser();
return { ...guestUser, type: "guest" };
},
}),
],
callbacks: {
jwt({ token, user }) {
if (user) {
token.id = user.id as string;
token.type = user.type;
}
return token;
},
session({ session, token }) {
if (session.user) {
session.user.id = token.id;
session.user.type = token.type;
}
return session;
},
},
});

View file

@ -2,12 +2,12 @@
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useSession } from "next-auth/react";
import { useActionState, useEffect, useState } from "react";
import { AuthForm } from "@/components/auth-form";
import { SubmitButton } from "@/components/submit-button";
import { toast } from "@/components/toast";
import { useSession } from "@/lib/client";
import { type LoginActionState, login } from "../actions";
export default function Page() {
@ -23,9 +23,9 @@ export default function Page() {
}
);
const { update: updateSession } = useSession();
const { refetch } = useSession();
// biome-ignore lint/correctness/useExhaustiveDependencies: router and updateSession are stable refs
// biome-ignore lint/correctness/useExhaustiveDependencies: router and refetch are stable refs
useEffect(() => {
if (state.status === "failed") {
toast({
@ -39,7 +39,7 @@ export default function Page() {
});
} else if (state.status === "success") {
setIsSuccessful(true);
updateSession();
refetch();
router.refresh();
}
}, [state.status]);

View file

@ -2,11 +2,11 @@
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useSession } from "next-auth/react";
import { useActionState, useEffect, useState } from "react";
import { AuthForm } from "@/components/auth-form";
import { SubmitButton } from "@/components/submit-button";
import { toast } from "@/components/toast";
import { useSession } from "@/lib/client";
import { type RegisterActionState, register } from "../actions";
export default function Page() {
@ -22,9 +22,9 @@ export default function Page() {
}
);
const { update: updateSession } = useSession();
const { refetch } = useSession();
// biome-ignore lint/correctness/useExhaustiveDependencies: router and updateSession are stable refs
// biome-ignore lint/correctness/useExhaustiveDependencies: router and refetch are stable refs
useEffect(() => {
if (state.status === "user_exists") {
toast({ type: "error", description: "Account already exists!" });
@ -39,7 +39,7 @@ export default function Page() {
toast({ type: "success", description: "Account created successfully!" });
setIsSuccessful(true);
updateSession();
refetch();
router.refresh();
}
}, [state.status]);