gndy Br
gndy Br

Reputation: 121

Why doesn't use server work in Next.js 13.4?

I wrote a function by declaring use server with code like this,

Cookies can only be modified in a Server Action or Route Handler. Read more: https://nextjs.org/docs/app/api-reference/functions/cookies#cookiessetname-value-options

I keep getting this error.

What could be the reason?

import { cookies } from "next/dist/client/components/headers";

type SearchParams = {
  searchParams: {
    code: string;
  };
};

export default async function EmailLoginPage({ searchParams }: SearchParams) {
  await testCookie();

  async function testCookie() {
    "use server";
    cookies().set("test", "test");
  }

  return <></>;
}

Upvotes: 1

Views: 950

Answers (1)

Ethan
Ethan

Reputation: 1664

Thanks, but It occurs same problem. Error: Cookies can only be modified in a Server Action or Route Handler.

There are two things are going wrong here:

  1. You're importing cookies wrong.
  2. Server Actions can only be called using the action or formAction prop.

Here's the updated code:

import { cookies } from "next/headers";

type SearchParams = {
  searchParams: {
    code: string;
  };
};

export default async function EmailLoginPage({ searchParams }: SearchParams) {

  async function testCookie() {
    "use server";
    cookies().set("test", "test");
  }

  return (
    <form action={testCookie}>
      <input placeholder="email" name="email" type="text" autofocus required/>
      <input placeholder="password" name="password" type="password" required/>
      <button type="submit">Login</button>
    </form>
  );
}

Read more about server actions.

Upvotes: 2

Related Questions