Device detection module for Nuxt applications that identifies device types, operating systems, browsers, and crawlers through server-side and client-side detection
npx @tessl/cli install tessl/npm-nuxtjs--device@3.2.0Nuxt Device is a TypeScript-based module that provides comprehensive device detection capabilities for Nuxt.js applications. It identifies device types (desktop, mobile, tablet), operating systems (iOS, Android, Windows, macOS), browsers (Chrome, Safari, Firefox, Edge), and web crawlers through both server-side rendering and client-side hydration. The module supports enhanced detection via CDN services like Amazon CloudFront and Cloudflare.
npx nuxi@latest module add deviceimport { useDevice } from '#imports';The module also provides global access via $device in templates and throughout the Nuxt application.
<template>
<div>
<div v-if="$device.isDesktop">Desktop View</div>
<div v-else-if="$device.isTablet">Tablet View</div>
<div v-else>Mobile View</div>
<p>User Agent: {{ $device.userAgent }}</p>
<p>Browser: {{ $device.isChrome ? 'Chrome' : 'Other' }}</p>
</div>
</template>
<script setup>
const { isMobile, isIos, isAndroid } = useDevice();
if (isMobile) {
console.log('Mobile device detected');
}
</script>Nuxt Device operates through several key components:
useDevice()$device object throughout the applicationThe primary API for accessing device information in Vue components using the composition API.
/**
* Vue composable that provides device detection information
* @returns Device object with all detection flags and user agent
*/
function useDevice(): Device;
/**
* Core device detection function for server-side usage
* @param userAgent - User agent string to analyze
* @param headers - Optional HTTP headers for CDN detection
* @returns Device object with all detection flags
*/
function generateFlags(userAgent: string, headers?: Record<string, string>): Device;Device information is available globally throughout the Nuxt application via the $device property.
/**
* Global device object available in templates, plugins, and throughout Nuxt app
* Accessible as this.$device in options API or $device in templates
*/
declare global {
interface NuxtApp {
$device: Device;
}
interface ComponentCustomProperties {
$device: Device;
}
}Configure the device detection module behavior.
/**
* Configuration options for @nuxtjs/device module
*/
interface ModuleOptions {
/**
* Sets the default value for the user-agent header (useful when running npm run generate)
* @default 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.39 Safari/537.36'
*/
defaultUserAgent?: string;
/**
* @deprecated This option will be removed in the next major release
*/
enabled?: boolean;
/**
* @deprecated This option will be removed in the next major release
*/
refreshOnResize?: boolean;
}Configuration Example:
// nuxt.config.ts
export default defineNuxtConfig({
modules: ['@nuxtjs/device'],
device: {
defaultUserAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
});Complete device detection information with all supported flags and properties.
/**
* Complete device detection information object
*/
interface Device {
/** Original user agent string */
userAgent: string;
/** True if desktop device (not mobile or tablet) */
isDesktop: boolean;
/** True if iOS device (iPhone, iPad, iPod) */
isIos: boolean;
/** True if Android device */
isAndroid: boolean;
/** True if mobile device (phone) */
isMobile: boolean;
/** True if mobile phone or tablet */
isMobileOrTablet: boolean;
/** True if desktop or tablet (not mobile phone) */
isDesktopOrTablet: boolean;
/** True if tablet device */
isTablet: boolean;
/** True if Windows operating system */
isWindows: boolean;
/** True if macOS operating system */
isMacOS: boolean;
/** True if Apple device (iOS or macOS) */
isApple: boolean;
/** True if Safari browser */
isSafari: boolean;
/** True if Firefox browser */
isFirefox: boolean;
/** True if Edge browser */
isEdge: boolean;
/** True if Chrome browser */
isChrome: boolean;
/** True if Samsung browser */
isSamsung: boolean;
/** True if web crawler/bot (powered by crawler-user-agents) */
isCrawler: boolean;
}Enhanced device detection using CDN-provided headers for improved performance and accuracy.
Amazon CloudFront Support:
When the user agent is Amazon CloudFront, the module automatically detects these headers:
cloudfront-is-mobile-viewer: Sets isMobile and isMobileOrTablet flagscloudfront-is-tablet-viewer: Sets isTablet and isMobileOrTablet flagscloudfront-is-desktop-viewer: Sets isDesktop flagcloudfront-is-ios-viewer: Sets isIos flagcloudfront-is-android-viewer: Sets isAndroid flagCloudflare Support:
The module detects the CF-Device-Type header with values:
mobile: Sets mobile device flagstablet: Sets tablet device flagsdesktop: Sets desktop device flagsUsage with CDN:
// The detection happens automatically when CDN headers are present
// No additional configuration required
const { isTablet, isMobile } = useDevice();
// CDN detection takes precedence over user agent parsing
if (isTablet) {
// This could be set by cloudfront-is-tablet-viewer header
// or by Cloudflare cf-device-type: tablet header
}The module provides several advanced integration patterns for complex applications.
Plugin Extension:
// plugins/device-analytics.ts
export default defineNuxtPlugin((nuxtApp) => {
const { $device } = nuxtApp;
// Track device analytics
if (!$device.isCrawler) {
analytics.track('device_type', {
isMobile: $device.isMobile,
isTablet: $device.isTablet,
browser: $device.isChrome ? 'chrome' :
$device.isSafari ? 'safari' :
$device.isFirefox ? 'firefox' : 'other'
});
}
});Middleware Integration:
// middleware/device-redirect.ts
export default defineNuxtRouteMiddleware((to) => {
const { $device } = useNuxtApp();
// Redirect mobile users to mobile-optimized routes
if ($device.isMobile && !to.path.startsWith('/mobile')) {
return navigateTo('/mobile' + to.path);
}
});Server-Side API Usage:
// server/api/device-info.ts
export default defineEventHandler(async (event) => {
const device = await generateFlags(
getHeader(event, 'user-agent') || '',
getHeaders(event)
);
return {
deviceType: device.isMobile ? 'mobile' :
device.isTablet ? 'tablet' : 'desktop',
platform: device.isIos ? 'ios' :
device.isAndroid ? 'android' : 'other'
};
});Common patterns for responsive design and device-specific functionality.
Layout Selection:
<template>
<NuxtLayout :name="$device.isMobile ? 'mobile' : 'default'">
<!-- page content -->
</NuxtLayout>
</template>
<script setup>
definePageMeta({
layout: false
});
</script>Progressive Enhancement:
<template>
<div>
<!-- Show simplified interface for mobile -->
<MobileNavigation v-if="$device.isMobile" />
<!-- Show full interface for desktop/tablet -->
<DesktopNavigation v-else />
<!-- Browser-specific optimizations -->
<VideoPlayer
:use-hardware-acceleration="$device.isChrome"
:fallback-format="$device.isSafari ? 'mp4' : 'webm'"
/>
</div>
</template>Crawler Detection:
<template>
<div>
<!-- Skip heavy JavaScript for crawlers -->
<StaticContent v-if="$device.isCrawler" />
<InteractiveContent v-else />
</div>
</template>The module extends Nuxt's runtime configuration for server-side and client-side access.
/**
* Device configuration in Nuxt runtime config
*/
declare module '@nuxt/schema' {
interface PublicRuntimeConfig {
device: Required<ModuleOptions>;
}
}Accessing Runtime Config:
// In plugins, middleware, or composables
const config = useRuntimeConfig();
const defaultUserAgent = config.public.device.defaultUserAgent;The module gracefully handles various edge cases and provides fallback behavior:
defaultUserAgent when no user agent is available