Search code examples
javascriptnode.jscookiesurlencode

Prevent url encode in response set cookie - nodejs


In my node application, I am trying to change my cookie value with the below code. But when I set some cookie values I see it modified in my response header of browser. Node code :

let nonEncodedString ='s%3A9Q8kumq4BgrHtJPM90ebhhl6OqChsxdp.x0uf93Hk5I03KWeF%2FFT3TM64riv3QAs'
res.cookie('connect.sid', nonEncodedString , { maxAge, httpOnly: true, overwrite: true });

But the header I get is

set-cookie: connect.sid=s%253A9Q8kumq4BgrHtJPM90ebhhl6OqChsxdp.x0uf93Hk5I03KWeF%252FFT3TM64riv3QAs; Max-Age=157680000; Path=/; Expires=Thu, 31 Jul 2025 11:28:35 GMT; HttpOnly

essentially s%3A9Q8kumq4BgrHtJPM90ebhhl6OqChsxdp.x0uf93Hk5I03KWeF%2FFT3TM64riv3QAs is changed to s%253A9Q8kumq4BgrHtJPM90ebhhl6OqChsxdp.x0uf93Hk5I03KWeF%252FFT3TM64riv3QAs. ie. '25' is being added.

I think it's happening because it is getting URL encoded. I don't want that to happen since its changing the value I am sending and I don't have control to parse it before the browser sets it in the cookie.


Solution

  • you should set an encode function:

      res.cookie('connect.sid', nonEncodedString,
        { maxAge,
          httpOnly: true,
          overwrite: true,
          encode: v => v
        })
    
    

    the default encode function is encodeURLComponent.