Search code examples
javascriptexpresscookiessession-cookieshttp-status-code-400

How to Avoid throwing 400 errors from ExpressJS


Background: I am getting 400 errors (and a blank 400 page response) from a malformed cookie on my site (coming from one of my affiliate pages). I have wrote a code to delete the cookie, but some of my customers still get an error because it's in their cache. Once they clear their cache the problem is fixed.

This issue is circumvented all together in my .NET code base by simply ignoring a 400 error, I would like to do the same in Express JS.

Ask: I would like to have express ignore all cookies on a 400 error (often caused by defective cookies) or to at least ignore the error all together. Is there any way to do this?

My ClearDefectiveCookies function for reference (functioning correctly)

const clearDefectiveCookies = (req, res, next) => {
  const cookies = req.cookies;
  const defectiveCookies = Object.keys(cookies).filter(key => typeof cookies[key] === 'string' && (cookies[key].charAt(0) === '='));

  if (defectiveCookies.length > 0) {
    defectiveCookies.forEach(defectiveCookie => {
      res.clearCookie(defectiveCookie);
    });
  }

  next();
};

Problematic Cookie for Reference

Name: xyz_123 and value: =NaN=xyz=123


Solution

  • So the answer is actually that node had a breaking change in November 2018, it isn't the cookie that is the issue, it's that node has a max cookie size causing the 400 errors. It isn't actually express..

    See answer here: Why am I getting 400 errors? Node, Express, ReactJS