maticzav/nookies

Can't set multiple cookies on server side

Closed this issue · 6 comments

Hi there!

Description
I'm trying to set multiple different cookies on the server side using setCookie but it's not working as expected.
In the example below it's just simply throwing errors.
I have another application where I use setCookie multiple times in another helper class and even though it works in as it sets a value, the options that get passed to the cookie dependency of nookies get applied to only one of the calls. For the other calls the value does not get encoded using encodeURIComponent for instance.

Am I doing something wrong here?
How is it possible to set multiple cookies during one request?

To Reproduce

  1. Create a new app: npx create-next-app nookies-issue
  2. Install nookies npm install --save nookies
  3. Copy following code into pages/index.js:
import { Component } from 'react'
import Head from 'next/head'
import { setCookie } from 'nookies'

const foo =
  'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) Ap…ML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'
const bar =
  'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) Ap…ML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'

export default class MyClass extends Component {
  static getInitialProps(ctx) {
    setCookie(ctx, 'foo', foo, {})
    setCookie(ctx, 'bar', bar, {})

    return {}
  }

  render() {
    return <h1>Home</h1>
  }
}
  1. Start server and visit localhost:3000

I'm having a similar issue.

Thank you for opening the issue. It seems like the problem comes from the cookie values - not the number of cookies you are setting. I am investigating the issue. Hopefully, I can sort this out soon.

🎉 This issue has been resolved in version 2.5.1 🎉

The release is available on:

Your semantic-release bot 📦🚀

Hi @maticzav ,
after updating the package the example from above is now working, thank you.
Unfortunately I cannot quite figure out what exactly you changed in your commit because there is so much happening in that commit.

I have another question though - might be different issue?
If you take the exact same example above and replace

    setCookie(ctx, 'foo', foo)
    setCookie(ctx, 'bar', bar)

with

    setCookie(ctx, 'foo', foo)
    setCookie(ctx, 'bar', bar)

You get the following error:
Screenshot 2021-01-21 at 10 10 09

Is this to be expected that you always have to pass in an empty options object?

No, of course, that shouldn't be the case. I just pushed the fix.

The problem was that we are cleverly checking which cookies should be set. In the process, we reencode cookies, and we also used to decode their values. That caused problems.

const parsedCookies = setCookieParser.parse(cookies, {
   decodeValues: false,
})

Can confirm it's working now as expected.
Thanks for the quick response and fix!