Anyone using auth.api in a server action with useActionState?

I'm having trouble getting the session to update, have followed the docs to use the nextCookies() plugin but the example server action doesn't return anything so I'm not really sure how that's meant to work. Maybe I'm holding it wrong, but my current setup is using a server action with useActionState on my sign in form so that I can display errors. The server action calls auth.api.signInEmail and redirects on success, or returns errors to the action state for me to display in the form. My UI doesn't update to replace the "Sign Up"/"Sign In" buttons with the "Sign Out" button as I would expect, so I suspect the cookies aren't being set?
Next.js integration | Better Auth
Integrate Better Auth with Next.js.
1 Reply
xephyr
xephyrOP6d ago
FWIW here's the action:
"use server";

import { APIError } from "better-auth/api";
import { redirect } from "next/navigation";
import { parseWithZod } from "@conform-to/zod";
import { auth } from "@/lib/auth";
import { signInEmailSchema } from "./schema";

export const signInEmail = async (prevState: unknown, formData: FormData) => {
const submission = parseWithZod(formData, { schema: signInEmailSchema });
if (submission.status !== "success") return submission.reply();

try {
await auth.api.signInEmail({
body: submission.value,
});
} catch (error) {
if (error instanceof APIError) {
return submission.reply({
formErrors: [error.message],
});
}
}

redirect("/");
};
"use server";

import { APIError } from "better-auth/api";
import { redirect } from "next/navigation";
import { parseWithZod } from "@conform-to/zod";
import { auth } from "@/lib/auth";
import { signInEmailSchema } from "./schema";

export const signInEmail = async (prevState: unknown, formData: FormData) => {
const submission = parseWithZod(formData, { schema: signInEmailSchema });
if (submission.status !== "success") return submission.reply();

try {
await auth.api.signInEmail({
body: submission.value,
});
} catch (error) {
if (error instanceof APIError) {
return submission.reply({
formErrors: [error.message],
});
}
}

redirect("/");
};

Did you find this page helpful?