Redirect to a custom page after the user signed in

What is the correct way to go in case a user should be redirected to a custom page after being authenticated?
I see that by default it is redirected to the / path as defined in the generated UserAuth#redirect_if_user_is_authenticated/2.
Imagine the scenario when you have a landing page defined at / path and you’d like to be redirected to another (protected) page after the authentication.

If you use the :require_authenticated_user plug on any other route than / (e.g. /path/to/protected/resource), you’ll be redirected to /users/log_in first, to log in. The original requested path will be saved in the session, so that you’ll be redirected to the originally requested path after you log in successfully (to see how it works, see the :user_return_to key in the UserAuth module).

There is also the option to change the implementation of the private function signed_in_path, which by default returns the / path. Its return value is used to redirect the user after he/she has logged in (and the previous mechanism wasn’t triggered).

Depending on how you let the user log in (provide a link to the protected route, or link to the login page explicitly), one of these two options will give you the desired result.

1 Like

To access any other protected routes, a User will do it only from the landing page (not protected and defined at /path) via a button/link. So in this case, there will be no originally requested path. Sure, even if a User tries to access manually a protected path, he will be redirected to the users/log_in path default behavior).

You users may bookmark a protected route, and the login session will expire after some time. So, when user click a bookmark, and has to go though login again, the route saving and redirect back trick suggested by @linusdm is still useful.

I do understand how the redirect will work in this case, :slight_smile: , my question was about how to redirect after a successful login when coming from a landing page. For example, in a Rails application using Devise, it is possible just to override after_sign_in_path_for or after_sign_out_path_for method in the application_controller and you’ll be good to go :smiley: .

As I supposed, changing the signed_in_path function to point to another path fixed the problem.

1 Like