Cookies in Express Js

  • Cookies in Express.js are small pieces of data sent from a server to a client's browser and stored locally. They are often used to store user-related information, session data, and other stateful information on the client side. Express.js provides a convenient way to work with cookies through the `cookie-parser` middleware.
Let's go through an example to illustrate how cookies are used in an Express.js application:
  • Install `cookie-parser`: First, you need to install the `cookie-parser` middleware. Open your terminal and run the following command:

    npm install cookie-parser

  • Create an Express App (`app.js`):

    // app.js

    const express = require('express');
    const cookieParser = require('cookie-parser');

    const app = express();
    const PORT = 3000;

    // Use cookie-parser middleware
    app.use(cookieParser());

    // Route to set a cookie
    app.get('/set-cookie', (req, res) => {
        // Set a cookie with name 'user' and value 'john-doe'
        res.cookie('user', 'john-doe', {
            maxAge: 900000,
            httpOnly: true
        });
        res.send('Cookie has been set!');
    });

    // Route to read a cookie
    app.get('/get-cookie', (req, res) => {
        // Read the 'user' cookie
        const userName = req.cookies.user;

        if (userName) {
            res.send(`Hello, ${userName}!`);
        } else {
            res.send('No user cookie found.');
        }
    });

    // Route to clear a cookie
    app.get('/clear-cookie', (req, res) => {
        // Clear the 'user' cookie
        res.clearCookie('user');
        res.send('Cookie has been cleared!');
    });

    app.listen(PORT, () => {
        console.log(`Server is running on http://localhost:${PORT}`);
    });

  • In this example: We use `cookie-parser` middleware to handle cookies. This middleware parses cookies attached to the client's request object and makes them available as `req.cookies`.
  • The `/set-cookie` route sets a cookie named 'user' with the value 'john-doe'. The cookie is configured to expire after 900,000 milliseconds (15 minutes) and is marked as `httpOnly` for enhanced security.
  • The `/get-cookie` route reads the 'user' cookie and responds with a personalized greeting if the cookie exists.
  • The `/clear-cookie` route clears the 'user' cookie.
  • Run the Application: Run your application using the command:

    node app.js

  • Test the Routes: Visit the following URLs in your browser or use tools like Postman:
    • http://localhost:3000/set-cookie: This will set the 'user' cookie.
    • http://localhost:3000/get-cookie: This will read and display the value of the 'user' cookie.
    • http://localhost:3000/clear-cookie: This will clear the 'user' cookie.
Observations:
  • The `/set-cookie` route sets the 'user' cookie.
  • The `/get-cookie` route reads and displays the value of the 'user' cookie.
  • The `/clear-cookie` route clears the 'user' cookie.
  • This example demonstrates the basic use of cookies in Express.js. Cookies can store various types of data and are commonly used for authentication, tracking user sessions, and maintaining user preferences. The `cookie-parser` middleware simplifies the handling of cookies in Express.js applications.

No comments:

Post a Comment