Next.js Discord

Discord Forum

NEXT JS - SET COOKIES SERVER SIDE

Answered
Transvaal lion posted this in #help-forum
Open in Discord
Transvaal lionOP
i have a component that i use export default async function Component(){}. I am making a requst to my backend and then upon successful response, i wnat to store something in cookies, but i get this error:
 "message": [
        "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"
      ],
      "level": "error",
      "timestamp": 1709567209340
    },
    {
      "message": [
        "Error: An error occurred in the Server Components render. The specific message is omitted in production builds to avoid leaking sensitive details. A digest property is included on this error instance which may provide additional details about the nature of the error."
      ],
. Do i have to move all my code to somewhere /api/path-to-component? Here is my code:
export default async function ShopifyPage({
  searchParams,
}: {
  searchParams: { shop?: string };
}) {
  const { shop } = searchParams;

  if (!!shop) {
    const url = `${process.env.NEXT_PUBLIC_API_URL}/shopify/auth?shop=${shop}`;
    console.log(url);
    const response = await fetch(url, {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
      },
    });

    if (response.status === 200) {
      const json: AuthResponse = await response.json();
      const { name, expires, value } = json.cookie;

      // Convert the 'expires' string to a Date object
      const expiresDate = new Date(expires);

      // Set the cookie with the extracted data
      cookies().set(name, value, {
        expires: expiresDate,
        httpOnly: true,
        secure: true,
      });

      redirect(json.auth_url);
    }
  }
Answered by joulev
You cannot set cookies in server components. You have to use middleware for this purpose
View full answer

13 Replies

@Transvaal lion i have a component that i use export default async function Component(){}. I am making a requst to my backend and then upon successful response, i wnat to store something in cookies, but i get this error: "message": [ "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" ], "level": "error", "timestamp": 1709567209340 }, { "message": [ "Error: An error occurred in the Server Components render. The specific message is omitted in production builds to avoid leaking sensitive details. A digest property is included on this error instance which may provide additional details about the nature of the error." ],. Do i have to move all my code to somewhere `/api/path-to-component`? Here is my code: export default async function ShopifyPage({ searchParams, }: { searchParams: { shop?: string }; }) { const { shop } = searchParams; if (!!shop) { const url = `${process.env.NEXT_PUBLIC_API_URL}/shopify/auth?shop=${shop}`; console.log(url); const response = await fetch(url, { method: "GET", headers: { "Content-Type": "application/json", }, }); if (response.status === 200) { const json: AuthResponse = await response.json(); const { name, expires, value } = json.cookie; // Convert the 'expires' string to a Date object const expiresDate = new Date(expires); // Set the cookie with the extracted data cookies().set(name, value, { expires: expiresDate, httpOnly: true, secure: true, }); redirect(json.auth_url); } }
You cannot set cookies in server components. You have to use middleware for this purpose
Answer
@joulev You cannot set cookies in server components. You have to use middleware for this purpose
Transvaal lionOP
but i am only setting cookies after a successful json response, how will middleware play a role in this?
Run the request in the middleware file
You cannot set cookies in server components, that’s a fundamental limitation, you cannot do anything to work around it
@joulev You cannot set cookies in server components, that’s a fundamental limitation, you cannot do anything to work around it
Transvaal lionOP
the error message leads to docs that say to use a server action or route handler. i cant just move all my code to an api file?
@Transvaal lion the error message leads to docs that say to use a server action or route handler. i cant just move all my code to an api file?
If you do use server actions/route handlers, they do work correctly but you need to call them from the client (on button click or by useEffect, for example). If you simply import and run the server action inside the server component it wont work either. That’s a limitation of server components
You’re welcome
@joulev You’re welcome
Transvaal lionOP
Hey, I'm using next auth js for oauth, and i implemented oauth that is not in their library, shopify, i wanted to know how i could update my session.accessToken from an api route handler. Any idea? lmk if you need more info
@Transvaal lion Hey, I'm using next auth js for oauth, and i implemented oauth that is not in their library, shopify, i wanted to know how i could update my session.accessToken from an api route handler. Any idea? lmk if you need more info
i don't use shopify so i can't comment. i recommend you make a new post with the details so someone familiar with shopify and next-auth can take a look
Transvaal lionOP
well i dont need help with the shopify part, i basicially generated an access token on my backend. but now im just trying to store it in session:
Transvaal lionOP
@joulev
As I said, I cannot offer assistance here. I recommend making a new post with relevant details