How To Handle Cookies In Node JS With Express

Handle Cookies In Node JS With Express

In web development, cookies play a crucial role in maintaining state and user sessions. They are small pieces of data stored on the client-side and are sent along with every request to the server. In this tutorial, you will learn how to handle cookies in a Node.js application using the Express framework, leveraging the cookie-parser middleware.

1. Setting up a Node.js project

First, make sure you have Node.js installed on your system. You can download and install it from the official Node.js website if you haven’t already.

Create a new directory for your project and navigate into it in your terminal. Then initialize a new Node.js project by running:

npm init -y

This will create a package.json file with default settings.

2. Installing Express and cookie-parser

Next, install Express and cookie-parser by running the following command:

npm install express cookie-parser

This will install Express and cookie-parser as dependencies for your project.

3. Creating Node server with cookie-parser middleware

reate a new file, let’s call it app.js, and set up a basic Express server. Import Express and cookie-parser, create an Express app, and use the cookie-parser middleware.

const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
const PORT = process.env.PORT || 3000;

app.use(cookieParser());
// Define routes and other middleware

app.listen(PORT, () => console.log(`Server is runngin on port ${PORT}`));

4. Setting Cookies in Node.js:

To set a cookie, use the res.cookie() method within your route handler.

app.get('/setcookie', (req, res) => {
  res.cookie('username', 'john', { maxAge: 900000, httpOnly: true });
  res.send('Cookie is set');
});

5. Accessing the Cookies:

You can access cookies using req.cookies within your route handlers.

app.get('/getcookie', (req, res) => {
  const username = req.cookies.username;
  res.send('Cookie value: ' + username);
});

6. Starting the Node.js Server:

// Import the required modules
const express = require("express");
const cookieParser = require("cookie-parser");

// Create an Express app
const app = express();

// Define the port for the server, using either the environment variable PORT or defaulting to 3000
const PORT = process.env.PORT || 3000;

// Use the cookie-parser middleware to parse cookies attached to the client request object
app.use(cookieParser());

// Define a route to set a cookie named 'username' with value 'john'
app.get("/setcookie", (req, res) => {
    // Set a cookie named 'username' with value 'john' and additional options
    res.cookie("username", "john", { maxAge: 900000, httpOnly: true });
    // Send a response indicating that the cookie is set
    res.send("Cookie is set");
});

// Define a route to get the value of the 'username' cookie
app.get("/getcookie", (req, res) => {
    // Access the 'username' cookie from the request object's cookies property
    const username = req.cookies.username;
    // Send a response displaying the value of the 'username' cookie
    res.send("Cookie value: " + username);
});

// Start the server, listening on the specified port
app.listen(PORT, () => console.log(`Server is running on port ${PORT}`));

Start the Express server by running node app.js. Your server will be running on port 3000 by default.

7. Testing the Cookie Handling Routes:

Test the routes using a web browser or API testing tool like Postman. Visit /setcookie to set a cookie and /getcookie to retrieve its value.


Exploring Cookie Parser Options:

cookieParser(secret):

The secret parameter allows you to sign cookies to prevent tampering. It’s a string used for signing the cookie. Pass it as the first argument when using cookie-parser.

const secret = 'your-secret-key';
app.use(cookieParser(secret));

Cookie Options:

You can specify various options when setting cookies. Common options include:

  • maxAge: Specifies the maximum age of the cookie in milliseconds.
  • expires: Specifies the cookie’s expiration date (Date object).
  • httpOnly: If set to true, the cookie is accessible only through the HTTP(S) protocol.
  • secure: If set to true, the cookie is sent only over HTTPS.
  • sameSite: Controls when cookies are sent with cross-origin requests.
app.get('/setcookie', (req, res) => {
    res.cookie('username', 'john', { maxAge: 900000, httpOnly: true });
    res.send('Cookie is set');
});

Apply options universally:

When you provide options to the cookieParser middleware, such as maxAge, httpOnly, secure, etc., these options are applied universally to all cookies parsed by the middleware. This means that every cookie set or parsed by your Express application will adhere to these options.

const options = {
    maxAge: 900000,
    httpOnly: true
};
app.use(cookieParser(secret, options));

Leave a Reply

Your email address will not be published. Required fields are marked *

We use cookies to ensure that we give you the best experience on our website. Privacy Policy