

{"id":114748,"date":"2023-07-20T19:05:33","date_gmt":"2023-07-20T13:35:33","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=114748"},"modified":"2023-07-20T19:05:52","modified_gmt":"2023-07-20T13:35:52","slug":"expressjs-cookies","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/expressjs-cookies\/","title":{"rendered":"ExpressJS Cookies"},"content":{"rendered":"<p>In web development, cookies are a common way to store data on the client-side, and they can be used for a variety of purposes, such as session management, user authentication, and tracking user behavior. In this article, we will explore the basics of cookies in Express.js and how they can be used to enhance the functionality of web applications.<\/p>\n<h3>What are Cookies?<\/h3>\n<p>Cookies are small text files that are stored on the client-side by a web server. They are used to store data that can be accessed by both the client and the server, and they can be used for a variety of purposes, such as session management, user authentication, and tracking user behavior. Cookies are sent back and forth between the client and server with every request and response, and they are stored in the client&#8217;s web browser until they expire or are manually deleted.<\/p>\n<h3>Using Cookies in ExpressJS<\/h3>\n<p>n Express.js, cookies can be set and retrieved using the cookie-parser middleware. This middleware parses incoming cookie headers and populates the req.cookies object with the key-value pairs of all cookies sent by the client.<\/p>\n<p>To use the cookie-parser middleware, you first need to install it using npm:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">npm install cookie-parser\r\n<\/pre>\n<p>Next, you need to require it in your application and use it as middleware before your routes:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">const express = require('express');\r\nconst cookieParser = require('cookie-parser');\r\n\r\nconst app = express();\r\n\r\napp.use(cookieParser());\r\n<\/pre>\n<p>Now that the middleware is set up, you can use the res.cookie() method to set a new cookie. This method takes two arguments: the name of the cookie and the value of the cookie.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">app.get('\/set-cookie', (req, res) =&gt; {\r\n  res.cookie('username', DataFlair);\r\n  res.send('Cookie set!');\r\n});\r\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">Cookie set!<\/div>\n<p>In this example, we define a new route &#8216;\/set-cookie&#8217; that sets a new cookie called &#8216;username&#8217; with the value &#8216;John&#8217;. Once the cookie is set, the server sends a response back to the client with the message &#8216;Cookie set!&#8217;.<\/p>\n<p>To retrieve a cookie value, you can simply access the req.cookies object using the name of the cookie:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">app.get('\/get-cookie', (req, res) =&gt; {\r\n  const username = req.cookies.username;\r\n  res.send(`Hello ${username}!`);\r\n});\r\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">Hello DataFlair<\/div>\n<p>In this example, we define a new route &#8216;\/get-cookie&#8217; that retrieves the value of the &#8216;username&#8217; cookie using the req.cookies object and sends a response back to the client with a personalized message.<\/p>\n<h3>Cookie Options in ExpressJS<\/h3>\n<p>Cookies can also be configured with various options, such as expiration time, path, and domain. To set these options, you can pass an options object as a third argument to the res.cookie() method.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">app.get('\/set-cookie', (req, res) =&gt; {\r\n  res.cookie('username', 'John', { maxAge: 86400000, httpOnly: true });\r\n  res.send('Cookie set!');\r\n});\r\n<\/pre>\n<p>In this example, we set the maxAge option to 86400000 milliseconds (1 day) and the httpOnly option to true, which makes the cookie accessible only through HTTP requests and not through client-side scripts.<\/p>\n<h3>ExpressJS Cookies Parser <strong>Installation<\/strong><\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">npm install cookie-parser\r\n<\/pre>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/04\/cookie-parser-install.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-115000\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/04\/cookie-parser-install.webp\" alt=\"cookie parser install\" width=\"512\" height=\"218\" \/><\/a><\/p>\n<p>The cookie-parser middleware works by parsing the Cookie header of an incoming request and populating a req.cookies object with the cookie key-value pairs. The middleware can also handle signed cookies, where the cookie value is signed using a secret key to prevent tampering.<\/p>\n<p>One of the functions provided by the cookie-parser middleware is JSONCookie(str). This function takes a string representing a JSON object and returns the parsed object. This is useful for cases where a cookie value is a JSON object and needs to be parsed before use.<\/p>\n<p>For example, consider the following cookie value:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">user={\"name\": \"John\", \"age\": 30}\r\n<\/pre>\n<p>To parse this cookie value and retrieve the user&#8217;s name, we can use the JSONCookie function as follows:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">const cookieParser = require('cookie-parser');\r\n\r\napp.use(cookieParser());\r\n\r\napp.get('\/', (req, res) =&gt; {\r\n  const user = cookieParser.JSONCookie(req.cookies.user);\r\n  const name = user.name;\r\n  res.send(`Hello ${name}!`);\r\n});\r\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">Hello John<\/div>\n<p>In addition to JSONCookie, the cookie-parser middleware also provides other functions to handle cookies, such as signedCookies, serialize, and parse. Here&#8217;s a brief overview of these functions:<\/p>\n<h4>1. signedCookies:<\/h4>\n<p>This function is similar to cookies, but it parses signed cookies using the secret key specified in the middleware options. The resulting object is stored in req.signedCookies.<\/p>\n<h4>2. serialize:<\/h4>\n<p>This function serializes an object into a cookie string. The resulting string can be used to set a cookie in the response headers.<\/p>\n<h4>3. parse:<\/h4>\n<p>This function parses a cookie string into an object. This is useful for cases where the cookie is received as a string in the request headers, rather than as individual key-value pairs.<\/p>\n<p>Overall, the cookie-parser middleware provides a convenient way to parse and handle cookies in Express.js applications. It simplifies the process of working with cookies, allowing developers to focus on building their application logic instead of dealing with low-level cookie handling.<\/p>\n<h3>Deleting Cookies in ExpressJS<\/h3>\n<p>To delete a cookie, you can use the res.clearCookie() method, which takes the name of the cookie as an argument.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">app.get('\/clear-cookie', (req, res) =&gt; {\r\n  res.clearCookie('username');\r\n  res.send('Cookie cleared!');\r\n});\r\n<\/pre>\n<p>In this example, we define a new route &#8216;\/clear-cookie&#8217; that deletes the &#8216;username&#8217; cookie using the res.clearCookie() method and sends a response back to the client with the message &#8216;Cookie cleared!&#8217;.<\/p>\n<h3>Security Considerations<\/h3>\n<p>Cookies can be a powerful tool for web developers, but they can also pose security risks if not properly configured. One of the most common security risks associated with cookies is cross-site scripting (XSS) attacks. This occurs when malicious scripts are injected into a website through vulnerable input fields, such as search boxes or contact forms. To mitigate the risk of XSS attacks, you can set the httpOnly option to true, which prevents client-side scripts from accessing the cookie.<\/p>\n<p>Another security risk associated with cookies is cross-site request forgery (CSRF) attacks, which occur when a malicious website sends a request to a legitimate website on behalf of the user, exploiting their authentication credentials stored in cookies.<\/p>\n<p>To mitigate the risk of CSRF attacks, you can use the csurf middleware in Express.js, which generates and validates unique tokens for each incoming request, ensuring that only legitimate requests are processed.<\/p>\n<h3>Conclusion<\/h3>\n<p>Cookies are a powerful tool for web developers that can be used for a variety of purposes, such as session management, user authentication, and tracking user behavior. In Express.js, cookies can be easily set and retrieved using the cookie-parser middleware, and they can be configured with various options, such as expiration time, path, and domain. However, it is important to consider the security risks associated with cookies and to configure them properly to prevent XSS and CSRF attacks. With proper configuration and usage, cookies can be a valuable asset in building secure and robust web applications.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In web development, cookies are a common way to store data on the client-side, and they can be used for a variety of purposes, such as session management, user authentication, and tracking user behavior.&#46;&#46;&#46;<\/p>\n","protected":false},"author":581,"featured_media":114794,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[27631],"tags":[27691],"class_list":["post-114748","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-express-js-tutorials","tag-expressjs-cookies"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v28.0 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>ExpressJS Cookies - DataFlair<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/data-flair.training\/blogs\/expressjs-cookies\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"ExpressJS Cookies - DataFlair\" \/>\n<meta property=\"og:description\" content=\"In web development, cookies are a common way to store data on the client-side, and they can be used for a variety of purposes, such as session management, user authentication, and tracking user behavior.&#046;&#046;&#046;\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/expressjs-cookies\/\" \/>\n<meta property=\"og:site_name\" content=\"DataFlair\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/DataFlairWS\/\" \/>\n<meta property=\"article:published_time\" content=\"2023-07-20T13:35:33+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-07-20T13:35:52+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/04\/expressjs-cookies.webp\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/webp\" \/>\n<meta name=\"author\" content=\"DataFlair Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:site\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"DataFlair Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"ExpressJS Cookies - DataFlair","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/data-flair.training\/blogs\/expressjs-cookies\/","og_locale":"en_US","og_type":"article","og_title":"ExpressJS Cookies - DataFlair","og_description":"In web development, cookies are a common way to store data on the client-side, and they can be used for a variety of purposes, such as session management, user authentication, and tracking user behavior.&#46;&#46;&#46;","og_url":"https:\/\/data-flair.training\/blogs\/expressjs-cookies\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2023-07-20T13:35:33+00:00","article_modified_time":"2023-07-20T13:35:52+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/04\/expressjs-cookies.webp","type":"image\/webp"}],"author":"DataFlair Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"DataFlair Team","Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/expressjs-cookies\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/expressjs-cookies\/"},"author":{"name":"DataFlair Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/c187795dc82ab948373cca526df7c445"},"headline":"ExpressJS Cookies","datePublished":"2023-07-20T13:35:33+00:00","dateModified":"2023-07-20T13:35:52+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/expressjs-cookies\/"},"wordCount":1006,"commentCount":0,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/expressjs-cookies\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/04\/expressjs-cookies.webp","keywords":["ExpressJS Cookies"],"articleSection":["Express JS Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/expressjs-cookies\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/expressjs-cookies\/","url":"https:\/\/data-flair.training\/blogs\/expressjs-cookies\/","name":"ExpressJS Cookies - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/expressjs-cookies\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/expressjs-cookies\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/04\/expressjs-cookies.webp","datePublished":"2023-07-20T13:35:33+00:00","dateModified":"2023-07-20T13:35:52+00:00","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/expressjs-cookies\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/expressjs-cookies\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/expressjs-cookies\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/04\/expressjs-cookies.webp","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/04\/expressjs-cookies.webp","width":1200,"height":628,"caption":"expressjs cookies"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/expressjs-cookies\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog Home","item":"https:\/\/data-flair.training\/blogs\/"},{"@type":"ListItem","position":2,"name":"Express JS Tutorials","item":"https:\/\/data-flair.training\/blogs\/category\/express-js-tutorials\/"},{"@type":"ListItem","position":3,"name":"ExpressJS Cookies"}]},{"@type":"WebSite","@id":"https:\/\/data-flair.training\/blogs\/#website","url":"https:\/\/data-flair.training\/blogs\/","name":"DataFlair","description":"Learn Today. Lead Tomorrow.","publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/data-flair.training\/blogs\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/data-flair.training\/blogs\/#organization","name":"DataFlair","url":"https:\/\/data-flair.training\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","width":106,"height":48,"caption":"DataFlair"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/DataFlairWS\/","https:\/\/x.com\/DataFlairWS","https:\/\/www.linkedin.com\/company\/dataflair-web-services-pvt-ltd\/","https:\/\/www.youtube.com\/user\/DataFlairWS"]},{"@type":"Person","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/c187795dc82ab948373cca526df7c445","name":"DataFlair Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","caption":"DataFlair Team"},"description":"DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.","url":"https:\/\/data-flair.training\/blogs\/author\/dfteam6\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/114748","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/users\/581"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=114748"}],"version-history":[{"count":5,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/114748\/revisions"}],"predecessor-version":[{"id":116607,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/114748\/revisions\/116607"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/114794"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=114748"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=114748"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=114748"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}