failing to compile when using cookies()
Answered
Cão da Serra de Aires posted this in #help-forum
Cão da Serra de AiresOP
Hello newbie here, i am trying to setup auth session using next js
I have this
form action
and then is action is used by signup form
what am i doing wrong?
cookies() api but the compilation is failing with the error in the first screenshot. I have this
createSession() function that is used in the signup form action. // /lib/configs/session.ts
"server only"
export async function createSession(payload: SessionPayloadType) {
const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000); // 7 days
const session = await encryptToken(payload);
const cookieStore = await cookies();
cookieStore.set("session", session, {
httpOnly: true,
secure: true,
expires: expiresAt,
sameSite: "lax",
path: "/",
});
}form action
// /lib/actions/signupAction.ts
/**
*
* @param _formState - state of the form required for React 'useAction' hook
* @param formData - the form field values
* @returns
*/
export async function signupAction(
_formState: FormState,
formData: FormData,
): Promise<FormState> {
const validationResults = validateSignup(formData);
if (!validationResults.success) {
return new FormState(
"failure",
"Form validations failed.",
flattenError(validationResults.error).fieldErrors,
);
}
if (await isEmailAVailable(validationResults.data.email)) {
return new FormState("failure", "Email already exists.");
}
const user = await createUser(validationResults.data);
createSession({ id: user.id, role: user.role });
// no error
return new FormState("success", "Account created successfully.");
}and then is action is used by signup form
"use client"
// /components/forms/SignupForm.tsx
const initialFormState = new FormState();
export default function SignupForm({
className = "",
}: Readonly<SignupFormProps>): ReactElement {
const [state, action, pending] = useActionState(
signupAction,
initialFormState,
);
return (
<form action={action} className={`space-y-4 ${className}`}>
</form>
)
}what am i doing wrong?
4 Replies
Pacific sand lance
mark signupAction with "use server" directive
Answer
@Pacific sand lance mark signupAction with "use server" directive
Cão da Serra de AiresOP
Thanks 🙏 works now. I thought actions are server side by default 🤔
@Cão da Serra de Aires Thanks 🙏 works now. I thought actions are server side by default 🤔
Pacific sand lance
they
become server actions when you mark them using "use server" directive, otherwise it's just code@Pacific sand lance they `become` server actions when you mark them using "use server" directive, otherwise it's just code
Cão da Serra de AiresOP
I see .. thanks