Next.js Discord

Discord Forum

Session not updated immediately after sign in credentials with next auth

Unanswered
Rex posted this in #help-forum
Open in Discord
RexOP
Hi, I creaed this function to sign-in with credentials, when I am successfully signed in, it redirects me to the home page, but my session is not automaticly updated, I still have the button Sign In instead of My Account but when I refresh the page, everything is good

export const signInWithCredentials = async (
  state: AuthResponse,
  data: FormData
): Promise<AuthResponse> => {
  try {
    const result = signInSchema.safeParse({
      email: data.get("email"),
      password: data.get("password"),
    });

    if (!result.success)
      return {
        success: false,
        errors: result.error.formErrors.fieldErrors,
      };

    const { email, password } = result.data;

    await signIn("credentials", { email, password });

    return {
      success: true,
    };
  } catch (error) {
    let errorMsg = "";
    if (error instanceof Error && error.message === "NEXT_REDIRECT") {
      redirect("/");
    } else if (error instanceof AuthError) {
      errorMsg = error.message;
    } else {
      errorMsg = (error as any).message;
    }
    return { error: errorMsg, success: false };
  }
};

19 Replies

export const signInWithCredentials = async (
  state: AuthResponse,
  data: FormData
): Promise<AuthResponse> => {
  try {
    const result = signInSchema.safeParse({
      email: data.get("email"),
      password: data.get("password"),
    });

    if (!result.success)
      return {
        success: false,
        errors: result.error.formErrors.fieldErrors,
      };

    const { email, password } = result.data;

    await signIn("credentials", { email, password });

    revalidatePath("/", "layout");

    return {
      success: true,
    };
  } catch (error) {
    let errorMsg = "";
    if (error instanceof Error && error.message === "NEXT_REDIRECT") {
      revalidatePath("/", "layout");
      redirect("/");
    } else if (error instanceof AuthError) {
      errorMsg = error.message;
    } else {
      errorMsg = (error as any).message;
    }
    return { error: errorMsg, success: false };
  }
};
its a server action
and this is my sign-in page where i call it

const SignIn = () => {
  const [state, action] = useActionState(signInWithCredentials, {});
  const router = useRouter();

  // useEffect(() => {
  //   if (state.success) {
  //     router.push("/");
  //   }
  // }, [state.success]);
  return (
    <div className="min-h-screen flex items-center px-4 justify-center">
      <AuthForm
        error={state.error}
        btnLabel="Prijavi se"
        title="Prijavite se"
        footerElements={[
          {
            label: "Nemate profil?",
            linkText: "Registruj se",
            link: "/sign-up",
          },
          {
            label: "Zaboravili ste lozinku?",
            linkText: "Resetujte je",
            link: "/reset-password",
          },
        ]}
        action={action}
      >
        <input
          placeholder="me@email.com"
          type="text"
          className="input-field"
          name="email"
        />
        {state.errors?.email && (
          <span className="text-red-500">{state.errors.email.join(", ")}</span>
        )}
        <input
          placeholder="********"
          type="password"
          className="input-field"
          name="password"
        />
        {state.errors?.password && (
          <span className="text-red-500">
            {state.errors.password.join(", ")}
          </span>
        )}
      </AuthForm>
    </div>
  );
};

export default SignIn;
@Rex yes
that's the problem. The signIn function is a clientside function does that all the things you need already. You server function (your authConfig already does the validation and that for you. You can also do your own things in there (in the callbacks), so call your signIn function clientside and all the errors that you experience now and maybe in the future, will be solved
RexOP
Okay
But why is the session not updated immediately
But I need to refresh my page so the UI gets updated
I mean there is a session
I can not acces pages like sign in when I am successfully signed in
But in my navbar I check if there is a session if it exists i have a link button My Account it its doesnt exists i have Sign In button
And even when I successfully sign in i am gettin redirected to my home page
But i still have the navbar which is not updated
Until i refresh my page
@Rex But I need to refresh my page so the UI gets updated
when using server actions, revalidatePath and an API route at the same time it can get pretty confusing especially, when I am not part of your code. That's why I also can't tell you the exact reason. When you are using it without a server action, it will work fine
RexOP
I fixed it on my own
@Rex I fixed it on my own
Please provide your solution as others are interested in your solution as well
@Rex?