saadq saadq - 10 months ago 38
Node.js Question

Setting a cookie's value to a template literal?

I'm creating a template literal like so:

const someVar = 'hello'

const str = `
Some random
multiline string with string interpolation: ${someVar}

And then in my Koa app, I'm doing:

this.cookies.set('str', str)

Apparently it doesn't like the multiline string, as it gives this error:

TypeError: argument value is invalid

Is there any way around this? Keeping the whitespace format is pretty necessary in my case.

Answer Source

This has nothing to do with the template literal; by the time you're getting the error, you have a string with newlines in it. You can't have newlines in a cookie value.

Probably the best thing to preserve those newlines is to use JSON:

this.cookies.set('str', JSON.stringify(str));

Of course, you'll need to JSON.parse it when using it.

You don't have to use JSON, of course; you could use URI-encoding:

this.cookies.set('str', encodeURIComponent(str));

...and then decode it with decodeURIComponent (or the equivalent for whatever's consuming the string).