Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript User Authentication With Express and Mongo Improving the App with Custom Middleware Writing More Middleware

Nathan Gallagher
Nathan Gallagher
21,518 Points

Why not just redirect to the login page if a user isn't logged in?

Any particular reason why Dave chose to display an error message instead of just redirecting non-logged in users to the login page when they try to access a password protected page? I'm wondering if there's a certain best practice here.

1 Answer

Steven Parker
Steven Parker
220,925 Points

:point_right: The error recognizes what was being attempted.

Just displaying the login page would certainly save a step towards getting to the desired page, but the issue is that the client was attempting to go directly to the protected page. So displaying the error recognizes the browser's intent, and provides an appropriate response.

Displaying a page other than the one requested, even in the case of an error, could be interpreted by the user as a malfunction of the application, or maybe even a hijacking or attempted identity theft.

The "best practice" here might be: "Always display either the requested page or an error".

Or even better, combine the two? Respond with a page which shows the error and then a login form underneath.