How can get errors with NextAuth V5 and Next 14.0.3?
Unanswered
Little yellow ant posted this in #help-forum
Little yellow antOP
I have to try get erros in client component at login form but with no success.
at create-user.tsx form i use zod to validate data and error handlers, but with the next-auth i cant get errors, why this happens?
repo: https://github.com/dracoalv/next-auth-beta
this code works fine...
but at login page i cant get the errors because signIn nextAuth functions, where and how can i get errors for the inputs and show erros like "Invalid credencials" or "email doesn't exists" etc..
login form
at create-user.tsx form i use zod to validate data and error handlers, but with the next-auth i cant get errors, why this happens?
repo: https://github.com/dracoalv/next-auth-beta
this code works fine...
'use server';
import { z } from 'zod';
import { sql } from "@vercel/postgres";
import { redirect } from "next/navigation";
import bcrypt from "bcrypt";
type State = {
errors?: {
name?: string[];
email?: string[];
password?: string[];
}
}
const FormSchema = z.object({
id: z.string(),
name: z
.string({invalid_type_error: 'Insira um nome válido'})
.min(3, 'O nome deve conter pelo menos 3 caracteres.'),
email: z.string().email('Insira um e-mail válido.'),
password: z.string().min(6, 'A senha deve conter no mÃnimo 6 caracteres.')
})
const CreateUser = FormSchema.omit({ id: true });
export async function createUser(prevState: State, formData: FormData) {
const validatedFields = CreateUser.safeParse({
name: formData.get('name'),
email: formData.get('email'),
password: formData.get('password')
});
if (!validatedFields.success) {
console.log('Erros de validação:', validatedFields.error.flatten().fieldErrors)
return {
errors: validatedFields.error.flatten().fieldErrors,
message: 'Preencha todos os campos. Falha ao criar usuário.'
}
}
const { name, email, password } = validatedFields.data
const hashedPassword = await bcrypt.hash(password, 10)
try {
const newUser = await sql`
INSERT INTO users (name, email, password)
VALUES (${name}, ${email}, ${hashedPassword})
`;
console.log('Usuário criado com sucesso.', newUser.rows[0])
} catch (error) {
console.log('Falha ao criar usuário:', error)
return { message: 'Falha ao inserir usuário no banco de dados.'}
}
redirect('/auth/login')
}but at login page i cant get the errors because signIn nextAuth functions, where and how can i get errors for the inputs and show erros like "Invalid credencials" or "email doesn't exists" etc..
export async function authenticate(prevState: string | undefined, formData: FormData) {
try {
await signIn('credentials', Object.fromEntries(formData));
} catch (error) {
if ((error as Error).message.includes('CredentialsSignin')) {
return 'CredentialsSignin';
}
throw error;
}
}login form
export default function LoginForm() {
const [state, dispatch] = useFormState(authenticate, undefined);
console.log(state)
return (
<form
action={dispatch}
className="w-fit p-10 border rounded bg-emerald-50/20"
>
<h1 className="mb-10 font-medium text-lg text-zinc-600">Faça login para continuar</h1>
<div className="grid gap-1 mb-4">
<label htmlFor="email" className="text-zinc-600">E-mail</label>
<input
type="text"
id="email"
name="email"
placeholder="seuemail@dvsk.com"
className="max-w-xs h-9 px-2 text-sm placeholder:text-zinc-300 border rounded-md"
/>
</div>
<div className="grid gap-1 mb-6">
<label htmlFor="email" className="text-zinc-600">Password</label>
<input
type="password"
id="password"
name="password"
className="max-w-xs h-9 px-2 text-sm placeholder:text-zinc-300 border rounded-md"
/>
</div>
<button
type="submit"
className="h-11 px-6 mb-10 font-medium text-emerald-50 bg-emerald-600 rounded-md hover:bg-emerald-500"
>
Acessar
</button>
<p className="w-full text-sm">
Ainda não tem uma conta? {' '}
<Link href="/auth/register" className="text-blue-500 hover:underline">Crie gratuitamente.</Link>
</p>
</form>
)
}7 Replies
Cape horse mackerel
Read on https://next-auth.js.org/getting-started/client#using-the-redirect-false-option
signIn() is returning a Promise, that resolves to error, status, ok and urlLittle yellow antOP
this doc is for v4, im using v5 doc: https://authjs.dev/guides/upgrade-to-v5
signIn<"credentials", true>(provider?: "credentials" | undefined, options?: ({
redirectTo?: string | undefined;
redirect?: true | undefined;
} & Record<string, any>) | undefined, authorizationParams?: string | ... 3 more ... | undefined): Promise<...>Cape horse mackerel
may I ask why are you using v5 beta version instead of v4?
Little yellow antOP
studying?
@Little yellow ant studying?
Toyger
for studying you should use stable releases, no one will help you with beta when even developers don't know about how many problems still untested.
Little yellow antOP
ok 🙂