or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-nuxtjs--device

Device detection module for Nuxt applications that identifies device types, operating systems, browsers, and crawlers through server-side and client-side detection

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@nuxtjs/device@3.2.x

To install, run

npx @tessl/cli install tessl/npm-nuxtjs--device@3.2.0

index.mddocs/

Nuxt Device

Nuxt 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.

Package Information

  • Package Name: @nuxtjs/device
  • Package Type: npm
  • Language: TypeScript
  • Installation: npx nuxi@latest module add device

Core Imports

import { useDevice } from '#imports';

The module also provides global access via $device in templates and throughout the Nuxt application.

Basic Usage

<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>

Architecture

Nuxt Device operates through several key components:

  • Nuxt Module: Integrates device detection into the Nuxt build and runtime system
  • Device Detection Engine: Core logic for analyzing user agents and CDN headers
  • Composable API: Vue composition API integration via useDevice()
  • Global Plugin: Provides $device object throughout the application
  • Type System: Complete TypeScript definitions for all device properties
  • CDN Integration: Enhanced detection using CloudFront and Cloudflare headers

Capabilities

Device Detection Composable

The 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;

Global Device Object

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;
  }
}

Module Configuration

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'
  }
});

Device Information Interface

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;
}

CDN Integration

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 flags
  • cloudfront-is-tablet-viewer: Sets isTablet and isMobileOrTablet flags
  • cloudfront-is-desktop-viewer: Sets isDesktop flag
  • cloudfront-is-ios-viewer: Sets isIos flag
  • cloudfront-is-android-viewer: Sets isAndroid flag

Cloudflare Support:

The module detects the CF-Device-Type header with values:

  • mobile: Sets mobile device flags
  • tablet: Sets tablet device flags
  • desktop: Sets desktop device flags

Usage 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
}

Advanced Integration Patterns

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'
  };
});

Conditional Rendering Patterns

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>

Runtime Configuration

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;

Error Handling and Edge Cases

The module gracefully handles various edge cases and provides fallback behavior:

  • Missing User Agent: Falls back to the configured defaultUserAgent when no user agent is available
  • Malformed Headers: Invalid CDN headers are ignored, falling back to user agent parsing
  • Server-Client Hydration: Device flags are computed server-side and hydrated on the client without conflicts
  • Unknown Devices: Unrecognized devices default to desktop with appropriate fallback flags

Performance Considerations

  • Zero Runtime Dependencies: No external libraries loaded on the client side
  • Server-Side Detection: Device flags are computed during SSR, reducing client-side computation
  • Static Analysis: User agent parsing uses optimized regular expressions for fast detection
  • CDN Integration: When available, CDN headers provide faster detection than user agent parsing
  • Lazy Evaluation: Device flags are computed once per request and cached throughout the application lifecycle