{"id":358,"date":"2021-04-10T15:13:16","date_gmt":"2021-04-10T09:43:16","guid":{"rendered":"http:\/\/codeforgeek.com\/?p=358"},"modified":"2023-02-21T10:03:19","modified_gmt":"2023-02-21T04:33:19","slug":"manage-session-using-node-js-express-4","status":"publish","type":"post","link":"https:\/\/codeforgeek.com\/manage-session-using-node-js-express-4\/","title":{"rendered":"How to Manage Session using Node.js and Express"},"content":{"rendered":"\n<p><a href=\"https:\/\/codeforgeek.com\/what-is-node-js\/\" data-type=\"URL\" data-id=\"https:\/\/codeforgeek.com\/what-is-node-js\/\">Node.js<\/a> is an emerging technology, and with <a href=\"https:\/\/codeforgeek.com\/express-nodejs-tutorial\/\" target=\"_blank\" data-type=\"URL\" data-id=\"https:\/\/codeforgeek.com\/express-nodejs-tutorial\/\" rel=\"noreferrer noopener\">Express <\/a>it become insanely powerful. We can use Node.js with Express to manage sessions. In this tutorial, you will learn to manage sessions including setting up sessions, saving data in sessions and fetching data from sessions.<\/p>\n\n\n\n<p>A website uses <a href=\"https:\/\/codeforgeek.com\/handling-http-status-code-like-a-pro\/\" data-type=\"URL\" data-id=\"https:\/\/codeforgeek.com\/handling-http-status-code-like-a-pro\/\" target=\"_blank\" rel=\"noreferrer noopener\">HTTP <\/a>protocol to transfer information between a client and a server. This HTTP protocol is a stateless protocol, where the server won\u2019t have a status of communication and it doesn\u2019t keep track of requests and responses made from a client to the server. In terms of security, it is really better to track the user request to know how many times a user requests or which data a user wants to access, etc.<\/p>\n\n\n\n<p>To make the HTTP protocol stateful from stateless, we have <strong>sessions<\/strong>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Session in Node.js<\/h2>\n\n\n\n<p>A session comes into action when a client makes a request to the server, a server then creates a session with a unique ID sent to the user as a response as cookies and stored on their browser and the session server created is stored in the server. Next time when the same user comes, the session unique ID attached to the user will also come and the server knows that this user is the same user as the previous one.<\/p>\n\n\n\n<p>For creating a session in Node.js, we have a module \u201c<strong>express-session<\/strong>\u201d.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">express-session Module in Node.js<\/h2>\n\n\n\n<p>This module is used to manage sessions in Node.js, for installing this module in your Node.js project using <a href=\"https:\/\/codeforgeek.com\/nodejs-npm-node-package-manager\/\" target=\"_blank\" data-type=\"URL\" data-id=\"https:\/\/codeforgeek.com\/nodejs-npm-node-package-manager\/\" rel=\"noreferrer noopener\">NPM<\/a>, execute the below command in the terminal.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nnpm i express-session\n<\/pre><\/div>\n\n\n<p>If you got an error, make sure that you have Node and NPM installed on your system.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Session Setup in Node.js<\/h2>\n\n\n\n<p>To use this &#8220;<strong>express-session<\/strong>&#8221; module to set a session in Node.js, it is also required to install the Express module. Execute the below command in the terminal to install Express.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nnpm i express\n<\/pre><\/div>\n\n\n<p>Once you have installed the <strong>express-session<\/strong> and <strong>express <\/strong>module, it&#8217;s time to create a server file &#8220;<strong>app.js<\/strong>&#8221; to set up the session.<\/p>\n\n\n\n<p>Inside the server file, let\u2019s start with importing the express and express-session module, then create an instance of express and use it to call the \u201cuse\u201d method and pass the session method with an object as an argument containing a secret key, and some optional parameters.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nconst express = require(&#039;express&#039;)\nconst session = require(&#039;express-session&#039;)\nconst app = express()\n    \napp.use(session({secret: &#039;Your_Secret_Key&#039;, resave: true, saveUninitialized: true}))\n<\/pre><\/div>\n\n\n<p>Once we have set up the session, it&#8217;s time to create session variables, to store some information.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Creating Session Variables<\/h2>\n\n\n\n<p>Below is the syntax to create session variables:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nreq.session.key = value\n<\/pre><\/div>\n\n\n<p><strong>where the key is later used to access the value.<\/strong><\/p>\n\n\n\n<p>Let\u2019s create a variables userName and store some values in it.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\napp.get(&quot;\/&quot;, function(req, res){\n    req.session.userName = &#039;Aditya@123&#039;;\n\n    res.send(&quot;Thanks for visiting&quot;);\n})\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">Accessing Session Variables<\/h2>\n\n\n\n<p>Below is the syntax to Access session variables:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nreq.session.key\n<\/pre><\/div>\n\n\n<p>Let\u2019s access the session variables userName which we have created in the above step, and send its value as a response to the client.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\napp.get(&quot;\/login&quot;, function(req, res){\n    var userName = req.session.userName;\n    res.send(&quot;Welcome &quot; + userName);\n})\n<\/pre><\/div>\n\n\n<p><strong>Complete Code:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nconst express = require(&#039;express&#039;)\nconst session = require(&#039;express-session&#039;)\nconst app = express()\n    \napp.use(session({secret: &#039;Your_Secret_Key&#039;, resave: true, saveUninitialized: true}))\n   \napp.get(&quot;\/&quot;, function(req, res){\n    req.session.userName = &#039;Aditya@123&#039;;\n\n    res.send(&quot;Thanks for visiting&quot;);\n})\n   \napp.get(&quot;\/login&quot;, function(req, res){\n    var userName = req.session.userName;\n    res.send(&quot;Welcome &quot; + userName);\n})\n    \napp.listen(3000, function(error){\n    if(error) {\n        console.log(error)\n    }\n    console.log(&quot;Server listening on PORT 3000&quot;)\n})\n<\/pre><\/div>\n\n\n<p><strong>Run the Application<\/strong><\/p>\n\n\n\n<p>The application code is written in a single file \u201c<strong>app.js<\/strong>\u201d that runs on executing the below command in the terminal.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nnode app.js\n<\/pre><\/div>\n\n\n<p><strong>Open the Application<\/strong><\/p>\n\n\n\n<p>Enter the below URL inside the search bar of a web browser to open the application.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nhttp:\/\/localhost:3000\/\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img decoding=\"async\" width=\"734\" height=\"437\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2023\/02\/Session-Set.png\" alt=\"Session Set\" class=\"wp-image-16980\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2023\/02\/Session-Set.png 734w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2023\/02\/Session-Set-300x179.png 300w\" sizes=\"(max-width: 734px) 100vw, 734px\" \/><figcaption class=\"wp-element-caption\">Session Variables Created<\/figcaption><\/figure>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img decoding=\"async\" width=\"816\" height=\"478\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2023\/02\/Session-Get.png\" alt=\"Session Get\" class=\"wp-image-16981\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2023\/02\/Session-Get.png 816w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2023\/02\/Session-Get-300x176.png 300w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2023\/02\/Session-Get-768x450.png 768w\" sizes=\"(max-width: 816px) 100vw, 816px\" \/><figcaption class=\"wp-element-caption\">Session Variables Assessed<\/figcaption><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Summary&nbsp;<\/h2>\n\n\n\n<p>The session is important to keep track of its clients, to have knowledge about how many times they request the server and what response they want, etc. It provides security as well. For setting sessions, we have a module<strong> express-session<\/strong> which can be installed using NPM. Hope this tutorial helps to understand the way of managing sessions using Node.js and Express.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Reference<\/h2>\n\n\n\n<p><a href=\"https:\/\/www.npmjs.com\/package\/express-session\" target=\"_blank\" rel=\"noopener\">https:\/\/www.npmjs.com\/package\/express-session<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Node.js is an emerging technology, and with Express it become insanely powerful. We can use Node.js with Express to manage sessions. In this tutorial, you will learn to manage sessions including setting up sessions, saving data in sessions and fetching data from sessions. A website uses HTTP protocol to transfer information between a client and [&hellip;]<\/p>\n","protected":false},"author":79,"featured_media":16987,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_surecart_dashboard_logo_width":"180px","_surecart_dashboard_show_logo":true,"_surecart_dashboard_navigation_orders":true,"_surecart_dashboard_navigation_invoices":true,"_surecart_dashboard_navigation_subscriptions":true,"_surecart_dashboard_navigation_downloads":true,"_surecart_dashboard_navigation_billing":true,"_surecart_dashboard_navigation_account":true,"_uag_custom_page_level_css":"","footnotes":""},"categories":[14],"tags":[],"class_list":["post-358","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-nodejs"],"blocksy_meta":[],"uagb_featured_image_src":{"full":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2021\/04\/How-to-Manage-Session-using-Node.js-and-Express-Thumbnail.png",1200,600,false],"thumbnail":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2021\/04\/How-to-Manage-Session-using-Node.js-and-Express-Thumbnail-150x150.png",150,150,true],"medium":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2021\/04\/How-to-Manage-Session-using-Node.js-and-Express-Thumbnail-300x150.png",300,150,true],"medium_large":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2021\/04\/How-to-Manage-Session-using-Node.js-and-Express-Thumbnail-768x384.png",768,384,true],"large":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2021\/04\/How-to-Manage-Session-using-Node.js-and-Express-Thumbnail-1024x512.png",1024,512,true],"1536x1536":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2021\/04\/How-to-Manage-Session-using-Node.js-and-Express-Thumbnail.png",1200,600,false],"2048x2048":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2021\/04\/How-to-Manage-Session-using-Node.js-and-Express-Thumbnail.png",1200,600,false]},"uagb_author_info":{"display_name":"Aditya Gupta","author_link":"https:\/\/codeforgeek.com\/author\/aditya\/"},"uagb_comment_info":0,"uagb_excerpt":"Node.js is an emerging technology, and with Express it become insanely powerful. We can use Node.js with Express to manage sessions. In this tutorial, you will learn to manage sessions including setting up sessions, saving data in sessions and fetching data from sessions. A website uses HTTP protocol to transfer information between a client and&hellip;","_links":{"self":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/posts\/358","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/users\/79"}],"replies":[{"embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/comments?post=358"}],"version-history":[{"count":0,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/posts\/358\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/media\/16987"}],"wp:attachment":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/media?parent=358"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/categories?post=358"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/tags?post=358"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}