Tuesday 30 April 2019

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

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



from How to Avoid throwing 400 errors from ExpressJS

No comments:

Post a Comment