Hello in this tutorial, we will understand Cookies and implement them in an Express.js application.
Cookies are a piece of any information sent from the server and are stored in the client’s browser. This information helps to track the client’s action and the browser sent it back to the server every time a client visits the website to recognize the client and its actions. Cookies in an application are used to manage sessions, client personalization, and tracking.
1.1 Setting up Node.js
To set up Node.js on windows you will need to download the installer from this link. Click on the installer (also include the NPM package manager) for your platform and run the installer to start with the Node.js setup wizard. Follow the wizard steps and click on Finish when it is done. If everything goes well you can navigate to the command prompt to verify if the installation was successful as shown in Fig. 1.
2. Express.js Cookies Tutorial
To set up the application, we will need to navigate to a path where our project will reside. For programming stuff, I am using Visual Studio Code as my preferred IDE. You’re free to choose the IDE of your choice.
2.1 Setting up dependencies
Navigate to the project directory and run
npm init -y to create a
package.json file. This file holds the metadata relevant to the project and is used for managing the project dependencies, script, version, etc. Add the following code to the file wherein we will specify the required dependencies.
To download the dependencies navigate to the directory path containing the file and use the
npm install command. If everything goes well the dependencies will be loaded inside the
node_modules folder and you are good to go with the further steps.
2.2 Creating the controller file
Create a controller file in the
routes folder. This file will expose endpoints that will be responsible to entertain the request from the client.
2.3 Creating an index file
Create an index file that will act as an entry point for our server. The file will contain the code to define the routes to the application endpoints.
3. Run the Application
To run the application navigate to the project directory and enter the following command as shown in Fig. 4. If everything goes well the application will be started successfully on port number
4. Project Demo
When the application is started, open the Postman tool to hit the application endpoints. You are free to choose any tool of your choice.
Similarly, you can create other endpoints. That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!
In this tutorial, we learned –
- Introduction to Cookies
- Steps to setup Node.js
- Sample programming stuff
You can download the source code of this tutorial from the Downloads section.
This was a programming tutorial to manage cookies in an express.js application.
You can download the full source code of this example here: Express.js Cookies Tutorial