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

@ -2,7 +2,6 @@
import Link from "next/link";
import { useRouter } from "next/navigation";
import type { User } from "next-auth";
import { useState } from "react";
import { toast } from "sonner";
import { useSWRConfig } from "swr";
@ -22,6 +21,7 @@ import {
SidebarMenu,
useSidebar,
} from "@/components/ui/sidebar";
import type { AuthUser } from "@/lib/auth";
import {
AlertDialog,
AlertDialogAction,
@ -34,7 +34,7 @@ import {
} from "./ui/alert-dialog";
import { Tooltip, TooltipContent, TooltipTrigger } from "./ui/tooltip";
export function AppSidebar({ user }: { user: User | undefined }) {
export function AppSidebar({ user }: { user: AuthUser | undefined }) {
const router = useRouter();
const { setOpenMobile } = useSidebar();
const { mutate } = useSWRConfig();

View file

@ -176,7 +176,7 @@ export function Chat({
}, [query, sendMessage, hasAppendedQuery, id]);
const { data: votes } = useSWR<Vote[]>(
messages.length >= 2
!isReadonly && messages.length >= 2
? `${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/vote?chatId=${id}`
: null,
fetcher

View file

@ -32,6 +32,7 @@ import {
DEFAULT_CHAT_MODEL,
modelsByProvider,
} from "@/lib/ai/models";
import { signIn, useSession } from "@/lib/client";
import type { Attachment, ChatMessage } from "@/lib/types";
import { cn } from "@/lib/utils";
import {
@ -86,6 +87,8 @@ function PureMultimodalInput({
}) {
const textareaRef = useRef<HTMLTextAreaElement>(null);
const { width } = useWindowSize();
const { data: session, refetch: refetchSession } = useSession();
const [isSigningIn, setIsSigningIn] = useState(false);
const hasAutoFocused = useRef(false);
useEffect(() => {
@ -304,10 +307,21 @@ function PureMultimodalInput({
<PromptInput
className="[&>div]:rounded-xl"
onSubmit={() => {
onSubmit={async () => {
if (!input.trim() && attachments.length === 0) {
return;
}
if (!session && !isSigningIn) {
setIsSigningIn(true);
const { error } = await signIn.anonymous();
if (error) {
toast.error("Failed to create session, please try again!");
setIsSigningIn(false);
return;
}
await refetchSession();
setIsSigningIn(false);
}
if (status === "ready") {
submitForm();
} else {

View file

@ -3,7 +3,6 @@
import { isToday, isYesterday, subMonths, subWeeks } from "date-fns";
import { motion } from "framer-motion";
import { usePathname, useRouter } from "next/navigation";
import type { User } from "next-auth";
import { useState } from "react";
import { toast } from "sonner";
import useSWRInfinite from "swr/infinite";
@ -23,6 +22,7 @@ import {
SidebarMenu,
useSidebar,
} from "@/components/ui/sidebar";
import type { AuthUser } from "@/lib/auth";
import type { Chat } from "@/lib/db/schema";
import { fetcher } from "@/lib/utils";
import { LoaderIcon } from "./icons";
@ -97,7 +97,7 @@ export function getChatHistoryPaginationKey(
return `${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/history?ending_before=${firstChatFromPage.id}&limit=${PAGE_SIZE}`;
}
export function SidebarHistory({ user }: { user: User | undefined }) {
export function SidebarHistory({ user }: { user: AuthUser | undefined }) {
const { setOpenMobile } = useSidebar();
const pathname = usePathname();
const id = pathname?.startsWith("/chat/") ? pathname.split("/")[2] : null;
@ -108,9 +108,11 @@ export function SidebarHistory({ user }: { user: User | undefined }) {
isValidating,
isLoading,
mutate,
} = useSWRInfinite<ChatHistory>(getChatHistoryPaginationKey, fetcher, {
fallbackData: [],
});
} = useSWRInfinite<ChatHistory>(
user ? getChatHistoryPaginationKey : () => null,
fetcher,
{ fallbackData: [] }
);
const router = useRouter();
const [deleteId, setDeleteId] = useState<string | null>(null);

View file

@ -3,8 +3,6 @@
import { ChevronUp } from "lucide-react";
import Image from "next/image";
import { useRouter } from "next/navigation";
import type { User } from "next-auth";
import { signOut, useSession } from "next-auth/react";
import { useTheme } from "next-themes";
import {
DropdownMenu,
@ -18,23 +16,27 @@ import {
SidebarMenuButton,
SidebarMenuItem,
} from "@/components/ui/sidebar";
import { guestRegex } from "@/lib/constants";
import { signOut, useSession } from "@/lib/client";
import { LoaderIcon } from "./icons";
import { toast } from "./toast";
export function SidebarUserNav({ user }: { user: User }) {
export function SidebarUserNav({
user,
}: {
user: { email?: string | null; isAnonymous?: boolean | null };
}) {
const router = useRouter();
const { data, status } = useSession();
const { data, isPending } = useSession();
const { setTheme, resolvedTheme } = useTheme();
const isGuest = guestRegex.test(data?.user?.email ?? "");
const isGuest = data?.user?.isAnonymous ?? user.isAnonymous ?? false;
return (
<SidebarMenu>
<SidebarMenuItem>
<DropdownMenu>
<DropdownMenuTrigger asChild>
{status === "loading" ? (
{isPending ? (
<SidebarMenuButton className="h-10 justify-between bg-background data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground">
<div className="flex flex-row gap-2">
<div className="size-6 animate-pulse rounded-full bg-zinc-500/30" />
@ -84,7 +86,7 @@ export function SidebarUserNav({ user }: { user: User }) {
<button
className="w-full cursor-pointer"
onClick={() => {
if (status === "loading") {
if (isPending) {
toast({
type: "error",
description:
@ -98,7 +100,12 @@ export function SidebarUserNav({ user }: { user: User }) {
router.push("/login");
} else {
signOut({
redirectTo: "/",
fetchOptions: {
onSuccess: () => {
router.push("/");
router.refresh();
},
},
});
}
}}

View file

@ -1,6 +1,7 @@
import Form from "next/form";
import { signOut } from "@/app/(auth)/auth";
import { headers } from "next/headers";
import { redirect } from "next/navigation";
import { auth } from "@/lib/auth";
export const SignOutForm = () => {
return (
@ -8,9 +9,11 @@ export const SignOutForm = () => {
action={async () => {
"use server";
await signOut({
redirectTo: "/",
await auth.api.signOut({
headers: await headers(),
});
redirect("/");
}}
className="w-full"
>