Redirect to external URL using BeforeEnterObserver

HI all,

I want to redirect to a external page using the BeforeEnterObserver interface

this is my code

@Route(value = "hello", layout = MainView.class)
@RouteAlias(value = "", layout = MainView.class)
public class HelloWorldView extends Div implements BeforeEnterObserver{

    private TextField name;
    private H1 mainTitle;
    private String parameter = "";

    public HelloWorldView() {
        //some code here

	public void beforeEnter(BeforeEnterEvent event) {
			   .executeJavaScript("window.location.href = ''");


And i getting this error message

java.util.NoSuchElementException: No value present
	at java.base/java.util.Optional.get( ~[na:na]

	at com.example.application.views.helloworld.HelloWorldView.beforeEnter( ~[classes/:na]

	at com.vaadin.flow.router.internal.AbstractNavigationStateRenderer.sendBeforeEnterEvent( ~[flow-server-4.0.4.jar:4.0.4]

Seems getUI method return a null object, is there a way to redirect to external website without use getUI method?

You are calling getUI().get() in beforeEnter so I think there is no UI yet.
Have a look at

INPUTsys Chris Peter:
You are calling getUI().get() in beforeEnter so I think there is no UI yet.
Have a look at

Thanks for your reply but i think forward method only works with internal views and it is not possible redirect to external URLs

The BeforeEnterEvent event object contains a reference to the UI. You could have something like

   event.getUI().getPage().open(someUrl, "_self");

Note that this will not prevent the view itself from being opened briefly - if you need to stop that from happening, you should reroute to a special route where the occurs.

HI @Olli Tietäväinen,

i have tried your code and worked but i want to avoid redirect the flow to another Vaadin view and go directly to my custom URL in this case, not sure if it approach is possible or not, maybe some workaround using servlets or the VaadinServiceInitListener.

Any advice is welcome :slight_smile:

Rene Garnica

Why do you want to avoid the redirect? The URL in the browser bar will stay the same if you use event.rerouteTo(). Another alternative would be to use a BeforeLeaveObserver instead of BeforeEnterObserver. Consider also that you can have these event handlers on the main layout instead of the child routes.