Next.js Discord

Discord Forum

signIn function not returning JSON to server

Unanswered
Silver Fox posted this in #help-forum
Open in Discord
Avatar
Silver FoxOP
export async function POST(
  request: Request
) {
  const body = await request.json()
  console.log(JSON.stringify(body));

  const validatedFields = LoginSchema.safeParse(body)

  if (!validatedFields.success) {
    return Response.json({ error: "Invalid credentials!" }, { status: 500 })
  }
  console.log("test");

  const { email, password } = validatedFields.data
  try {
    await signIn("credentials", {
      email,
      password,
      redirectTo: DEFAULT_LOGIN_REDIRECT
    })
    // return Response.json({ success: true, message: "Login successful!" });
  } catch (error) {


    if (error instanceof AuthError) {
      switch (error.type) {
        case "CredentialsSignin":
          return Response.json({ error: "Invalid credentials!" }, { status: 500 })
        default:
          return Response.json({ error: "Something went wrong!" }, { status: 500 })
      }
    }
    throw error
  }

}

this is the app/api/login
and this is how i am calling it
function onSubmit(values: z.infer<typeof LoginSchema>) {
    startTransition(async () => {
      const response = await fetch("/api/login", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(values),
      });
      console.log(response)
      const data = await response.json()
      if (response.ok && data.success) {
        setStatus("success")
        setStatusMessage(data.success)
      } else {
        setStatus("error")
        setStatusMessage(data.error)
      }
    });
  }

i get this error
syntaxerror: Unexpected token '<', "<!DOCTYPE "... is not valid JSON

10 Replies

Avatar
Silver FoxOP
am i using the signIn function correctly?
Avatar
Toyger
you need check what response you get from /api/login in devtools network tab either with postman/insomnia/etc...
because it's definetely not json in response
Avatar
Silver FoxOP
it returns the HTML code of the page where it is supposed to redirect to
Image
Image
after it redirects the app continues to work fine unless i try to login in again or the session expires
Avatar
Toyger
didn't notice signin at first, signIn is client component feature, you can't use it in api. you neen to login user through client not through your api.
Avatar
Silver FoxOP
makes sense but how does it work with server actions then 🤔
export const login = async (
.....
.....
  try {
      await signIn("credentials", {
        email,
        password,
        redirectTo: callbackUrl || DEFAULT_LOGIN_REDIRECT,
      })
    } catch (error) {
      if (error instanceof AuthError) {
        switch (error.type) {
          case "CredentialsSignin":
            return { error: "Invalid credentials!" }
          default:
            return { error: "Something went wrong!" }
        }
      }
  
      throw error;
  }
};

this works if I use server actions
and then on the client side
    startTransition(() => {
      login(values, callbackUrl)
        .then((data) => {
          if (data?.error) {
            form.reset();
            setError(data.error);
          }
        })
        .catch(() => setError("Something went wrong"));

  };
Avatar
Toyger
not sure why it working, but if it working then why you are not using server actions?
Avatar
Silver FoxOP
just figured that out now, i will be using server actions for the login, still wierd
anyways thanks for the help :blob_wave: