use-breakpoint-agent
Version:
A React hook to detect device type based on screen width
18 lines (17 loc) • 729 B
JavaScript
import { UAParser } from "ua-parser-js";
import { DeviceEnum } from "../types/index.js";
export function getDeviceTypeFromHeaders(headers) {
var _a;
if (typeof window !== "undefined") {
throw new Error("use-breakpoint-agent/server cannot be used on the client side");
}
let agent = headers instanceof Headers ? headers.get("user-agent") : headers["user-agent"];
agent = Array.isArray(agent) ? agent[0] : agent;
const data = UAParser(agent || undefined);
const device = (_a = data.device) === null || _a === void 0 ? void 0 : _a.type;
if (device === "mobile")
return DeviceEnum.MOBILE;
if (device === "tablet")
return DeviceEnum.TABLET;
return DeviceEnum.DESKTOP;
}