diff --git a/components/user-auth-form.tsx b/components/user-auth-form.tsx index 7ccff79d..723a4459 100644 --- a/components/user-auth-form.tsx +++ b/components/user-auth-form.tsx @@ -1,6 +1,7 @@ "use client" import * as React from "react" +import { useSearchParams } from "next/navigation" import { signIn } from "next-auth/react" import * as z from "zod" import { useForm } from "react-hook-form" @@ -24,6 +25,7 @@ export function UserAuthForm({ className, ...props }: UserAuthFormProps) { resolver: zodResolver(userAuthSchema), }) const [isLoading, setIsLoading] = React.useState(false) + const searchParams = useSearchParams(); async function onSubmit(data: FormData) { setIsLoading(true) @@ -31,7 +33,7 @@ export function UserAuthForm({ className, ...props }: UserAuthFormProps) { const signInResult = await signIn("email", { email: data.email.toLowerCase(), redirect: false, - callbackUrl: `${window.location.origin}/dashboard`, + callbackUrl: searchParams.get("from") || "/dashboard", }) setIsLoading(false) diff --git a/middleware.ts b/middleware.ts index f354c3e6..9f05fd14 100644 --- a/middleware.ts +++ b/middleware.ts @@ -19,7 +19,14 @@ export default withAuth( } if (!isAuth) { - return NextResponse.redirect(new URL("/login", req.url)) + let from = req.nextUrl.pathname; + if (req.nextUrl.search) { + from += req.nextUrl.search; + } + + return NextResponse.redirect( + new URL(`/login?from=${encodeURIComponent(from)}`, req.url) + ); } }, {