An open source design system that's fully customizable and agent ready
TypeScript
fix(Timestamp): never read the current time during a server render (#7883)
Joeyca48bb778953
diff --git a/.changeset/timestamp-server-clock.md b/.changeset/timestamp-server-clock.mdnew file mode 100644index 0000000000..257ca58b93--- /dev/null+++ b/.changeset/timestamp-server-clock.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Timestamp no longer reads the current time while rendering on the server. Absolute formats (`date`, `time`, `date_time` and the other fixed formats) never read the clock, so pages that use them prerender in Next.js with `cacheComponents` turned on, the default for new Next.js 16 apps, where they used to fail the build. `relative`, `relative_short` and `auto` read the clock on the client only: a server render or static prerender shows the full date and time in UTC, labelled, and the client switches to the format's normal output right after hydration, so server and client markup now always match. Client-only rendering is unchanged. No API changes.++@josephfarinadiff --git a/packages/core/src/Timestamp/Timestamp.doc.mjs b/packages/core/src/Timestamp/Timestamp.doc.mjsindex 00b29f5e15..2f13f18f4d 100644--- a/packages/core/src/Timestamp/Timestamp.doc.mjs+++ b/packages/core/src/Timestamp/Timestamp.doc.mjs@@ -28,7 +28,7 @@ export const docs = {name: 'format',type: "'relative' | 'relative_short' | 'auto' | 'date' | 'date_long' | 'date_weekday' | 'date_time' | 'time' | 'system_date' | 'system_date_time' | 'system_time' | 'unix_seconds'",description:- "Display format. 'relative' uses the locale's native long relative-time wording ('2 hours ago' in English), 'relative_short' uses its narrow pattern ('2h ago' in English) for compact surfaces, 'date' shows 'Mar 21, 2025', 'date_long' shows 'March 21, 2025', 'date_weekday' shows 'Wed, Mar 21, 2025', 'date_time' shows 'Mar 21, 2025, 2:51 PM', 'time' shows '2:51 PM', 'system_*' variants use ISO-style formatting, 'unix_seconds' shows the Unix time in whole seconds since the epoch (an absolute, zone-independent value), 'auto' switches from relative to date_time based on recency.",+ "Display format. 'relative' uses the locale's native long relative-time wording ('2 hours ago' in English), 'relative_short' uses its narrow pattern ('2h ago' in English) for compact surfaces, 'date' shows 'Mar 21, 2025', 'date_long' shows 'March 21, 2025', 'date_weekday' shows 'Wed, Mar 21, 2025', 'date_time' shows 'Mar 21, 2025, 2:51 PM', 'time' shows '2:51 PM', 'system_*' variants use ISO-style formatting, 'unix_seconds' shows the Unix time in whole seconds since the epoch (an absolute, zone-independent value), 'auto' switches from relative to date_time based on recency. Absolute formats never read the current time. 'relative', 'relative_short' and 'auto' read it on the client only: a server render or static prerender shows the full date and time in UTC, labelled, and the client switches to the format's normal output after hydration.",default: "'auto'",},{diff --git a/packages/core/src/Timestamp/Timestamp.test.tsx b/packages/core/src/Timestamp/Timestamp.test.tsxindex e9d722b46e..de1b623a51 100644--- a/packages/core/src/Timestamp/Timestamp.test.tsx+++ b/packages/core/src/Timestamp/Timestamp.test.tsx@@ -11,6 +11,9 @@ import {} from 'vitest';import {render, screen, act, waitFor, fireEvent} from '@testing-library/react';import userEvent from '@testing-library/user-event';+import {Profiler} from 'react';+import {hydrateRoot, type Root} from 'react-dom/client';+import {renderToString} from 'react-dom/server';import {Timestamp} from './Timestamp';import {formatInstant} from './formatInstant';import {formatTooltipLines} from './tooltipEntries';@@ -1466,3 +1469,168 @@ describe('Timestamp pass-through props', () => {});});});++/**+ * Counts `new Date()` calls with no argument (reads of the current time) made+ * while `run` executes.+ */+function countClockReads(run: () => void): number {+ const ActiveDate = globalThis.Date;+ let reads = 0;+ class CountingDate extends ActiveDate {+ constructor(...args: [] | [string | number | Date]) {+ if (args.length === 0) {+ reads += 1;+ }+ super(...(args as [string | number | Date]));+ }+ }+ globalThis.Date = CountingDate as DateConstructor;+ try {+ run();+ } finally {+ globalThis.Date = ActiveDate;+ }+ return reads;+}++describe('Timestamp server rendering', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2026-03-25T12:00:00Z'));+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it.each(['date', 'date_time', 'time', 'unix_seconds'] as const)(+ 'never reads the current time for the absolute %s format',+ format => {+ const element = (+ <Timestamp value="2026-03-25T10:00:00Z" format={format} />+ );+ expect(countClockReads(() => renderToString(element))).toBe(0);+ expect(countClockReads(() => render(element))).toBe(0);+ },+ );++ it.each(['relative', 'relative_short', 'auto'] as const)(+ 'renders the %s format as the full date and time in UTC on the server without reading the clock',+ format => {+ const value = '2026-03-25T10:00:00Z';+ let html = '';+ expect(+ countClockReads(() => {+ html = renderToString(<Timestamp value={value} format={format} />);+ }),+ ).toBe(0);+ const host = document.createElement('div');+ host.innerHTML = html;+ expect(host.textContent).toBe(+ formatInstant(new Date(value), 'date_time', 'en-US', {+ timeZone: 'UTC',+ isTimezoneShown: true,+ }),+ );+ },+ );++ it('never commits the UTC placeholder when a client Timestamp switches to a relative format', () => {+ const value = Date.now() / 1000 - 7200;+ const committed: string[] = [];+ function Spy({format}: {format: 'date' | 'relative'}) {+ return (+ <Profiler+ id="ts"+ onRender={() => {+ committed.push(document.querySelector('time')?.textContent ?? '');+ }}>+ <Timestamp value={value} format={format} hasTooltip={false} />+ </Profiler>+ );+ }+ const {rerender} = render(<Spy format="date" />);+ committed.length = 0;+ rerender(<Spy format="relative" />);+ expect(screen.getByText('2 hours ago')).toBeInTheDocument();+ expect(committed.some(text => text.includes('UTC'))).toBe(false);+ });++ describe('across time zones', () => {+ const originalTZ = process.env.TZ;++ afterEach(() => {+ if (originalTZ === undefined) {+ delete process.env.TZ;+ } else {+ process.env.TZ = originalTZ;+ }+ });++ it('writes the same server markup whatever the server time zone', () => {+ const element = (+ <Timestamp value="2026-03-25T10:00:00Z" format="relative" />+ );+ process.env.TZ = 'UTC';+ const utc = renderToString(element);+ process.env.TZ = 'Asia/Tokyo';+ expect(renderToString(element)).toBe(utc);+ });++ it('hydrates server markup from another time zone without a mismatch', () => {+ const value = Date.now() / 1000 - 7200;+ const element = (+ <Timestamp value={value} format="relative" hasTooltip={false} />+ );+ process.env.TZ = 'UTC';+ const host = document.createElement('div');+ document.body.appendChild(host);+ host.innerHTML = renderToString(element);++ process.env.TZ = 'America/Los_Angeles';+ const errors = vi.spyOn(console, 'error').mockImplementation(() => {});+ let root: Root | undefined;+ try {+ act(() => {+ root = hydrateRoot(host, element, {+ onRecoverableError: error => {+ throw error;+ },+ });+ });+ expect(host.textContent).toBe('2 hours ago');+ expect(errors).not.toHaveBeenCalled();+ } finally {+ errors.mockRestore();+ act(() => root?.unmount());+ host.remove();+ }+ });+ });++ it('hydrates the server markup without a mismatch, then shows the relative phrase', () => {+ const value = Date.now() / 1000 - 7200;+ const element = (+ <Timestamp value={value} format="relative" hasTooltip={false} />+ );+ const host = document.createElement('div');+ document.body.appendChild(host);+ host.innerHTML = renderToString(element);+ expect(host.textContent).not.toBe('2 hours ago');++ const errors = vi.spyOn(console, 'error').mockImplementation(() => {});+ let root: Root | undefined;+ try {+ act(() => {+ root = hydrateRoot(host, element);+ });+ expect(host.textContent).toBe('2 hours ago');+ expect(errors).not.toHaveBeenCalled();+ } finally {+ errors.mockRestore();+ act(() => root?.unmount());+ host.remove();+ }+ });+});diff --git a/packages/core/src/Timestamp/Timestamp.tsx b/packages/core/src/Timestamp/Timestamp.tsxindex 0e9fc46315..2f87e66d72 100644--- a/packages/core/src/Timestamp/Timestamp.tsx+++ b/packages/core/src/Timestamp/Timestamp.tsx@@ -17,7 +17,14 @@* - /packages/cli/assets/templates/blocks/components/Timestamp/ (showcase blocks)*/-import {lazy, Suspense, useEffect, useRef, useState} from 'react';+import {+ lazy,+ Suspense,+ useEffect,+ useRef,+ useState,+ useSyncExternalStore,+} from 'react';import * as stylex from '@stylexjs/stylex';import {Text} from '../Text';import type {TextType, TextSize, TextColor, TextWeight} from '../theme/types';@@ -215,6 +222,13 @@ function getLiveInterval(diffSeconds: number): number {return 300_000; // every 5 minutes}+// Whether this render may read the current time. Server renders (including+// static prerenders) and the hydration pass read `false`, so the markup never+// depends on when it was rendered; client renders read `true`.+const subscribeToNothing = () => () => {};+const canReadClockOnClient = () => true;+const canReadClockOnServer = () => false;+/** Whether a format is non-relative (i.e. shows a fixed date/time). */function isAbsoluteFormat(format: TimestampFormat,@@ -279,7 +293,29 @@ export function Timestamp({const locale = useLocale();const timeRef = useRef<HTMLTimeElement>(null);const mergedTimeRef = useMergedRefs(ref, timeRef);- const [now, setNow] = useState(() => new Date());+ // Only relative and auto formats depend on the current time. Absolute+ // formats never read the clock, so they render identically on the server,+ // in a static prerender, and on the client. A clock-dependent format reads+ // it on the client only: server renders and the hydration pass show the+ // full date and time in UTC, and the client switches to the relative phrase+ // right after hydration.+ const needsClock = !isAbsoluteFormat(format);+ const canReadClock = useSyncExternalStore(+ subscribeToNothing,+ canReadClockOnClient,+ canReadClockOnServer,+ );+ const [now, setNow] = useState<Date | null>(() =>+ needsClock && canReadClock ? new Date() : null,+ );+ // Read the clock during render once it may be read: after hydration (the+ // store re-renders with its client value) and when `format` switches from+ // an absolute value to a clock-dependent one, so the placeholder never+ // commits on the client.+ if (needsClock && canReadClock && now === null) {+ // eslint-disable-next-line @eslint-react/purity -- seeds clock state once, like the initializer; never runs on the server or while hydrating+ setNow(new Date());+ }const date = parseValue(value);// An unparseable value (a malformed date string, or a NaN timestamp from@@ -289,25 +325,40 @@ export function Timestamp({const isValidDate = !Number.isNaN(date.getTime());const isoString = isValidDate ? date.toISOString() : '';- // Determine effective format- const diffSeconds = Math.round((now.getTime() - date.getTime()) / 1000);- const effectiveFormat: TimestampFormat =- format === 'auto'+ // Determine effective format. Until the clock is read, a clock-dependent+ // format renders as the full date and time.+ const isClockPending = needsClock && now === null;+ const diffSeconds =+ now === null ? 0 : Math.round((now.getTime() - date.getTime()) / 1000);+ const effectiveFormat: TimestampFormat = isClockPending+ ? 'date_time'+ : format === 'auto'? Math.abs(diffSeconds) <= autoThreshold? 'relative': 'date_time': format;- // Format the display text. No time zone is passed: the visible text always- // reads in the viewer's own zone, and only the tooltip names others.+ // Format the display text in the viewer's own zone; only the tooltip names+ // others. The one exception is the pre-hydration placeholder, written in+ // UTC with its label so every zone produces the same markup.const displayText = !isValidDate? '': effectiveFormat === 'relative'- ? formatRelativeTime(date, now, locale, 'long')+ ? formatRelativeTime(date, now ?? date, locale, 'long'): effectiveFormat === 'relative_short'- ? formatRelativeTime(date, now, locale, 'narrow')+ ? formatRelativeTime(date, now ?? date, locale, 'narrow'): isAbsoluteFormat(effectiveFormat)- ? formatInstant(date, effectiveFormat, locale, {isTimezoneShown})+ ? formatInstant(+ date,+ effectiveFormat,+ locale,+ // The pre-hydration placeholder is written in UTC, labelled, so+ // the server and the hydrating client produce the same text in+ // every time zone.+ isClockPending+ ? {timeZone: 'UTC', isTimezoneShown: true}+ : {isTimezoneShown},+ ): '';// Full absolute text for the tooltip (visible — keeps the compact timezone