Devise by default redirects the user to the previous url (if present) after authenticating. This is a very useful default to have. But this behaviour is lost if we override the after_sign_in_path_for method in our application.

Internally devise stores the previous url in the session with key resource_return_to. In its actual implemention, after_sign_in_path_for checks for the presence of the resource_return_to key in the session and redirects the user to it. We need to do the same if we ever override this method.

The recommended way of overriding is

def after_sign_in_path_for(resource) {
  # Remember to check for the presence of stored_location
  stored_location_for(resource) ||
  # Your custom logic here
  # Example: If your users have a preferred page to be taken to after signin
  if resource.preferred_page.present?
    preferred_page_path(resource)
  else
    super
  end
}

Ref: stored_location_for is a helper method provided by devise.