amannn / next-intl

🌐 Internationalization (i18n) for Next.js
https://next-intl-docs.vercel.app
MIT License
2.58k stars 236 forks source link

Set cookies in getRequestConfig #1387

Closed Ronan-V closed 1 month ago

Ronan-V commented 1 month ago

Description

I need to update a cookie in getRequestConfig. Since this function is executed during the Server Components render pass, I assume that I should be able to call a Server Action which sets my cookie:

import { getRequestConfig } from "next-intl/server";
import { cookies } from "next/headers";

export default getRequestConfig(async () => {
const setCookie = async () => {
   "use server";
   cookies().set({
      name: "myCookie",
      value: "myValue",
   });
};
await setCookie();
return {...}

However, I get an error telling me that cookies can only be modified in... a Server Action ! Am I wrong somewhere ?

    at Proxy.callable (D:\Coding\Web\pro_cuult\node_modules\.pnpm\next@14.2.7_react-dom@18.3.1_react@18.3.1__react@18.3.1\node_modules\next\dist\compiled\next-server\app-page.runtime.dev.js:36:12959)
    at $$ACTION_0 (webpack-internal:///(rsc)/./i18n/request.ts:67:61)
    at eval (webpack-internal:///(rsc)/./i18n/request.ts:45:11)
    at eval (webpack-internal:///(rsc)/./node_modules/.pnpm/next-intl@3.20.0_next@14.2.7_react-dom@18.3.1_react@18.3.1__react@18.3.1__react@18.3.1/node_modules/next-intl/dist/esm/server/react-server/getConfig.js:10:783)```

### Verifications

- [X] I've verified that the problem I'm experiencing isn't covered in [the docs](https://next-intl-docs.vercel.app/).
- [X] I've searched for similar, existing issues on GitHub and [Stack Overflow](https://stackoverflow.com/search?q=next-intl).
- [X] I've compared my app to [a working example](https://next-intl-docs.vercel.app/examples) to look for differences.

### Mandatory reproduction URL

https://github.com/amannn/next-intl-bug-repro-app-router.git

### Reproduction description

Steps to reproduce:
1. Open `src/i18n/request.ts`
2. Add the Server Action to set a cookie:
```const setCookie = async () => {
   "use server";
   cookies().set({
      name: "myCookie",
      value: "myValue",
   });
};
await setCookie();
  1. See error: [Error]: Cookies can only be modified in a Server Action or Route Handler

Expected behaviour

Being able to call a Server Action to set a cookie in getRequestConfig.

amannn commented 1 month ago

Since this function is executed during the Server Components render pass, I assume that I should be able to call a Server Action which sets my cookie

Nope, during this phase you can not call a Server Action or set a cookie. You can instead set a cookie in the middleware though or alternatively in a Server Action you're calling from the client.

Ronan-V commented 1 month ago

My bad then. Thank you for the quick response !