HTTP Cookies in Node - Js
HTTP Cookies in Node - Js
js
geeksforgeeks.org/http-cookies-in-node-js
August 9, 2018
Cookies are small data that are stored on a client side and sent to the client along with server requests. Cookies have various
functionality, they can be used for maintaining sessions and adding user-specific features in your web app. For this, we will use cookie-
parser module of npm which provides middleware for parsing of cookies.
First set your directory of the command prompt to root folder of the project and run the following command:
npm init
This will ask you details about your app and finally will create a package.json file.
After that run the following command and it will install the required module and add them in your package.json file
});
app.listen(3000, (err)=>{
if (err)
throw err;
});
node app.js
It will start our server on port 3000 and if go to the url: localhost:3000, we will get a page showing the message :
welcome to express app
So until now we have successfully set up our express app now let’s start with cookies.
For cookies first, we need to import the module in our app.js file and use it like other middlewares.
Let’s say we have a user and we want to add that user data in the cookie then we have to add that cookie to the response using the
following code :
res.cookie(name_of_cookie, value_of_cookie);
app.use(cookieParser());
});
let users = {
name : "Ritik" ,
Age : "18"
});
res.send(req.cookies);
});
app.listen(3000, (err)=>{
if (err)
throw err;
});
So if we restart our server and make a get request to the route: localhost:3000/getuser before setting the cookies it is as follows :
After making a request to localhost:3000/setuser it will add user data to cookie and gives output as follows :
Now if we again make a request to localhost:3000/getuser as this route is iterating user data from cookies using req.cookies so output
will be as follows :
If we have multiple objects pushed in cookies then we can access specific cookie using req.cookie.cookie_name .
res.clearCookie(cookieName);
Now let us make a logout route which will destroy user data from the cookie. Now our app.js looks like :
app.use(cookieParser());
});
name : "Ritik" ,
Age : "18"
});
res.send(req.cookies);
});
});
app.listen(3000, (err)=>{
if (err)
throw err;
});
For destroying the cookie make get request to following link: user logged out[/caption]
To check whether cookies are destroyed or not make a get request to localhost:3000/getuserand you will get an empty user cookie
object.
This is about basic use of HTTP cookies using cookie-parser middleware. Cookies can be used in many ways like maintaining sessions
and providing each user a different view of the website based on their previous transactions on the website.