Next.js Discord

Discord Forum

Storing Cookies in a Client Component Login Page

Unanswered
Brokenwind posted this in #help-forum
Open in Discord
Hello, so I'm using Next JS 14 with the App router and I was wondering if it's possible to have the login page in a client component then store the cookies with next/headers.

I can't do this directly and I'm getting this:

× You're importing a component that needs next/headers. That only works in a Server Component but one of its parents is marked with "use client", so it's a Client Component.

I've seen examples on how to store cookies but all of them seems to use Server Components for the login so the error doesn't appear. The reason I'm using client side is because I'm doing some validations with a hook. Thanks.

1 Reply

I decided to put "use server" in the function I am using cookies:

"use server"; import { cookies } from "next/headers"; import { endpoints } from "@/utils/endpoints"; export async function signIn(formData) { ...

Then from my client component, I can just use signIn normally.

const handleSubmit = async (event) => { const data = form.getValues(); try { signIn(data); } catch (error) { console.error(error); } };

I don't understand why it worked or if this is even a good idea.