Redirect does not work

I am trying to redirect to an external URL.
In one of the handle_info functions in my liveview, I have something like:

redirect(socket, external: "https://somewebsite.com")

But it just does not do anything.
If I change external: to to:, I get an error message saying that redirect/2 expects a path, so I know the statement is executed. If I additionally change it to one of the paths defined in my router, then nothing happens either. No message or anything. I can see that redirect just returns the socket itself. But nothing special to see.
I found some info that redirect does not work in child components, so I made sure the redirect is in a root live view. I guess I am just missing something obvious, I just don’t see it.
Any ideas?

You need to use a path that is defined in your router.

For example, if you have:

# router.ex

...
live "/users", Userslive
...

you can use:

redirect(socket, to: live_path(socket, UsersLive))

if you have an action defined in the router

...
live "/users", Userslive
live "/users/new", Userslive, :new
...

you can specify the action in the path:

redirect(socket, to: Routes.users_path(socket, :new))

Thanks, but two questions:

1 How to redirect to an external URL?

2 I did use the live_path for the internal path, but as said, nothing happens.

You are returning the proper annotated socket for redirection as below?

def handle_update(...) do
  ...
  {:noreply, redirect(socket, external: "https://somewebsite.com")}
end

and not something like:

  ...
  redirect(socket, external: "https://somewebsite.com")
  {:noreply, socket}
end

The redirection is done client side.

2 Likes

Awesome. That’s it!