ExpressJS Cookies - ExpressJS

What are cookies? What are their uses?

Cookies are simple, small files/data that are sent to client with a server request and stored on the client side. Every time the user loads the website back, this cookie is sent with the request. This helps us keep track of the users actions. There are numerous uses of HTTP Cookies like session management, personalization(Recommendation systems), user tracking etc

How to install cookie-parser

To use cookies with express, we need the cookie-parser middleware. To install it, use,
Now to use cookies with express, we'll require cookie-parser. cookieParser is a middleware which parses cookies attached to the client request object. To use it, we will require it in our index.js file and use it in the same way we use other middleware. We are going to use it on every route. Use the following code to ensure both of these things happen:
cookie-parser parses Cookie header and populates req.cookies with an object keyed by the cookie names. To set a new cookie lets define a new route in your express app like:
To check if your cookie is set or not, just go to your browser, fire up the console, and enter:
You will get the output like(you may have more cookies set maybe due to extensions in your browser):
The browser also sends back cookies every time is queries the server. To view cookies from your server, on the server console in a route, add the following code to that route:
Next time you send a request to this route, you'll get the ouput:

How to add cookies with expiration time

Pass an object with property 'expire' set to the time when you want it to expire. For example,
Another way to set expiration time is using 'maxAge' property. Using this property, we can provide relative time instead of absolute time. An example of this method:

How to delete existing cookies

Use the clearCookie function. For example, if you need to clear a cookie named foo, use the following code:

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

ExpressJS Topics