Skip to content

Instantly share code, notes, and snippets.

@philwolstenholme
Created September 28, 2025 14:28
Show Gist options
  • Select an option

  • Save philwolstenholme/fff89398fd02f0032859c9a3a60cfc94 to your computer and use it in GitHub Desktop.

Select an option

Save philwolstenholme/fff89398fd02f0032859c9a3a60cfc94 to your computer and use it in GitHub Desktop.
import { UAParser } from "ua-parser-js";
/**
* Uses the `Sec-CH-UA-Mobile` header if it's available to work out how many
* items to show per page.
*/
export const getItemsPerPage = ({
astroRequest,
mobileItemsPerPage = 5,
desktopItemsPerPage = 12,
}: {
astroRequest?: Request;
mobileItemsPerPage?: number;
desktopItemsPerPage?: number;
}) => {
if (!astroRequest) {
return desktopItemsPerPage;
}
// Prefer client hints if available.
const clientHintMobile = astroRequest.headers.get("Sec-CH-UA-Mobile");
if (clientHintMobile) {
return clientHintMobile === "?1" ? mobileItemsPerPage : desktopItemsPerPage;
}
// User agent sniff if we must.
const userAgent = astroRequest.headers.get("User-Agent");
if (userAgent) {
const { device } = UAParser(userAgent);
const smallScreenDeviceTypes: (typeof device.type)[] = [
"mobile",
"tablet",
"wearable",
];
return smallScreenDeviceTypes.includes(device.type)
? mobileItemsPerPage
: desktopItemsPerPage;
}
return desktopItemsPerPage;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment