Skip to content

cookie was modified before the i18n:beforeLocaleSwitch hook was triggered #3819

@Ercilan

Description

@Ercilan

Environment


  • Operating System: Windows_NT
  • Node Version: v22.17.0
  • Nuxt Version: 4.1.2
  • CLI Version: 3.28.0
  • Nitro Version: 2.12.6
  • Package Manager: pnpm@9.15.9
  • Builder: -
  • User Config: compatibilityDate, devtools, typescript, runtimeConfig, imports, hooks, nitro, routeRules, modules, app, i18n, linkChecker, seo, site, robots, sitemap, ogImage, pwa, css, build, experimental, devServer, vite
  • Runtime Modules: @nuxt/eslint@1.9.0, @nuxtjs/i18n@10.1.0, @vueuse/nuxt@13.9.0, @nuxtjs/seo@3.1.0, @pinia/nuxt@0.11.2, ./modules/pwa-i18n, @vite-pwa/nuxt@1.0.4
  • Build Modules: -

Reproduction

Not sure about the reason. On StackBlitz, npm i throws the error ERROR Cannot find native binding. npm has a bug related to optional dependencies (https://github.com/npm/cli/issues/4828). On CodeSandbox, it gets stuck at Resuming MicroVM... Still booting, please wait.

Describe the bug

my config: ssg

strategy: "prefix_except_default",
detectBrowserLanguage: {
  useCookie: true,
  cookieKey: "app-locale",
  redirectOn: "root",
  alwaysRedirect: false,
},

I have a page that users can share via its link.
To prevent other users from being forced to switch languages when visiting this URL,
I tried adding a query parameter and then checking for its presence in the i18n:beforeLocaleSwitch hook when the page is accessed.
The idea was to prioritize using the user’s existing cookie language to avoid forcing a language change.

However, in my tests I found that when directly opening that URL, by the time this hook is triggered, the browser’s cookie has already been updated to the language from the URL, so I don’t have a chance to retrieve the user’s previously set language.


  • In addition, if redirectOn could be configured as a function, wouldn’t it be much easier to implement my requirement?

  • The comment for the alwaysRedirect option in the code says: Always redirect to the detected locale, not just on first visit, which doesn’t match the documentation for alwaysRedirect. This initially confused me about its relationship with redirectOn: "all".
    My current understanding is(is this right?):

    • alwaysRedirect: whether to always force a redirect to the language stored in the cookie.

    • redirectOn: under what circumstances to redirect to the language detected by detectBrowserLanguage (including the language in the route? and with the route language having higher priority?).

Additional context

No response

Logs

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions