Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

Guest cart issues - set cookie in custom GraphQL mutation

default discord avatar
revnelsonlast year
1 1

Main question: How can I set response headers from a custom GraphQL mutation resolve function?

Longer version: Hello! I'm making a Cart collection that can optionally be assigned to a user. Access checks will allow a user to access the cart assigned to them, and allow anyone to access a cart that they know the ID of and that hasn't been assigned to a user.

I'm making custom GraphQL queries and mutations, but I need a way to get the cart ID from the user, and I don't want this to be a frontend responsibility. Thus, I'd like to pass and read a cart cookie. Within the resolve function, I can readily read the cookies sent from the client, but can't figure out how to set a cookie.

For an example use-case: when a guest calls the addCartItem mutation, if no cart cookie is received I'd like to create a guest cart (no associated user) and set a cookie in the response header with a JWT token that contains the cart ID. I see that the context arg exists in the resolve function, but there doesn't seem to be a method for setting headers on the context.res object. Can anyone point me to a way to do this?

  • Selected Answer
    default discord avatar
    revnelsonlast year

    I could've sworn I had tried context.res.set('key', 'value') and got an error along the lines of set not existing or not being a function, but I've tried again and it seems to work just fine. Not sure if it was user error on my end, or the fact that between my initial post and now I've updated from v1.8.2 to v1.9.5. Regardless, the solution is to simply use context.res.set('key', 'value').

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.