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.
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 validBoth 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
- The server renders with the zone from the
tzcookie, orfallback, and writes it to<html data-time-zone>. - A script at the top of
<head>compares it with the device's zone. - If they differ, it sets the cookie and reloads before anything paints.
- 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.
getRequestTimeZonereads 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 thanuseTimeZone(). When they must agree, senduseTimeZone().valuewith the request and read it withgetRequestTimeZone(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