Design flaw in BeforeEnterObserver ?

I’m trying to work out if flow has a design flaw in the beforeEnter mechanism or if I’ve mis-understood the approach.

I have a set of routable components (views in the vaadin 8 nomenclature).

These routeable components all assume that the user is currently logged in and display information about the user.

All of these components share a common parent layout e.g.

@Route(value = "", layout = MainLayout.class)
public class HomePage extends PolymerTemplate<HomePage.HomePageModel>

Now my assumption was that I could simply put a ‘BeforeEnterObserver’ in the Mainlayout and check if the user was logged in.
If the user isn’t logged then I would take them to the login page.

All sounds good.

The problem is that the constructor of my HomePage class builds the ui and attempts to get the current user as part of that process.

I had assumed that the BeforeEnter event would fire before the HomePage was created.
It turns out that the HomePage constructor is called before the BeforeEnter event is fired.

The result is that my HomePage class is throwing an NPE because the current user object hasn’t been initialised.

This appears to make the BeforeEnter event less than useful for re-routing a user to a login page.

Instead it would appear that every view must start by checking if they are logged in.
This is certainly possible makes for tedious and error prone work.

It would appear to me that we need one of the following:

  1. don’t call the contstructor of the target view until after the BeforeEnter event is fired
  2. provide an entry point e.g. ‘enter()’ where we can do our view construction knowing that BeforeEnter event has already fired and we can reasonably assume that the user is logged in.
  3. document the fact that the constructor is called before ‘BeforeEnter’ as I had to trace though vaadin code to work this out.

So have I mis-understood the design intent?

FYI: I’m running vaadin 12.

  1. provide an entry point e.g. ‘enter()’ where we can do our view construction knowing that BeforeEnter event has already fired and we can reasonably assume that the user is logged in.

I think there is exactly what you are looking for, and it is the AfterNavigationObserver, which is called if you are not kicking user to other view in BeforeEnter.

https://vaadin.com/api/platform/12.0.7/com/vaadin/flow/router/AfterNavigationObserver.html

  1. document the fact that the constructor is called before ‘BeforeEnter’ as I had to trace though vaadin code to work this out.

Thanks for stressing this out, we need to check where in documentation to put it.

Any progress on this yet?

In Vaadin 14.2 there will be some change in how the Routing events are triggered, see here: https://github.com/vaadin/flow/pull/7130