nuxt-time-zone
nuxt-time-zone

The visitor's time zone, the same on the server and the client, with no hydration mismatches on dates.

nuxt-time-zone

CI npm version for Nuxt 4.6+ license: MIT

The visitor's time zone, the same on the server and the client. No hydration mismatches on dates.

Install

Requires Nuxt 4.6 or later.

npx nuxi module add nuxt-time-zone
// nuxt.config.ts
export default defineNuxtConfig({
  modules: ['nuxt-time-zone'],
})

Usage

// app
const timeZone = useTimeZone() // Readonly<Ref<string>>, e.g. 'Europe/Madrid'

// server
const timeZone = getRequestTimeZone(event) // 'Europe/Madrid'
const timeZone = getRequestTimeZone(event, body.timeZone) // the zone the page sent, when it is valid

Both are auto-imported. They agree while the server renders a page. Later API calls read the cookie again, see Caveats.

Options

timeZone: {
  cookieName: 'tz', // cookie that carries the zone
  fallback: 'UTC', // zone when there is no valid cookie
}

How it works

  1. The server renders with the zone from the tz cookie, or fallback, and writes it to <html data-time-zone>.
  2. A script at the top of <head> compares it with the device's zone.
  3. If they differ, it sets the cookie and reloads before anything paints.
  4. The client hydrates with the zone the server used.

No reload on prerendered, ssr: false or POST pages, when cookies are blocked, or after 3 reloads in a row.

Caveats

  • Cached HTML serves one zone to everyone. Don't cache pages with dates, or vary the cache on Cookie.
  • The API can disagree with the page. getRequestTimeZone reads each request's cookie. On a prerendered or cached page, when the cookie is blocked, or after another tab changes it, it can return another zone than useTimeZone(). When they must agree, send useTimeZone().value with the request and read it with getRequestTimeZone(event, body.timeZone). An invalid zone falls back to the cookie.
  • Safari expires the cookie after 7 days, so the next visit reloads once.
  • Strict CSP must allow the inline head script, by hash or nonce.

Tests

18 scenarios in SPEC.md, each a Playwright test in Chromium and WebKit.

Credit

Based on Daniel Roe's <NuxtTime>. Reload guards from @epic-web/client-hints.

Develop

pnpm install
pnpm dev:prepare
pnpm dev
pnpm check && pnpm typecheck && pnpm exec vp run check:doctor
pnpm build:playground && pnpm test:e2e

License

MIT