Proper Middleware Order and Implementation for Setting Cookies in Express Framework

Nov 11, 2025 · Programming · 13 views · 7.8

Keywords: Express Framework | Cookie Setting | Middleware Order | Node.js | Security

Abstract: This article provides an in-depth analysis of common issues and solutions when setting cookies in Node.js Express framework. By examining the impact of middleware execution order on cookie setting, it explains why static file middleware can prevent subsequent middleware from executing. The article includes complete code examples demonstrating proper usage of cookie-parser middleware, cookie parameter configuration, and handling cookie reading and validation. It also covers the security advantages of the httpOnly flag, helping developers build more secure web applications.

Importance of Middleware Execution Order

In the Express framework, the execution order of middleware directly affects application behavior. When using express.static middleware to handle static file requests, if this middleware is placed before custom cookie-setting middleware, it will directly respond to the request and terminate the execution of subsequent middleware. This explains why cookies could not be properly set in the original code.

Proper Usage of Cookie Parser

Modern Express applications require the separate cookie-parser package to handle cookies. First install via npm: npm install cookie-parser, then import and use in the application:

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

const app = express();
app.use(cookieParser());

Implementation of Cookie Setting Middleware

The correct cookie setting middleware should check if a cookie already exists, create a new cookie if it doesn't, and ensure to call the next() function to pass control to the next middleware:

app.use(function (req, res, next) {
  const cookie = req.cookies.cookieName;
  
  if (cookie === undefined) {
    const randomNumber = Math.random().toString().substring(2);
    res.cookie('cookieName', randomNumber, { 
      maxAge: 900000, 
      httpOnly: true 
    });
    console.log('Cookie created successfully');
  } else {
    console.log('Cookie exists:', cookie);
  }
  
  next();
});

Correct Middleware Order Configuration

Ensure cookie-related middleware executes before static file middleware:

// Cookie parser first
app.use(cookieParser());

// Cookie setting middleware
app.use(cookieMiddleware);

// Static file middleware last
app.use(express.static(__dirname + '/public'));

Detailed Cookie Parameters

When setting cookies, several important parameters can be configured:

Security Considerations and Practical Recommendations

Using httpOnly flagged cookies is more secure than storing tokens in localStorage because it prevents XSS attacks from accessing sensitive information. In practical applications, it is recommended to:

Complete Example Code

Below is a complete Express server configuration example:

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

const app = express();

// Middleware configuration
app.use(cookieParser());

app.use(function (req, res, next) {
  const cookie = req.cookies.cookieName;
  
  if (!cookie) {
    const randomValue = Math.random().toString().substring(2);
    res.cookie('cookieName', randomValue, {
      maxAge: 15 * 60 * 1000, // 15 minutes
      httpOnly: true
    });
    console.log('New cookie set');
  }
  
  next();
});

app.use(express.static('public'));

const server = http.createServer(app);
server.listen(5555, () => {
  console.log('Server running on port 5555');
});

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.