Giter VIP home page Giter VIP logo

client-hints's Introduction

Eliminate a flash of incorrect content by using client hints

Detect the user's device preferences (like time zone and color scheme) and send them to the server so you can server render the correct content for them.

npm install @epic-web/client-hints

Build Status MIT License Code of Conduct

The Problem

Sometimes your server rendered code needs to know something about the client that the browser doesn't send. For example, the server might need to know the user's preferred language, or whether the user prefers light or dark mode.

For some of this you should have user preferences which can be persisted in a cookie or a database, but you can't do this for first-time visitors. All you can do is guess. Unfortunately, if you guess wrong, you end up with a bad experience for the user.

And what often happens is we render HTML that's wrong and then hydrate the application to be interactive with client-side JavaScript that now knows the user preferences and now we know the right thing to render. This is great, except we've already rendered the wrong thing so by hydrating we cause a shift from the wrong thing to the right thing which is jarring and can be even a worse user experience than leaving the wrong thing in place (I call this a "flash of incorrect content"). You'll get an error in the console from React when this happens for this reason.

The Solution

Client hints are a way to avoid this problem. The standard for this is still a work in progress and there is uncertainty when they will land in all major browsers we are concerned with supporting. So this is a "ponyfill" of sorts of a similar feature to the client hints headers proposed to the standard.

The idea behind the standard is when the browser makes a request, instead of responding to the request immediately, the server instead responds to the client informing it there's a need for certain headers. The client will then repeat the request with those headers added. The server can then respond with the correct content.

Our solution is inspired by this, but instead of headers we use cookies (which can actually have a few benefits over headers). The idea is to render some JavaScript at the top of the <head> of our document before anything else. It's a small and fast inline script which checks the user's cookies for the expected client hints. If they are not present or if they're outdated, it sets a cookie and triggers a reload of the page. Effectively doing the same thing the browser would do with the client hints headers.

This allows us to server render the right thing for first time visitors without triggering a content layout shift or a flash of incorrect content. After that first render, the client will have the correct cookies and the server will render the right thing every time thereafter.

Watch the tip on EpicWeb.dev:

Kent smiling with VSCode showing code in the client-hints.tsx file

Usage

This is how @epic-web/client-hints is used in the Epic Stack:

import { getHintUtils } from '@epic-web/client-hints'
import {
	clientHint as colorSchemeHint,
	subscribeToSchemeChange,
} from '@epic-web/client-hints/color-scheme'
import { clientHint as timeZoneHint } from '@epic-web/client-hints/time-zone'
import { useRevalidator } from '@remix-run/react'
import * as React from 'react'
import { useRequestInfo } from './request-info.ts'

const hintsUtils = getHintUtils({
	theme: colorSchemeHint,
	timeZone: timeZoneHint,
	// add other hints here
})

export const { getHints } = hintsUtils

export function useHints() {
	const requestInfo = useRequestInfo()
	return requestInfo.hints
}

export function ClientHintCheck({ nonce }: { nonce: string }) {
	const { revalidate } = useRevalidator()
	React.useEffect(
		() => subscribeToSchemeChange(() => revalidate()),
		[revalidate],
	)

	return (
		<script
			nonce={nonce}
			dangerouslySetInnerHTML={{
				__html: hintsUtils.getClientHintCheckScript(),
			}}
		/>
	)
}

And then the server-side code in the root loader (what powers the useRequestInfo hook) looks like this:

export async function loader({ request }: DataFunctionArgs) {
	return json({
		// other stuff here...
		requestInfo: {
			hints: getHints(request),
		},
	})
}

Hints include:

  • @epic-web/client-hints/color-scheme (also exports subscribeToSchemeChange)
  • @epic-web/client-hints/time-zone
  • @epic-web/client-hints/reduced-motion (also exports subscribeToMotionChange)

FAQ

Customize cookie name

If you wish to customize the cookie name, you can simply override it like so:

const hintsUtils = getHintUtils({
	theme: {
		...colorSchemeHint,
		cookieName: 'my-custom-cookie-name',
	},
})

If you're using one of the subscribeTo*Change functions, you'll need to pass your custom cookie name to those as well.

Custom Hints

