Learn About Cookies in Express.js with Our Step-by-Step Tutorial

Posted by








Express JS Tutorial | Cookies

Express JS Tutorial | Cookies

When it comes to web development, cookies play a crucial role in maintaining user sessions and storing user-specific information. In this tutorial, we will explore how to work with cookies in Express JS.

Setting Cookies

With Express JS, setting cookies is a breeze. You can use the res.cookie() method to set cookies in the response object. Here’s an example:

    
const express = require('express');
const app = express();

app.get('/setcookie', (req, res) => {
  res.cookie('username', 'john_doe');
  res.send('Cookie has been set');
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});
    
  

Reading Cookies

To read cookies in Express JS, you can access the req.cookies object, which is automatically populated with cookies sent by the client. Here’s an example:

    
app.get('/readcookie', (req, res) => {
  const username = req.cookies.username;
  res.send(`Hello ${username}`);
});
    
  

Clearing Cookies

If you want to clear a cookie, you can use the res.clearCookie() method. Here’s an example:

    
app.get('/clearcookie', (req, res) => {
  res.clearCookie('username');
  res.send('Cookie has been cleared');
});
    
  

Working with cookies in Express JS is simple and straightforward. It allows you to store user-specific information and maintain user sessions effectively. Whether you’re building a simple website or a complex web application, cookies are an essential part of web development.

Happy coding!