How to create a cookie with Node JS and Express JS

Publication: 5 of March, 2020
Hello today we are going to create, request and send cookies with NodeJS, as many of you know a cookie is a small piece of information from a website store on your computer browser.
So I´m going to use Brackets as a code editor, I created a directory with the name of cookies in my computer and inside that directory a file with the name server.js and index.html, and using the command line to initialize npm and install in this case express and cookie parser we go to the creating the code inside server.js.
Inside the file server.js the following code was written.

const express = require("express");

const cookieParser = require("cookie-parser");

const app = express();

app.use(cookieParser());

As you can see in the code above was set up expres and the file of cookie parser was imported, after this we create the normal root directory like this.

app.get("/", function(req, res) {

   res.sendFile(__dirname + "/index.html");

});

app.listen(3000, function(req, res) {

    console.log("App listening in port 3000");

});

And after this we go ahead create the cookie and we are going to send the data in JSON format that we are going to send to the browser, so before of the main route we write the variable in JSON format and inside of the main route we write res.cookie, we going to write the following.

var users = { 

   name : "Luis", 

    Age : "20"

} 

 res.cookie("info", users );

As you can see I created a variable with the name of users and the with res.cookie we send the cookie and the string inside the quotes is the name of the cookie, that you can see in your browser, now after this, we create another route to test the cookie just after the main route like this.

app.get("/users", function(req, res) {

   res.send(req.cookies);

});

As you see , I sent the information of the cookie, and I get that information with req.cookies now if you have several cookies you can specify the name like this req.cookies.info, now with the code looking like this.

const express = require("express");

const cookieParser = require("cookie-parser");

const app = express();

app.use(cookieParser());

var users = { 

   name : "Luis", 

    Age : "20"

} 

app.get("/", function(req, res) {

    res.cookie("info", users );

    res.sendFile(__dirname + "/index.html");

});

app.get("/users", function(req, res) {

    res.send(req.cookies);

});

app.listen(3000, function(req, res) {

    console.log("App listening in port 3000");

});

Now when we run the app and when we go to the route /users we can get the information of the cookie that we set up at the begging, hope you like see you in the next one.

Copyright Luis Gonzalez 2021