Next.js Discord

Discord Forum

Store HTTP Only cookies

Unanswered
Tramp ant posted this in #help-forum
Open in Discord
Tramp antOP
How can I store HTTP Only cookies on both client and server side components I seem to be stuggling to access them

import { cookies } from 'next/headers'

async function UserPage() {

  const cookieStore = cookies();
  cookieStore.set('session', 'ABCD', {expires: 1 / 24, httpOnly: true})

  return (
    <div>
    </div>
  );
}

export default UserPage;


Errors
Error: 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

12 Replies

well use a server action or route handler, called from a client component when loading the page with "useEffect" for instance
What you are doing is weird anyway you probably don't want to set a user session as a side effect to opening a user page
Tramp antOP
Yeah it was just a sample
I have an API request and once that is done I want to set the HTTPOnly cookie but I can't seem to set it at all
"use server"

import { cookies } from "next/headers";
import { NextResponse } from "next/server";

export async function authenticateSessionToken() {
  const AUTHENTICATION_REQUEST = "/api/v1/authenticate";

  const options: RequestInit = {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json'
    },
  };

  const cookieStore = cookies()
  cookieStore.set({
    name: 'sessionToken',
    value: 'SAMPLE39842094',
    httpOnly: true,
    path: '/',
  })

  try {
    const response = await fetch(AUTHENTICATION_REQUEST, options);

    if (!response.ok) {
      throw new Error('Network response was not ok');
    }

    const data = await response.json();
    return NextResponse.json({ data: data }, { status: 200 });
  } catch (error) {
    console.error('Error during authentication:', error);
    return NextResponse.error();
  }
}
Which gets called by
<Button onClick={() => authenticateSessionToken()}>Authenticate</Button>
but errors

⨯ Internal error: Error: Only plain objects, and a few built-ins, can be passed to Client Components from Server Components. Classes or null prototypes are not supported.
at eF
Of course the value in this case is random but it would come from the response
Any ideas @Eric Burel ?
You are showing an unrelated issue compared to your first post, but anyway you seem to have a different error that you need to fix
I think you are rendering Button from a server component while trying to pass it an onClick callback
Tramp antOP
Dw I fixed it :)