Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Avoid throwing 400 errors from ExpressJS

Tags:

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

like image 506
Kevin Danikowski Avatar asked Apr 24 '19 20:04

Kevin Danikowski


1 Answers

Possibly that the problem is the way how you call res.clearCookie. If you look in the documentation, it says:

Web browsers and other compliant clients will only clear the cookie if the given options is identical to those given to res.cookie(), excluding expires and maxAge.

So in order to clear the cookies, you will have to provide a second argument as an object, providing the path.

like image 149
Shimon Brandsdorfer Avatar answered Nov 15 '22 06:11

Shimon Brandsdorfer