Skip to content

Instantly share code, notes, and snippets.

@stephane-vanraes
Created May 3, 2022 11:34
Show Gist options
  • Save stephane-vanraes/fd693f8f789396c85b676e4a1ae6e32a to your computer and use it in GitHub Desktop.
Save stephane-vanraes/fd693f8f789396c85b676e4a1ae6e32a to your computer and use it in GitHub Desktop.
Prefers-Color-Scheme Client Hint and SvelteKit
/**
See https://wicg.github.io/user-preference-media-features-headers/ for more info on the Client Hint
This code will inform the server which color scheme the user prefers.
It can be used to apply to correct classes and prevent a flash of the wrong scheme during load.
*/
export async function handle({ event, resolve }) {
// Read the Color Scheme Client Hint
const colorScheme = event.request.headers.get('Sec-CH-Prefers-Color-Scheme')
if (!colorScheme) {
// If not present, send back that this server accepts the color scheme hint
const response = new Response('custom response');
response.headers.set('Accept-CH', 'Sec-CH-Prefers-Color-Scheme')
return response;
}
// Attach to locals so it can be read in getSession or whatever
event.locals.colorScheme = colorScheme;
// Usual stuff
const response = await resolve(event);
return response;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment