Cookie Parser
Written By: Avinash Malhotra
Updated on
ExpressJS Cookie Parser?
Cookie Parser is a middleware of Node JS used to get cookie data. To get Cookie data in ExpressJS, req.cookies
property is used. req.cookies is an object that contains cookies sent by request in JSON after parsing.
Cookie Parser can get both unsigned and signed cookies.
Install Cookie Parser
npm i cookie-parser
Cookie API
After installing Cookie Parser, first include the module in main app. Then the app.use is used to call module.
req.cookies property is used to get cookie data in JSON. If there is no cookie, it will return {}. But if there is cookie, we will get the Cookie Data in JSON using req.cookies. See example below.
const express=require('express');
const app=express();
const cookieparser=require('cookie-parser');
app.use(cookieparser());
app.get("/",(req,res)=>{
res.status(200).send(req.cookies);
})
app.listen(3000,()=>{
console.log("server running")
})
Signed Cookie
cookie-parser can also parse Signed Cookies. req.signedCookies property is used to get Signed Cookie data in JSON.
Create Signed Cookie
const express=require('express');
const app=express();
const cookieparser=require('cookie-parser');
app.use(cookieparser('secret'));
app.get("/",(req,res)=>{
res.cookie("name","value",{signed:true});
res.status(200).send(req.signedCookies);
});
app.listen(3000,()=>{
console.log("server running")
});
Read Signed Cookie
const express=require('express');
const app=express();
const cookieparser=require('cookie-parser');
app.use(cookieparser('secret'));
app.get("/",(req,res)=>{
res.status(200).send(req.signedCookies);
})
app.listen(3000,()=>{
console.log("server running")
});
Set and Read Cookie
In this example, we are going to Set and Read Cookies using cookie parser.
const express=require('express');
const app=express();
const cookieparser=require('cookie-parser');
app.use(cookieparser());
app.get("/setcookie",(req,res)=>{
res.cookie("name","avinash", {maxAge:86400, httpOnly: true});
return res.send('Cookie has been set');
});
app.get("/getcookie",(req,res)=>{
const name=req.cookies.name;
if(name){
return res.send(name)
}
else{
return res.send("no cookies found");
}
})
app.listen(3000,()=>{
console.log("server running")
})