session in nodejs

Nodejs is one of the popular back-end platform during these days it is so fast in run time and also consist of many powerful and useful libraries. anyway in this article i want introduce a nice method for transfer your information as an object between your routes.

We going to use session to make a class for managing our data. we will create an existence as a Javascript class with few static methods to manipulate data and save or remove a particular session.

There is just few steps to do it.

Step one: Add some dependencies:

To use get and set cookies and create session you will need these two library.

npm i express-session — save
npm i cookie-parser — save
Step two: Add this piece of code in specific place before your routes:

You can add them on your Server.js file or in a particular middleware between your routes. in my case there is a file name startup.js and i call it in Server.js.

Step three: Create a Bundle class.

Create a file named bundle.js in a favorite directory in my case there is in my utilities folder under the root path.

I want explain it a little. in these class you have three method as you can see they are Static because of their usage you will see in forward. (if you do know anything about static methods please search it on google).

Whole methods follow one rule (Models , Error and Message) the Models include all of your data consist of Arrays of object or just a single Json object again Errors and Message can be fill when you need pass an error or specific message to another routes to show on a View.

Know let me to explain the functions one by one.

1.createBundle: this function will return you an object that contains our three universal object it will be used when you want to pass your data to a view.

2.setBundle: this function has responsibly of saving your data in a specific session and prevent loosing data during a http request the last parameter of this function is optional to use if you want to set a particular session you can name it by bundleName parameter.

3.getBundle: When you redirected to another route so you need to get data from the session it so easy for you to just call getBundle function and save the data in a variable or directly pass it to a View. keep in your mind if your bundle has been sat by a specific name you should get it by same name.

Step four: Use your bundle class.

According to the explains above now you can use the bundle class very easy but i will take you some example of how it is work.

I wish you were familiar with this small and tricky way it just take you a good vision to how you can implement your bundle service it is so obvious that you can change it in a way your are easy to use.

At last i am eager to hear your feedback and let me to help you if there is something unclear in this article.

--

--

Mohamad Ravaei

Experienced .NET Developer | 7 years mastering C#, ASP.NET, Azure, JavaScript, Databases | Crafting innovative, scalable solutions.