• Home
  • Overview
  • Layout
  • Data fetching
  • Static
  • Metadata
  • Preview
  • RSC
  • Server Actions
  • Intercepting Routes
  • API Routes
  • Fonts
  • SSR
  • Next.js Logo
    13

Server Actions

Server-only formClient formClient Optimistic


Server actions in server component

const Page = async () => {
  const cookie = cookies().get('user')?.value;
  const user = cookie && JSON.parse(cookie);
  const secret = process.env.SECRET_TOKEN;

  const register = async (formData: FormData) => {
    'use server';

    const name = formData.get('name');

    if (!name) return;

    cookies().set({
      name: 'user',
      value: JSON.stringify({ name }),
      httpOnly: true,
    });

    console.log(secret); // see network tab

    revalidatePath('/parallel/me');
  };

  const logout = async () => {
    'use server';

    cookies().set({ name: 'user', value: '', httpOnly: true });

    revalidatePath('/parallel/me');
  };

  if (!user?.name) {
    return (
      <div>
        <h2>Server actions in server component</h2>

        <form action={register}>
          <label>
            Enter your name:
            <input type="text" name={'name'} />
          </label>
          <button>Submit</button>
        </form>
      </div>
    );
  }

  return (
    <div>
      <h2>Server actions in server component</h2>

      <form action={logout}>
        <h3>Hello, {user.name}!</h3>
        <button>Logout</button>
      </form>
    </div>
  );
};