0

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});

2
  • 1
    You can't store an array, but you can use JSON.stringify(array), be aware that the amount of data a cookie can contain is limited so don't store a large array in there. If you want to store larger amounts of data use localstorage or other type of session. Commented Nov 29, 2019 at 17:09
  • Thanks it worked like charm. I didn't know it was that easy :) Commented Nov 29, 2019 at 17:13

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.