djthoms djthoms - 3 months ago 23
Node.js Question

Express 401 redirect is not happening automatically

Encountering a situation where I redirect users with a 401 when they're not authorized to access a page. I have this in one of my routes:

res.redirect(401, '/login');

Seems simple enough, but the app loiters and doesn't redirect the user to
. It just sits on a page similar to this:

Unauthorized. Redirecting to /login

Headers look fine too:

HTTP/1.1 401 Unauthorized
X-Powered-By: Express
Location: /login
Vary: Accept
Content-Type: text/html; charset=utf-8
Content-Length: 63
set-cookie: connect.sid=stuff; Path=/; HttpOnly
Date: Sun, 20 Nov 2016 02:20:07 GMT
Connection: keep-alive

The weird thing is that if I omit the status, the redirect happens normally:

res.redirect('/login'); // doesn't hang on page, redirect occurs immediately

I was under the impression that redirection would be automatic, but maybe not? Any insight?


401 is not a redirect status. Just use a regular (303) redirect instead – 401 is invalid if you’re not sending a WWW-Authenticate header anyway.