Ahmed
Ahmed

Reputation: 1359

Storing an array in a cookie in nodeJS

I was wondering if it is possible to store an array in a cookie in nodeJS. For example I can set a cookie using the following code res.cookie('Name', "John", { maxAge: 900000});. My question is it possible to store and array of names instead of one name. For example res.cookie('Name', ["john","mark"], { maxAge: 900000});

Upvotes: 0

Views: 778

Answers (1)

Heisenbug
Heisenbug

Reputation: 223

No, you can't. But you can do something better: store the array in a Json Web Token (JWT).

A JWT is a token in which you can store information in JSON format. You can do it this way:

var jwt = require('jsonwebtoken');
var token = jwt.sign({ Name: ["john","mark"] }, 'YOUR-SECRET-KEY');

Now you have your array of names inside the token variable (and encrypted with your secret key). You can put this token in a cookie:

res.cookie('jwt', token, { maxAge: 900000});

And the user can't edit the cookie information without knowing the secret key you used on the server to create the token.

When you want to decode the information from the token on the user's cookies, you just have to do:

var decoded = jwt.verify(req.cookies.jwt, 'YOUR-SECRET-KEY');
console.log(decoded.Name)
//output: ["john","mark"]

Here is the npm package. Surely you can just encrypt your cookies with any other method, but the pro point of using JWT is that you can store the information like a simple JSON. And then send the token on the cookie.

Upvotes: 2

Related Questions