skip to Main Content

I am trying to develop a login system in my NextJS app. But I am keep getting the error –

AxiosError {message: ‘Request failed with status code 400’, name: ‘AxiosError’, code: ‘ERR_BAD_REQUEST’, config: {…}, request:
XMLHttpRequest, …}

Here, I am providing the neccessary code snippets related to this topic.

Client Side(RegisterPage) –

const [authState, setAuthState] = useState({
    name: "",
    email: "",
    password: "",
    password_confirmation: "",
  });

  const [loading, setLoading] = useState<boolean>(false);
  const [errors, setErrors] = useState<registerErrorType>({});

  const submitForm = () => {
    setLoading(true);
    axios
      .post("http://localhost:3000/api/auth/register", authState)
      .then((res) => {
        setLoading(false);
        const response = res?.data;
        // debugger;
        if (response?.status == 200) {
          console.log("User created successfully");
        } else if (response?.status == 400) {
          setErrors(response?.errors);
        }
      })
      .catch((error: any) => {
        console.error("Axios request error:", error);
        setLoading(false);
      });
  };

Server Side(RegisterPage) –

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const validator = vine.compile(registerSchema);
    const output = await validator.validate(body);
    validator.errorReporter = () => new ErrorReporter();
    // check if email already existes
    const user = await User.findOne({ email: output.email });
    if (user) {
      return NextResponse.json(
        {
          status: 400,
          errors: {
            email: "Email is already exists",
          },
        },
        { status: 200 }
      );
    } else {
      // Encrypt the password
      const salt = bcrypt.genSaltSync(10);
      output.password = bcrypt.hashSync(output.password, salt);
      await User.create(output);
      return NextResponse.json(
        { status: 200, message: "User created successfully" },
        { status: 200 }
      );
    }
  } catch (error) {
    if (error instanceof errors.E_VALIDATION_ERROR) {
      return NextResponse.json(
        { status: 400, errors: error.messages },
        { status: 400 }
      );
    }
  }
}

Thank you 🙂

2

Answers


  1. Could it be that your authState input is simply wrong and being catched and throws a validation error? Can you do a console.log() or put a breakpoint on the authState body when it is sent to the server?

    Also I would start by using a more general try-catch, right now you are using a specific catch on an error but only throw on a validation error (which seems to be what this is about) but what if it wasn’t, then the error would be swallowed and your code will crash.

    Also, I know this doesn’t solve your specific problem in hand but in the grand scheme of things it might be worth considering going for a library like NextAuth or Auth0 to help you kick-start the authentication/authorisation work.

    Hope this at leasts gives you something to think about 🙂

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search