OGZY MMO
OGZY MMO

Reputation: 11

Handling 500 Internal Server Error on tRPC Mutation in a Next.js T3 Stack Application

When calling the auth.UserChecker mutation from my React frontend, the server responds with a 500 error. The mutation is intended to check user credentials during login. Also, the register page is the same thing as a login page, but does just different input this is the Hum getting there

List of tools being used

Location of error occurred trpc query : Src -> server -> api -> routers -> auth.ts

Being used : Src -> components -> auth -> [ register.tsx. | login.tsx ]

The rest of the T3 app configuration is default

https://github.com/gaveone/expo-A

login.tsx

"use client";
import { api } from "@/trpc/react";
function Login() {
  const { toast } = useToast();
  const UserChecker =  api.auth.UserChecker.useMutation({
    onSuccess: (response) => {
      console.log("Mutation successful", response);
      // Handle successful mutation, e.g., redirect or update UI
    },
    onError: (error) => {
      console.log("Mutation error", error);
      toast({
        variant: "destructive",
        title: "Error", 
        
        description: "An error occurred during login."
      });
    }
  })
  const [user, setNewUser] = useState({
    email: "",
    password: "",
  });
  const loginForm = z.object({
    email: z
      .string()
      .min(1, { message: "This field has to be filled." })
      .email("This is not a valid email."),
    password: z.string().min(1, { message: "This field has to be filled" }),
  });

   async function LoginFormSubmet() {
    const validUser = loginForm.safeParse(user);
   
      if (validUser.data) {
        console.log("4");

        const Data = validUser.data;
        UserChecker.mutate(Data)
          
      }
    
  }
  return (
    <>
      
       Input will be here.

      <Button
        
        className=" relative w-48"
        onClick={(e) => {
          e.preventDefault();
          LoginFormSubmet();
        }}
      >
        {" "}
        Register
      </Button>
     
    </>
  );
}

export default Login;

trpc query

import { object, z } from "zod";
import bcrypt from 'bcryptjs';

import {
  createTRPCRouter,
  protectedProcedure,
  publicProcedure,
} from "@/server/api/trpc";

export const authRouter = createTRPCRouter({
    UserChecker:publicProcedure.input(z.object({email:z.string() ,password:z.string()}))
    .mutation(async({ctx,input})=>{
        console.log(input);
        return JSON.parse(JSON.stringify({data:"password"}));

    }),
    makeNewUser:publicProcedure.input(z.object({
        name: z.string().min(1 ,{message:"This field has to be filled."}),
        dateOfBirth:z.string().min(1 ,{message:"This field has to be filled."}),
        email:z.string().min(1, { message: "This field has to be filled." }).email("This is not a valid email."),
        password:z.string().min(5 ,{message:"password  must be at least 5 characters"}),
        confirmPassword:z.string()

    })).mutation( async({ctx ,input})=>{
        const FindUser = await ctx.db.user.findUnique({
            where:{
                email:input.email
            }
        })

        if(FindUser){return{error:"this user exists"}}
        if(!FindUser){
            const salt = await bcrypt.genSalt(10);
            const passwordHash =  await bcrypt.hash(input.password, salt);
        const newUser = await ctx.db.user.create({
            data:{
                name:input.name,
                email:input.email,
                dateOfBirth:input.dateOfBirth,
                password:passwordHash
            }
        })

        }


    }),
    findUser:publicProcedure.input(z.object({
        email:z.string().min(1, { message: "This field has to be filled." }).email("This is not a valid email.")
    })).query(async({ ctx ,input}) =>{
        return ctx.db.user.findUnique({where:{email:input.email}})
    }),

    
    findUserValidation:publicProcedure.input(z.object({
        email:z.string().min(1, { message: "This field has to be filled." }).email("This is not a valid email."),
        password:z.string(),

    })).mutation(async({ ctx ,input}) =>{
        const FoundUser = await ctx.db.user.findUnique({where:{email:input.email}})
        if(!FoundUser){return {error:"user Does not exist"}}
        const CheckPassword = await bcrypt.compare(input.password ,FoundUser.password)
        if(!CheckPassword){return{error:"user Does not exist"}}
        return{input}
    })
 
});

Upvotes: 1

Views: 171

Answers (0)

Related Questions