Category: Next.js, React and TypeScript

Next.js: cookies().set does not work in Server Component

Read this guide in Polish

Trying to set cookies directly when rendering the page returns the cookie limitation error. Reading and writing cookies have different rules; writing is allowed only in the appropriate context of the server response.

How to determine the source of the error

Check whether setter is called in page.tsx, Route Handler or Server Action.

Verify whether the cookie mutation occurs before sending the HTTP response.

What to do step by step

1. Transfer cookie writing to Server Action or Route Handler and leave the component to read the data.

2 . For the session, check the HttpOnly, Secure, SameSite attributes and path; run the test after clean login.

How to check the score

After a mutant request, the response contains the correct Set-Cookie header, and the new session is read correctly.

What to do

Do not save session secrets by the available JavaScript code to the client if they require HttpOnly protection.