Fix login redirection to requested page after authentication by Nowaker · Pull Request #1912 · hackmdio/codimd

Problem

When a user attempts to access a protected resource without being logged in, they are correctly redirected to the login page with a next parameter preserving their intended destination (e.g., /?next=%2Fwb0e9nB5T3qecF27Y4xlsg). However, after successful authentication, the application always redirects to the dashboard/homepage instead of returning the user to their originally requested URL.

This creates a poor user experience as users must manually navigate back to the content they were originally trying to access.

Solution

The root cause was identified in the email authentication implementation where the successReturnToOrRedirect parameter was hardcoded to always redirect to the server's homepage.

successReturnToOrRedirect: config.serverURL + '/',

This change properly utilizes the req.session.returnTo value that's already being correctly set by the setReturnToFromReferer function:

// After: Redirect to originally requested page or homepage if none
successReturnToOrRedirect: req.session.returnTo,

Testing

Manually tested the authentication flow by:

  1. Attempting to access a protected note while logged out
  2. Confirming redirection to login page with proper next parameter
  3. Logging in with valid credentials
  4. Verifying successful redirection to the originally requested note

This fix respects the standard behavior of Passport.js's successReturnToOrRedirect parameter, which will redirect to the URL stored in req.session.returnTo if available, or fall back to the configured redirect URL otherwise.