Set locale from langauge stored in cookie before loading pages

When a user select a language in my app, the language is stored in a cookie, to remember the language the next session.

But where/when is it appropriate to read the cookie and set the language when starting a new session - such that is set before any page is loaded (e.g. login page, about page, etc)?

The simplest would be to read the cookie in the BeforeEnterObserver.beforeEnter in every view.

You can create a base class that implements that code for your views.

Then you don’t have to care if it’s already set or not.

In my example app I do it in afterNavigation of the login view.

The same app provides you example how to persist the selected language to cookie as well using request handler.

I’m usually doing this, if you’re using Spring Boot:

@Component
public class ApplicationFormBaseUIInitializer implements VaadinServiceInitListener {

    @Override
    public void serviceInit(ServiceInitEvent event) {
        event.addIndexHtmlRequestListener(indexHtmlResponse -> {
            String lang = readCookie(indexHtmlResponse.getVaadinRequest().getCookies(), "locale").orElse("de-DE");
            Locale locale = Locale.forLanguageTag(lang);
            indexHtmlResponse.getDocument().getElementsByTag("html")
                    .attr("lang", locale.getLanguage());

            VaadinSession.getCurrent().setLocale(locale);
        });
    }

    public Optional<String> readCookie(Cookie[] cookies, String key) {
        if (cookies == null) {
            return Optional.empty();
        }
        return Arrays.stream(cookies)
                .filter(c -> key.equals(c.getName()))
                .map(Cookie::getValue)
                .findFirst();
    }
}

It will be set the correct html tag from the cookie and set the locale of the Vaadin session. (see the open ticket here: Lang attribute on the html tag is not in sync with the UI locale · Issue #18585 · vaadin/flow · GitHub )

I do indeed. This looks pretty neat. I’ll try it out