Skip to content

Instantly share code, notes, and snippets.

@maapteh
Last active January 28, 2022 06:28
Show Gist options
  • Save maapteh/ef9ba0ae55ce48b0be04250c558b39b8 to your computer and use it in GitHub Desktop.
Save maapteh/ef9ba0ae55ce48b0be04250c558b39b8 to your computer and use it in GitHub Desktop.
middleware user agent
// reason: package provided by our components library
// eslint-disable-next-line import/no-extraneous-dependencies
import MobileDetect from 'mobile-detect';
import { Viewport } from '@lib/types';
/** server-side script for guessing user Viewport if its Mobile/Tablet or others. This initial Viewport is used in our ViewportProvider which then runs the Viewport detection client-side */
export const getViewportFromUserAgent = (
userAgent: string | null
): Viewport.lg | Viewport.sm | Viewport.md => {
// corporate firewalls or users who like to stay unknown
if (!userAgent) {
return Viewport.lg;
}
const device = new MobileDetect(userAgent);
const isMobile = device.mobile();
const isTablet = device.tablet();
if (isMobile && !isTablet) {
// Our "xs" viewport is given for phones our Tenants do not really support since they are below the 5%, so our best bet is to handle phones like they are sm
return Viewport.sm;
}
if (isTablet) {
// we understand they can be rotated etc, once again best educated guess
return Viewport.md;
}
// we handle mobile first
return Viewport.sm;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment