Cookies are small data that are stored on a client-side and sent to the client along with server requests. With the help of the cookie-parser module, we can do set the cookies as well as get the cookies.
Create a project folder and run the following command from the root directory of the project:
npm init -y
This command will ask for the name of the module. Keep pressing enter until the end of the options. This will create an empty npm module with a package.json file. We will now install all the required dependencies using the below command:
npm install express cookie-parser
We are using express to create a server and cookie-parser is the library which will help us in working with cookies easily. Let’s create a file called index.js and write the code to create a server with two routes to set and get the cookies as given in the code below:
Here we have a route /setcookie which is used to set a cookie with key my_cookie and the value as geeksforgeeks. We can alter these keys and values to be anything as per requirement. Another route is /getcookie which is used to get all the cookies and show them on the webpage. At the end of the code, we are listening to 3000 port for our server to be able to run.
Run the index.js file using the following command:
This will run the server as shown in the image above. We can check cookies by visiting localhost:3000/setcookie.
This will show a message as cookies are added. We can check the cookies by visiting localhost:3000/getcookie.
Now we can see that our cookies are added to the cookies object as shown above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.