Cookies🍪, lets bake this happen

Charlie K
3 min readDec 23, 2020

Setting up Http Cookies using Express JS for your application

What are cookies?

Cookies

Cookies are small files that websites send to your device that the sites then use to monitor your user activities, session management and for personalization.

A cookie generally contains the information as a string generally in the form of a key-value pair and remembers the user’s information among all web pages in a browser.

How cookies work

When a user sends a request to server say by visiting a website that request is treated as a new request. The server in our case the backend attaches a cookie to the request so that when a user makes a future request the server recognizes the user from the cookie.

Requirements:

· Node installed

· Text editor

· Chrome browser

Setup

We will be using npm package express for setting up our server and cookie-parser

On the terminal use the command to install express and cookie-parser

npm install express cookie-parser

The res.cookie() function is used to set the cookie name to value.

The 🍪 code

To view the set cookies, we can use:

1. document.cookie in Console tab on the browser Developer Tools

Console

2. Tools | Developer Tools. Then click on Resources | Cookies

Cookies tab

You should never store sensitive information in cookie, though cookies are so dough-pe😂- Charlie K

Risk of Cookies and What You Need to Watch out For

Cross-Site Scripting (XSS)

This is an attack aimed at stealing session cookies in the client-side script using JavaScript (document.cookie)

This can be eliminated through adding HttpOnly flag attribute to the cookie

response.setHeader('Set-Cookie', 'foo=bar; HttpOnly');

Cookie Tossing Attack

A user is provided with a cookie by a malicious site, which has been designed to look like it’s come from the targeted site’s subdomain. For example: http://subdomain.placeholder.com. Therefore, when the user goes to the targeted site (placeholder.com), all of the cookies are sent, including legitimate ones and the subdomain cookie. Where the cookie that’s interpreted first is the subdomain, this data will overrule any of the legitimate data contained in the other valid cookies.

Now what next?

Protecting your online privacy

· Use an “Incognito” or “Private” browsing mode

· Viewing and Deleting Your Browser’s Stored Cookies

Conclusion

Cookies are so integral to the internet of today. Despite their advantages they also pose a security risk for users.

Now you can at least setup cookies for your web app, next we’ll add sessions to store and keep track of cookies for authentication and session management over stateless Http .

Remember when it comes to baking, don’t be afraid to take whisks

--

--

Charlie K

learn, innovate repeat. Writer, web developer ,tech & nature enthusiast. My posts are abstract😜