Skip to content

Add CookieLocaleContextResolver to Spring WebFlux for cookie-based locale persistence #36569

@husseinvr97

Description

@husseinvr97

Problem

Consider a multilingual WebFlux application where users can explicitly switch their language via a UI control (e.g. clicking "العربية" or "English"). The application needs to remember that choice across requests without requiring
a user session.

Spring MVC provides CookieLocaleResolver for persisting a user's locale preference across requests via a cookie. The WebFlux reactive stack currently only offers:

  • AcceptHeaderLocaleContextResolver — reads from the Accept-Language header (cannot be changed programmatically)
  • FixedLocaleContextResolver — uses a fixed configured locale

Neither supports persisting a user's explicit locale choice across requests. The LocaleContextResolver interface already defines setLocaleContext() for exactly this purpose, and AcceptHeaderLocaleContextResolver even hints
at it in its error message: "use a different locale context resolution strategy".

@Override
	public void setLocaleContext(ServerWebExchange exchange, @Nullable LocaleContext locale) {
		throw new UnsupportedOperationException(
				"Cannot change HTTP accept header - use a different locale context resolution strategy");
	}

Proposed Solution

Add CookieLocaleContextResolver in org.springframework.web.server.i18n, implementing LocaleContextResolver directly (following the same pattern as AcceptHeaderLocaleContextResolver and FixedLocaleContextResolver).

The implementation would:

  • Read the locale from a cookie via ServerWebExchange.getRequest().getCookies()
  • Write the locale cookie via ServerWebExchange.getResponse().addCookie(ResponseCookie)
  • Cache the resolved locale in exchange attributes to avoid re-parsing per request
  • Expose the same configurable cookie properties as CookieLocaleResolver: name, maxAge, path, domain, secure, httpOnly, sameSite
  • Support locale + timezone combined in one cookie value (same format as the MVC version)
  • Fall back to a configurable default locale when no cookie is present

Since ResponseCookie is already used throughout WebFlux, no new dependencies are needed — this is purely a feature parity gap.

I am happy to submit a PR if this direction looks right.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions