Step 14

Add the following to index.js after app.use(cookieParser()); and before any of the route handlers:

app.use((req, res, next) => {
  if (req.cookies.message) {
    res.clearCookie("message");
  }
  next();
});

Recall middleware intercept req and res objects:

  • before the req goes to any of the route handlers, we intercept it and check if it contains a "message" cookie.
  • if there is a "message" cookie, then we call the clearCookie on the response object, so it will be called in addition to whatever else is done to the "response" in any of the route handlers (and other middleware).
  • the next() function is part of the semantic of any middleware; it calls the "next" middleware (if there is any).

Save index.js and try to recreate the issue we observed in the previous section.