Installing cookie-parser
Node + Express is a powerful combination. It allows for setting up a quick shorthand for listening for paths and responding in easy ways to requests. However, as it comes to cookies, it does not contain built-in functionality for accessing them within the headers of a request or response.
Enter cookie-parser.
In an existing Express project, it can be installed through the standard installation method of “npm install cookie-parser”.
Using Middleware
“cookie-parser” is Express middleware. It is enabled for all routes through using the App.use() function.
Within a common structure, it would be used before any other routes.
const Express = require('express');
const App = Express();
const port = 80;
const CookieParser = require('cookie-parser');
App.use(CookieParser());
Sending Cookies
Sending cookies back to a client is as easy as using the existing Response object. Using res.cookie(), a name-value pair (and optional expiration time) can be sent back to the client.
Within the request-response cycle, this can be used within the callback function to a Express route:
const Express = require('express');
const App = Express();
const port = 80;
const CookieParser = require('cookie-parser');
App.use(CookieParser());
App.get("/send", (req, res) => {
res.cookie("loggedin", "true");
res.send("Cookie sent!");
});
Reading Cookies
With the “cookie-parser” package installed, the Request object will have a new object: cookies. Any cookie name-value pairs will appear as properties when parsed as part of the Request object.
App.get("/read", (req, res) => {
let response = "Not logged in!";
if(req.cookies.loggedin == "true") {
response = "Yup! You are logged in!";
}
res.send(response);
});
Reviewing
Express has the built-in function <Response>.cookie(). It allows for setting name-value pairs for cookies.
With the “cookie-parser” package installed, there is an additional object cookies as part of the Request object. This can be checked for any properties from the parsed cookies passed to the server code.
Full Example:
const Express = require('express');
const App = Express();
const port = 80;
const CookieParser = require('cookie-parser');
App.use(CookieParser());
App.get("/send", (req, res) => {
res.cookie("loggedin", "true");
res.send("Cookie sent!");
});
App.get("/read", (req, res) => {
let response = "Not logged in!";
if(req.cookies.loggedin == "true") {
response = "Yup! You are logged in!";
}
res.send(response);
});
App.listen(port, () => {
console.log("Server running!");
});