npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@epic-web/client-hints

v1.3.5

Published

Server-render browser-based user preferences (like theme preference and timezone).

Downloads

56,355

Readme

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