epic-stack icon indicating copy to clipboard operation
epic-stack copied to clipboard

Implement client preference cookies

Open kentcdodds opened this issue 1 year ago • 2 comments

We need to implement this decision: https://github.com/epicweb-dev/epic-stack/blob/main/decisions/05-client-pref-cookies.md

Any takers?

kentcdodds avatar May 17 '23 02:05 kentcdodds

If the only thing the app needs to do is display the current date or time, then it's fine to just put the client's UTC offset (what you can get from new new Date().getTimezoneOffset()) in the cookie.

But the offset isn't enough if you need to do more complicated things, like derive new date/time values like "tomorrow at 9AM" or "how many hours of server time do I have to pay for between now and next Friday at midnight?" because there might be a DST transition in between.

To get the time zone ID on the client, it's easy: new Intl.DateTimeFormat().resolvedOptions().timeZone.

But actually using the ID (creating date/time values with it, adding/subtracting, etc.) requires more code. Possibilities:

  • Temporal, after it's natively available (probably on track for late 2023 or early 2024)
  • A Temporal polyfill. Disclosure: I'm one of the champions of the Temporal proposal and a maintainer of one of those polyfills.
  • Another library like day.js or date-fns-tz.

Also: the client's time zone can change if the client is a mobile device or laptop and the user is moving between time zones, e.g. on a plane. So a persistent cookie can get stale. The client should refresh the cookie periodically, and/or before doing some time-zone-sensitive thing, like showing a meeting reminder.

justingrant avatar May 19 '23 00:05 justingrant

Thanks @justingrant,

I think the implementation I have so far handles these cases as far as we need to in the starter code: #64

kentcdodds avatar May 19 '23 17:05 kentcdodds

I created an example that adds a time zone client hint. It also includes a helper function for formatting dates using the Intl.DateTimeFormat object, so everything uses native browser APIs.

https://github.com/kiliman/epic-stack-time-zone

kiliman avatar Jul 10 '23 13:07 kiliman