If you have anything custom you'd like to detect, hints are actually pretty simple. Here's the code for the timezone hint:

import { type ClientHint } from '@epic-web/client-hints'

export const clientHint = {
	cookieName: 'CH-time-zone',
	getValueCode: 'Intl.DateTimeFormat().resolvedOptions().timeZone',
	fallback: 'UTC',
} as const satisfies ClientHint<string>

If you need to transform the value for some reason (like change it from a string to a boolean etc.) then you can use the transform method. Here's how the color scheme hint uses that:

import { type ClientHint } from '@epic-web/client-hints'

export const clientHint = {
	cookieName: 'CH-prefers-color-scheme',
	getValueCode: `window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'`,
	fallback: 'light',
	transform(value) {
		return value === 'dark' ? 'dark' : 'light'
	},
} as const satisfies ClientHint<'dark' | 'light'>

The benefit of doing this is the types for the hint will only ever be 'dark' | 'light' and not string.

License

MIT

client-hints's People

Contributors

canrau avatar cevr avatar gonstoll avatar kentcdodds avatar muhammadjalabi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

client-hints's Issues

Seeing comma separated timezones

In some rare instances, we have seen users timezones set to a comma separated string of timezones, which looked like this:
'America/New_York,America/New_York'. I'm wondering if this could be a bug in the library or related to users browsers, or manual intervention potentially?

Client Hints Break Traffic Channel Attribution

Related: epicweb-dev/epic-stack#580 (comment)

I had migrated from a simple stack on Vercel to the Epic Stack on Fly (โค๏ธ love it) and had assumed I had some redirect breaking channel attribution in GA and spun out on that for a while.

Last week I was looking thru the client hints code and had an A-ha seeing the window.location.reload(); in there. A page reload sets the page referrer to the current page and since client-hinds runs inline at the top of the document, it runs before any analytics does. In the chart below you can see my direct traffic goes to normal levels after I removed the client hint code.

For my site, assuming many others, understanding attribution as accurately as possible is important for verifying success of paid campaigns, social media, emails etc. We should probably document this trade-off and maybe offer some sort of opt-in or manual handle of reload on cookie diff to preserve referrer?

image

Add explicit extension to all imports

That's necessary for full compatibility with ESM in TypeScript when using "moduleResolution": "NodeNext".

When the import doesn't have the extension, TypeScript can't properly resolve it:
image

After I manually add the extension, you can see now it resolves correctly:
image

TypeScript doesn't modify the paths used in the imports when compiling, so it's really a matter of adding the extension to all imports in the source code.

Add a locale hint

Sorry for opening an issue for this, it's not really an issue. I didn't find the discussions tab, so I created this issue to ask if you're open to adding more hints. If you are, then I'd like to contribute one for the user's locale.

Type information lost on JsonifyObject (?)

Hello!

I have a project using epic-stack and I decided to apply the same changes as epicweb-dev/epic-stack@d312d7b and epicweb-dev/epic-stack@ae3f66a to start using @epic-web/client-hints.

However, upon doing the change, @typescript-eslint started to complain about unsafe assignments due to hints being of type any, even though VSCode is saying getHints returns ClientHintsValue<Hints>.
image

The difference to the pre-@epic-web/client-hints usage is that getHints used to return a simple object:
image

Looking into getHints, the implementation is the same in both versions, but what changes are the type definitions:
Before

{
      [name in ClientHintNames]: (typeof clientHints)[name] extends {
        transform: (value: string) => infer ReturnValue;
      }
        ? ReturnValue
        : (typeof clientHints)[name]["fallback"];
},

After

Hints extends Record<string, ClientHint<any>>

After a lot of searching, I think this is the same issue as reported by Kent here: sindresorhus/type-fest#667
The referenced workaround is to change from any to unknown but I'm not sure if that's enough, as I tried to manually change the .d.ts file in node_modules and it didn't work.

How to reproduce

  1. Create a new project using epic-stack: npx create-epic-app@latest
  2. Add some reference to requestInfo.hints in app/utils/request-info.ts, such as console.log(data.requestInfo.hints)
  3. hints is recognized as any in VSCode even though it has the correct type passed into JsonifyObject
image image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.