Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node Express Response Cookie Value is Encoded

I'm trying to set a cookie on the response using Express, but it's encoding the value. I'm setting a value with an equals sign, but on the client, it's coming through as %3D.

Any advice?

Thanks!

like image 464
Danny Ackerman Avatar asked Feb 09 '16 17:02

Danny Ackerman


People also ask

Is a cookie value encoded?

The commonly held belief is that cookie values must be URL-encoded, but this is a fallacy even though it is the de facto implementation. The original specification indicates that only three types of characters must be encoded: semicolon, comma, and white space.

How do I read cookie data in node JS?

We can check cookies by visiting localhost:3000/setcookie. This will show a message as cookies are added. We can check the cookies by visiting localhost:3000/getcookie. Now we can see that our cookies are added to the cookies object as shown above.

What encoding type is used for cookie value?

55951 – HTML5 specifies UTF-8 encoding for cookie values.

How do you use cookies in Express?

Now to use cookies with Express, we will require the cookie-parser. cookie-parser is a middleware which parses cookies attached to the client request object. To use it, we will require it in our index. js file; this can be used the same way as we use other middleware.


3 Answers

Argh, I found it!

http://expressjs.com/en/api.html#res.cookie

encode option needs to be set to String.

like image 87
Danny Ackerman Avatar answered Oct 02 '22 07:10

Danny Ackerman


Express req.cookie method accepts the third param as config, you can set the encoding method for cookie value in it. By default it uses encodeURLComponent, so to prevent this, you can define a custom function to override it:

const myCookieEncode = function (val) {
    return val;
};

...

res.cookie(cookieName, cookieValue, { encode: myCookieEncode })
like image 29
merlin.ye Avatar answered Oct 02 '22 08:10

merlin.ye


Actually, it's by default encoding into 'HTML URL encoding' So in URL every special character have a code and '=' has a code '%3D'. So it is simply converting into that code

You can read more from here

like image 21
LAV VISHWAKARMA Avatar answered Oct 02 '22 08:10

LAV VISHWAKARMA