Does ``await cookie()`` return empty Cookie Store in different server-side function context?
Answered
Little Shearwater posted this in #help-forum
Little ShearwaterOP
I've been debugging this issue where
CookieStore.set( ) and CookieStore.get( ) works differently and sometime return undefined (for getter). And I recently found out that it works correctly only in original request (before calling the utility function to set the cookie).Answered by joulev
when you call
utilityCookie, if you add an await before it does it work?9 Replies
Little ShearwaterOP
## ✅ Setting cookie in API Router (Working Method)
## ❌ Setting cookie in utility function (called FROM API Router) (Not working method)
export async function ServerApi() {
const cookieStore = await cookies(); // Get the cookie store.
cookieStore.set(...) // Successfully set
}
...
export async function AnotherServerApi() {
const cookieStore = await cookies(); // Get the cookie store.
const cookie = cookieStore.get("MyCookie"); // Get the cookie.
console.log(cookie); // Successfully logs a defined cookie.
}## ❌ Setting cookie in utility function (called FROM API Router) (Not working method)
export async function ServerApi(request: Request) {
utilityCookie(); // Instead of directly setting cookie, we call the function.
}
...
export async function utilityCookie() {
const cookieStore = await cookies(); // Get the cookie store.
cookieStore.set(...) // Set the cookie
console.log(cookieStore.get("MyCookie")); // Successfuly log a defined cookie.
}
...
export async function AnotherServerApi() {
const cookieStore = await cookies(); // Get the cookie store.
const cookie = cookieStore.get("MyCookie"); // Get the cookie.
console.log(cookie); // Undefined cookie.
}when you call
utilityCookie, if you add an await before it does it work?Answer
@joulev when you call `utilityCookie`, if you add an `await` before it does it work?
Little ShearwaterOP
I'll try and see.
@joulev when you call `utilityCookie`, if you add an `await` before it does it work?
Little ShearwaterOP
Uhhhh, I'm embarassed to say but this worked 😭
I am not sure how this async issue can prevent it from being set.
I am not sure how this async issue can prevent it from being set.
my guess is that the whole thing terminates before the cookie.set call has a chance to run, as things did not
await for that cookie.set before terminating@joulev my guess is that the whole thing terminates before the cookie.set call has a chance to run, as things did not `await` for that cookie.set before terminating
Little ShearwaterOP
Oh you're actually right! It turns out the request did indeed end before the cookie.set could be called.
just checked that out.
Will be more careful when dealing with asynchronous matters
I appreciate your help! You may mark that as solution! 👍