Skip to main content

Cookies

What is Cookie?

Cookies are small pieces of data stored on a user's device by websites they visit. They serve various purposes in web development.

Example Cookies use cases.

  1. Session Management

  2. Personalization

  3. Tracking and Analytics

  4. Advertising

  5. Shopping Carts

  6. Security

EX: Find cookies in YouTube.

  1. open dev tools in YouTube tab. (Usually use F12 to open it.) image.png
  2. go to Application tab.

    DYKimage.png

  3. Here's your YouTube cookies information is displayed.

    image.png


     

Try Using cookies in your web server.

1. Init your server project
Here I will teach you how to create a project by terminal.
(windows PowerShell in windows or bash, sh, zsh in MacOS & Linux)
You can also create it in your comfortable ways.
  1.  Create your project folder and enter it with: 
    mkdir backend_w3
    cd backend_w3
    
    # for mac users (sh, bash and etc..) you can use && to sequently run the commands
    mkdir backend_w3 && cd backend_w3
    # for windows PowerShell use ; instead
    mkdir backend_w3 ; cd backend_w3
    mkdir -> make directory (AKA folder)
    cd -> change working directory (AKA change folder)

  2. Initialize your project and install node modules dependencies with  npm:
    npm init -y
    npm i express nodemon

    -y is for accept all default configurations.

  3. Create index.js as main server file.
    const express = require('express');
    
    const app = express();
    const port = 4000;
    
    app.get('/', (req, res) => res.send('Hello World!'));
    
    app.listen(port, () => console.log(`Server running on port ${port}`));
    
  4. Create an endpoint for sending cookie in index.js before app.listen:
    app.get('/getCookie', (req, res) => {
    	try {
    		const name = 'MyCookie';
    		const value = 'This is my cookie';
    		res.cookie(name, value);
    		return res.send('Cookie set');
    	} catch (error) {
    		console.log(error);
    		return res.status(500).send('Cookie not set');
    	}
    });
  5. Now you if you go to localhost:4000/getCookie and inspect it you will see your cookie there.

    image.png

  6. But as you see your cookies information is not private and that is some critical privacy issue due to the use cases of cookies sometime store sensitive information of users or even our own website.