### Template and Script Setup Usage Source: https://github.com/nuxt-modules/device/blob/main/README.md Demonstrates how to use the $device helper in the template and the useDevice composable in script setup to conditionally render content based on device type. ```vue ``` -------------------------------- ### Usage in Script Setup Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/00-overview.md Demonstrates how to use the useDevice composable within the script setup block to access device detection flags like isMobile and isDesktop. ```javascript const { isMobile, isDesktop } = useDevice() ``` -------------------------------- ### Install Nuxt Device Module Source: https://github.com/nuxt-modules/device/blob/main/README.md Use this command to add the Nuxt Device module to your project. ```bash npx nuxt module add device ``` -------------------------------- ### CloudFront Header Behavior Example Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/09-cdn-support.md Demonstrates how multiple CloudFront device headers can be present simultaneously, affecting the final detection results. ```text CloudFront-Is-Mobile-Viewer: true CloudFront-Is-IOS-Viewer: true ``` -------------------------------- ### Device Type Usage Example Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/04-types.md Demonstrates how to import and use the `Device` type with the `useDevice` composable to access device information in a type-safe manner. ```typescript import type { Device } from '@nuxtjs/device' const device: Device = useDevice() // Type-safe access const isMobileUser: boolean = device.isMobile const browserName: string = device.userAgent ``` -------------------------------- ### Setup Mock Device for Unit Tests Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/12-integration-patterns.md Provides a utility function to create mock device objects for testing. Customize properties like user agent and device type. ```typescript // tests/setup.ts import { createNuxtApp } from '@nuxt/app' export function setupDeviceMock(deviceOverrides = {}) { const defaultDevice = { userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)', isMobile: false, isTablet: false, isDesktop: true, isChrome: true, isSafari: false, isFirefox: false, isEdge: false, isSamsung: false, isCrawler: false, isWindows: true, isMacOS: false, isLinux: false, isIos: false, isAndroid: false, isApple: false, isMobileOrTablet: false, isDesktopOrTablet: true, } return { ...defaultDevice, ...deviceOverrides } } ``` -------------------------------- ### Example Headers for CDN Detection Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/09-cdn-support.md Illustrates a scenario with multiple headers from a CDN. The module prioritizes CloudFront detection, ignoring other headers like CF-Device-Type in this case. ```text User-Agent: Amazon CloudFront CloudFront-Is-Mobile-Viewer: true CF-Device-Type: desktop ``` -------------------------------- ### Basic Nuxt Device Module Setup Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/05-configuration.md Integrates the Nuxt Device module with default settings. The default user agent simulates a desktop Chrome browser. ```typescript // nuxt.config.ts export default defineNuxtConfig({ modules: ['@nuxtjs/device'] }) ``` -------------------------------- ### Basic Nuxt.config.ts Setup Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/03-api-module.md Integrates the Nuxt Device module into your Nuxt application by adding it to the modules array. ```typescript export default defineNuxtConfig({ modules: ['@nuxtjs/device'] }) ``` -------------------------------- ### Example: CloudFront Integration Debug Middleware Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/09-cdn-support.md A server middleware to log CloudFront-specific device detection headers when a CloudFront request is identified. ```typescript // server/middleware/cloudfront-debug.ts export default defineEventHandler((event) => { const headers = useRequestHeaders() if (headers['user-agent'] === 'Amazon CloudFront') { console.log('CloudFront request detected:', { isMobile: headers['cloudfront-is-mobile-viewer'], isTablet: headers['cloudfront-is-tablet-viewer'], isDesktop: headers['cloudfront-is-desktop-viewer'], isIos: headers['cloudfront-is-ios-viewer'], isAndroid: headers['cloudfront-is-android-viewer'] }) } }) ``` -------------------------------- ### Device-Aware Data Fetching with useDeviceAwareFetch Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/12-integration-patterns.md Create a custom composable to optimize data fetching based on the detected device type. This example adjusts query parameters like 'limit' and 'includeImages' for mobile, tablet, and desktop. ```typescript // composables/useDeviceAwareFetch.ts export const useDeviceAwareFetch = (url: string, options = {}) => { const device = useDevice() // Adjust request based on device const optimizedOptions = { ...options, query: { ...options.query, limit: device.isMobile ? 10 : device.isTablet ? 20 : 50, includeImages: !device.isMobile, // Skip images on mobile imageQuality: device.isTablet ? 'medium' : device.isDesktop ? 'high' : 'low' } } return useFetch(url, optimizedOptions) } ``` -------------------------------- ### Accessing $device in Script Setup Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/02-api-device-plugin.md Shows how to access the $device property within the script section of a Vue component using `useNuxtApp`. ```APIDOC ## Accessing $device in Script Setup ### Description Retrieve the `$device` object from the Nuxt app context within your script using `useNuxtApp()` to access device information programmatically. ### Example ```vue ``` ``` -------------------------------- ### Component Test Example: Mobile Layout Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/12-integration-patterns.md Tests a Vue component to ensure it renders the mobile layout when the mock device is set to 'isMobile: true'. Requires the setupDeviceMock utility. ```typescript // tests/MyComponent.spec.ts import { describe, it, expect } from 'vitest' import { mount } from '@vue/test-utils' import MyComponent from '~/components/MyComponent.vue' import { setupDeviceMock } from './setup' describe('MyComponent', () => { it('renders mobile layout on mobile', () => { const wrapper = mount(MyComponent, { global: { mocks: { $device: setupDeviceMock({ isMobile: true, isDesktop: false }) } } }) expect(wrapper.find('.mobile-layout').exists()).toBe(true) }) it('renders desktop layout on desktop', () => { const wrapper = mount(MyComponent, { global: { mocks: { $device: setupDeviceMock({ isMobile: false, isDesktop: true }) } } }) expect(wrapper.find('.desktop-layout').exists()).toBe(true) }) }) ``` -------------------------------- ### Nuxt Request Headers Example Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/09-cdn-support.md Demonstrates how Nuxt's useRequestHeaders() function provides headers with lowercase keys, which the module correctly handles due to case-insensitive key matching. ```typescript const headers = useRequestHeaders() // Keys are lowercase: { 'cloudfront-is-mobile-viewer': 'true' } // But module receives them correctly ``` -------------------------------- ### Parsing Browser Version Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/11-known-limitations.md Parse the user agent string to extract specific browser version information. This example shows how to get the version for Chrome and Firefox. ```typescript const getBrowserVersion = () => { const device = useDevice() const ua = device.userAgent if (device.isChrome) { const match = ua.match(/Chrome\/([\d.]+)/) return match?.[1] } if (device.isFirefox) { const match = ua.match(/Firefox\/([\d.]+)/) return match?.[1] } return null } ``` -------------------------------- ### Access $device in Script Setup Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/02-api-device-plugin.md Retrieve the $device property from the Nuxt app context in your script setup to use device detection logic programmatically. ```javascript import { useNuxtApp } from '#imports' const { $device } = useNuxtApp() console.log($device.isChrome) ``` -------------------------------- ### Cloudflare Device Type Header Example Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/09-cdn-support.md This header indicates the device type detected by Cloudflare. It can be 'mobile', 'tablet', or 'desktop'. ```text CF-Device-Type: mobile ``` -------------------------------- ### Mobile-First Navigation with Conditional Rendering Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/08-examples.md Create a navigation structure that prioritizes mobile experience and expands for desktop. This example shows a mobile menu toggle and conditionally renders navigation links based on device type. ```vue ``` -------------------------------- ### Define Nuxt Module Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/03-api-module.md Defines the Nuxt module with its meta information, configuration options, and setup function. ```typescript export default defineNuxtModule({ meta: { name: '@nuxtjs/device', configKey: 'device', compatibility: { nuxt: '>=3.0.0', }, version: '4.0.0', }, setup(options, nuxt) { // Module setup implementation } }) ``` -------------------------------- ### Dynamic Layout Selection Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/02-api-device-plugin.md Select different Nuxt layouts dynamically based on the device type. This example shows how to use a 'mobile' layout for mobile devices and the 'default' layout otherwise. ```vue ``` -------------------------------- ### Device-Specific Features and Content Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/02-api-device-plugin.md Render specific UI elements or content tailored to different devices, browsers, or platforms. This example demonstrates showing desktop-only sidebars, mobile-only quick access, and platform-specific messages. ```vue ``` -------------------------------- ### Dynamic Navigation Menu for Different Devices Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/08-examples.md Implement a responsive navigation menu that adapts to different screen sizes. Desktop users see a standard navigation bar, while mobile users get a collapsible menu triggered by a button. ```vue ``` -------------------------------- ### Browser-Specific Features and Warnings Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/08-examples.md Conditionally render features or warnings based on the browser (Safari, Firefox, Chrome, Edge). This example shows how to check for a set of supported browsers and display browser-specific UI elements. ```vue ``` -------------------------------- ### Multiple Layout Variants Based on Device Type Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/08-examples.md Conditionally render different layout structures (desktop, tablet, mobile) within a single page component using device detection. This example uses slots for sidebar and main content. ```vue ``` -------------------------------- ### Basic Device Detection with useDevice Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/01-api-useDevice.md Demonstrates how to use the useDevice composable to access and log device properties like isMobile and isChrome. It also shows how to display the user agent and device type in the template. ```vue ``` -------------------------------- ### SSR Initialization with Request Headers Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/07-ssr-and-csr.md Initializes device detection on the server using request headers and a default user agent if none is provided. ```typescript if (import.meta.server) { const headers = useRequestHeaders() const userAgent = headers['user-agent'] || defaultUserAgent flags = reactive(generateFlags(userAgent, headers)) } ``` -------------------------------- ### Module Entry Points Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/00-overview.md Lists the main exports from the @nuxtjs/device module, including the default module definition, the useDevice composable, and the $device template plugin. ```plaintext Main exports: - default: Nuxt module definition - useDevice composable: Access device detection object - $device: Template plugin for accessing device properties ``` -------------------------------- ### Setting Runtime Config via Environment Variable Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/05-configuration.md Demonstrates how to set the `defaultUserAgent` using an environment variable when generating the Nuxt application. ```bash NUXT_PUBLIC_DEVICE_DEFAULT_USER_AGENT="Mozilla/5.0 (iPhone...)" npm run generate ``` -------------------------------- ### $device Properties Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/02-api-device-plugin.md Lists and describes all available properties on the $device object for detailed device information. ```APIDOC ## $device Properties ### Description The `$device` object exposes a comprehensive set of properties derived from the `Device` type, allowing for granular device and browser detection. ### Properties | Property | Type | Description | |--------------------|----------|---------------------------------------------------| | `userAgent` | `string` | Full User-Agent string from request/client | | `isDesktop` | `boolean`| Desktop device indicator | | `isMobile` | `boolean`| Mobile device indicator | | `isTablet` | `boolean`| Tablet device indicator | | `isMobileOrTablet` | `boolean`| Mobile or tablet indicator | | `isDesktopOrTablet`| `boolean`| Desktop or tablet indicator | | `isIos` | `boolean`| iOS operating system indicator | | `isAndroid` | `boolean`| Android operating system indicator | | `isLinux` | `boolean`| Linux operating system indicator | | `isWindows` | `boolean`| Windows operating system indicator | | `isMacOS` | `boolean`| macOS operating system indicator | | `isApple` | `boolean`| Apple platform indicator (macOS or iOS) | | `isChrome` | `boolean`| Chrome browser indicator | | `isFirefox` | `boolean`| Firefox browser indicator | | `isEdge` | `boolean`| Edge browser indicator | | `isSafari` | `boolean`| Safari browser indicator | | `isSamsung` | `boolean`| Samsung Internet browser indicator | | `isCrawler` | `boolean`| Web crawler/bot indicator | ``` -------------------------------- ### Test Component Device Detection with Vitest Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/08-examples.md Mock the $device object in global mocks to simulate different device types (mobile, desktop) when mounting components for testing. This allows verification of layout rendering based on device detection. ```typescript // __tests__/MyComponent.spec.ts import { describe, it, expect, vi } from 'vitest' import { mount } from '@vue/test-utils' import MyComponent from '~/components/MyComponent.vue' describe('MyComponent device detection', () => { it('renders mobile layout on mobile device', () => { const wrapper = mount(MyComponent, { global: { mocks: { $device: { isMobile: true, isTablet: false, isDesktop: false, isChrome: true, userAgent: 'Mozilla/5.0 (iPhone...' } } } }) expect(wrapper.find('.mobile-layout').exists()).toBe(true) }) it('renders desktop layout on desktop device', () => { const wrapper = mount(MyComponent, { global: { mocks: { $device: { isMobile: false, isTablet: false, isDesktop: true, isChrome: true, userAgent: 'Mozilla/5.0 (Windows...' } } } }) expect(wrapper.find('.desktop-layout').exists()).toBe(true) }) }) ``` -------------------------------- ### Get All Request Headers in SSR Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/07-ssr-and-csr.md Use the `useRequestHeaders()` composable to retrieve all incoming HTTP headers during Server-Side Rendering. Headers are returned as a lowercase key-value object. ```typescript const headers = useRequestHeaders() // Returns all headers as { 'header-name': 'value' } ``` -------------------------------- ### Mock Runtime Configuration for Testing Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/05-configuration.md Mock the `useRuntimeConfig` import using `@nuxt/test-utils` to provide a controlled configuration for Vitest tests. ```typescript // vitest test file import { mockNuxtImport } from '@nuxt/test-utils' // Mock the runtime config mockNuxtImport('useRuntimeConfig', () => () => ({ public: { device: { defaultUserAgent: 'Mozilla/5.0 (Test User Agent)' } } })) ``` -------------------------------- ### CSR Feature Flagging by Device Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/07-ssr-and-csr.md Conditionally enable features based on device type using computed properties. This example enables a feature only for desktop Safari users on the client-side. ```typescript const isFeatureEnabled = computed(() => { // Feature only for desktop Safari if ($device.isSafari && $device.isDesktop) { return true } return false }) ``` -------------------------------- ### Get Browser Name from User Agent Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/06-detection-logic.md Iterates through a predefined list of browser patterns, returning the name of the first matching browser. Returns an empty string if no match is found. ```typescript const browsers = [ { name: 'Samsung', regex: /SamsungBrowser/i }, { name: 'Edge', regex: /edg(?:[ea]|ios)?\//i }, { name: 'Firefox', regex: /firefox|iceweasel|fxios/i }, { name: 'Chrome', regex: /chrome|crios|crmo/i }, { name: 'Safari', regex: /safari|applewebkit/i }, ] function getBrowserName(userAgent: string): string { for (const browser of browsers) { if (browser.regex.test(userAgent)) { return browser.name } } return '' } ``` -------------------------------- ### Setting Environment Variable via CLI Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/05-configuration.md Shows how to pass the `DEVICE_USER_AGENT` environment variable via the command line when generating the Nuxt application. ```bash DEVICE_USER_AGENT="Mozilla/5.0 (iPhone...)" npm run generate ``` -------------------------------- ### OS and Browser Detection with useDevice Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/01-api-useDevice.md Demonstrates detecting specific operating systems (iOS, Android) and browsers (Safari, Chrome) using properties from useDevice. It includes a computed property to conditionally enable a feature based on these detections. ```vue ``` -------------------------------- ### Environment-Based Configuration with Fallback Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/05-configuration.md Configures the default user agent using an environment variable, with a fallback to a default desktop user agent if the variable is not set. ```typescript // nuxt.config.ts export default defineNuxtConfig({ modules: ['@nuxtjs/device'], device: { defaultUserAgent: process.env.DEVICE_USER_AGENT || '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' } }) ``` -------------------------------- ### Device Detection with useDevice Composable Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/08-examples.md Utilize the useDevice composable to access device detection properties like isMobile, isDesktop, and isTablet within your script setup. This approach is recommended for better code organization and reusability. ```vue ``` -------------------------------- ### Device-Aware State Management with useDeviceLayout Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/12-integration-patterns.md Develop a composable to manage UI layout and state that adapts to different device types. It provides layout information, sidebar visibility, and a toggle function, automatically hiding the sidebar on mobile. ```typescript // composables/useDeviceLayout.ts export const useDeviceLayout = () => { const device = useDevice() const layout = computed(() => { if (device.isMobile) return 'mobile' if (device.isTablet) return 'tablet' return 'desktop' }) const sidebarVisible = ref(!device.isMobile) const toggleSidebar = () => { sidebarVisible.value = !sidebarVisible.value } // Auto-hide sidebar on mobile watch(() => device.isMobile, (isMobile) => { if (isMobile) { sidebarVisible.value = false } }) return { layout, sidebarVisible, toggleSidebar } } ``` -------------------------------- ### Client-Side Initialization Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/07-ssr-and-csr.md Initializes device detection on the client-side using the browser's navigator object. This is used in CSR mode. ```typescript else { const userAgent = navigator.userAgent || defaultUserAgent flags = reactive(generateFlags(userAgent)) } ``` -------------------------------- ### Configuration via .env File Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/05-configuration.md Specifies the default user agent for iPad by defining `NUXT_PUBLIC_DEVICE_DEFAULT_USER_AGENT` in a `.env` file. Nuxt automatically loads this configuration. ```env NUXT_PUBLIC_DEVICE_DEFAULT_USER_AGENT=Mozilla/5.0 (iPad; CPU OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1 ``` -------------------------------- ### Configure defaultUserAgent for Tablet Rendering Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/05-configuration.md Set the `defaultUserAgent` to mimic an iPad for static site generation. ```typescript defaultUserAgent: 'Mozilla/5.0 (iPad; CPU OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1' ``` -------------------------------- ### Browser Capability Detection with useBrowserCapabilities Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/12-integration-patterns.md Create a composable to detect various browser and device capabilities, such as WebGL support, Web Workers, touch device presence, and specific browser workarounds. This helps in providing a tailored experience or implementing necessary fallbacks. ```typescript // composables/useBrowserCapabilities.ts export const useBrowserCapabilities = () => { const device = useDevice() return { // Browser features supportsWebGL: !process.server && checkWebGL(), supportsWebWorkers: !process.server && typeof Worker !== 'undefined', supportsServiceWorker: !process.server && 'serviceWorker' in navigator, // Device features isTouchDevice: device.isMobileOrTablet, isHighDPI: !process.server && window.devicePixelRatio > 1, // Browser-specific workarounds needsSafariWorkaround: device.isSafari && device.isMobile, needsIEWorkaround: device.userAgent.includes('Trident'), needsEdgeWorkaround: device.isEdge && device.isMobile, // Mobile app context isInMobileApp: !process.server && !!window.MobileAppBridge, } } function checkWebGL() { const canvas = document.createElement('canvas') return !!(window.WebGLRenderingContext && canvas.getContext('webgl')) } ``` -------------------------------- ### Configure defaultUserAgent for Mobile Rendering Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/05-configuration.md Set the `defaultUserAgent` to mimic an iPhone for static site generation. ```typescript defaultUserAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1' ``` -------------------------------- ### Accessing Specific Device Flags Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/00-overview.md Illustrates how to access specific device properties and flags, such as userAgent, isChrome, and isIos, using the useDevice composable. ```javascript const device = useDevice() console.log(device.userAgent) console.log(device.isChrome) console.log(device.isIos) ``` -------------------------------- ### Configure Default User Agent for Static Generation (SSG) Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/07-ssr-and-csr.md Set a default User-Agent for the Nuxt Device module during Static Site Generation (SSG). This allows pre-rendering pages for specific device types based on environment variables. ```typescript export default defineNuxtConfig({ device: { // Pre-render as specific device type defaultUserAgent: process.env.NODE_ENV === 'production' ? 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_0...)' : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2)...' } }) ``` -------------------------------- ### ModuleOptions Interface Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/03-api-module.md Defines the configuration options for the Nuxt Device module, including the default user agent. ```typescript 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 } ``` -------------------------------- ### Module Configuration Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/MANIFEST.txt Configure the @nuxtjs/device module to customize its behavior, such as setting a default user agent for testing or specific detection scenarios. ```APIDOC ## Module Configuration ### Description Allows customization of the @nuxtjs/device module's behavior through Nuxt configuration. ### Configuration Options #### `defaultUserAgent` - **Type**: `string` - **Default**: `undefined` - **Description**: Sets a default User-Agent string for all requests. Useful for testing or simulating specific devices during development. ### Configuration Example (`nuxt.config.ts`) ```typescript export default defineNuxtConfig({ modules: [ '@nuxtjs/device' ], device: { defaultUserAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1.1 Mobile/15E148 Safari/604.1' } }) ``` ### Runtime Access Patterns Configuration options are accessible via the `$device` property or `useDevice()` composable, depending on the context. ``` -------------------------------- ### Lazy Device Detection with useLazyDevice Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/12-integration-patterns.md Defer device detection until the component is mounted to improve initial load performance. This composable returns the device object and a ready state. ```typescript // composables/useLazyDevice.ts export const useLazyDevice = () => { const device = ref(null) const isReady = ref(false) onMounted(async () => { // Defer detection until component is mounted await nextTick() device.value = useDevice() isReady.value = true }) return { device, isReady } } ``` -------------------------------- ### TypeScript Support for Device Type Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/02-api-device-plugin.md Leverage full TypeScript support by importing the Device type and accessing the $device object via useNuxtApp().$device for type-safe development. ```typescript // The Device type is automatically available import type { Device } from '@nuxtjs/device' const device: Device = useNuxtApp().$device ``` -------------------------------- ### Usage in Template Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/00-overview.md Shows how to use the $device template plugin to conditionally render content based on whether the device is mobile or desktop. ```vue ``` -------------------------------- ### Conditional Download Link with useDevice Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/01-api-useDevice.md Shows how to dynamically determine a download link based on the detected device (iOS, Android, or desktop) using properties from the useDevice composable. ```vue ``` -------------------------------- ### Configure defaultUserAgent for Android Rendering Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/05-configuration.md Set the `defaultUserAgent` to mimic an Android device. ```typescript defaultUserAgent: 'Mozilla/5.0 (Linux; Android 11; SM-G991B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.120 Mobile Safari/537.36' ``` -------------------------------- ### Nuxt Device Module File Structure Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/README.md Overview of the directory structure for the Nuxt Device module, outlining the purpose of each file. ```plaintext output/ ├── README.md # This file ├── 00-overview.md # Project overview ├── 01-api-useDevice.md # useDevice composable API ├── 02-api-device-plugin.md # $device plugin API ├── 03-api-module.md # Module definition API ├── 04-types.md # Type definitions ├── 05-configuration.md # Configuration options ├── 06-detection-logic.md # Detection engine details ├── 07-ssr-and-csr.md # Rendering mode behavior ├── 08-examples.md # Code examples ├── 09-cdn-support.md # CDN integration ├── 10-browser-detection.md # Browser detection details ├── 11-known-limitations.md # Limitations and workarounds └── 12-integration-patterns.md # Integration best practices ``` -------------------------------- ### CloudFront Detection Logic Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/09-cdn-support.md TypeScript code demonstrating how the module detects device types based on CloudFront-specific headers. This logic is applied first due to its high priority. ```typescript if (userAgent === 'Amazon CloudFront') { if (headers['cloudfront-is-mobile-viewer'] === 'true') { mobile = true mobileOrTablet = true } if (headers['cloudfront-is-tablet-viewer'] === 'true') { mobile = false mobileOrTablet = true } if (headers['cloudfront-is-desktop-viewer'] === 'true') { mobile = false mobileOrTablet = false } if (headers['cloudfront-is-ios-viewer'] === 'true') { ios = true } if (headers['cloudfront-is-android-viewer'] === 'true') { android = true } } ``` -------------------------------- ### generateFlags() Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/06-detection-logic.md Generates a Device object with detection flags based on the User-Agent string and optional HTTP headers. ```APIDOC ## generateFlags() ### Description Generates a `Device` object containing 18 boolean and string flags that indicate the detected device type, OS, and browser based on the provided User-Agent string and optional HTTP headers. This function is the primary interface for device detection. ### Method Signature ```typescript export default function generateFlags( userAgent: string, headers: Record = {} ): Device ``` ### Parameters #### Function Parameters - **userAgent** (string) - Required - The User-Agent string to parse. - **headers** (Record) - Optional - An object containing HTTP headers. Keys should be lowercase. This is used for CDN detection. ### Return Value Returns a `Device` object populated with detection flags. ``` -------------------------------- ### OS Detection for Platform Information Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/08-examples.md Display messages indicating the user's operating system (Windows, macOS, Linux, iOS, Android). This is useful for providing OS-specific guidance or information. ```vue ``` -------------------------------- ### Browser Compatibility Warnings Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/10-browser-detection.md Implement compatibility checks to warn users if they are using an unsupported browser. This ensures a consistent experience across modern browsers. ```vue ``` -------------------------------- ### Nuxt Device Module Documentation Structure Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/DELIVERY_SUMMARY.md This markdown code block outlines the directory structure and file names for the generated technical reference documentation of the Nuxt Device module. ```markdown /workspace/home/output/ ├── README.md (Main navigation hub) ├── 00-overview.md (Project scope & architecture) ├── 01-api-useDevice.md (Composable API) ├── 02-api-device-plugin.md (Plugin property API) ├── 03-api-module.md (Module definition) ├── 04-types.md (Type definitions) ├── 05-configuration.md (Configuration options) ├── 06-detection-logic.md (Detection engine) ├── 07-ssr-and-csr.md (Rendering modes) ├── 08-examples.md (30+ code examples) ├── 09-cdn-support.md (CDN integration) ├── 10-browser-detection.md (Browser detection) ├── 11-known-limitations.md (Limitations & workarounds) ├── 12-integration-patterns.md (Integration best practices) └── MANIFEST.txt (File manifest) ``` -------------------------------- ### Merge Device Configuration Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/03-api-module.md Merges user-provided device options with default values for runtime configuration. ```typescript nuxt.options.runtimeConfig.public.device = defu( nuxt.options.runtimeConfig.public.device, { defaultUserAgent: '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' } ) ``` -------------------------------- ### Detect OS and Browser Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/02-api-device-plugin.md Use the $device object in your template to conditionally render content based on the detected operating system or browser. This is useful for providing tailored experiences or warnings. ```vue ``` -------------------------------- ### Register Device Plugin Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/03-api-module.md Registers the runtime plugin responsible for initializing the device detection functionality. ```typescript addPlugin(resolve('./runtime/plugin')) ``` -------------------------------- ### Windows Version Detection Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/11-known-limitations.md The module detects if a device is Windows but does not provide the specific version. Parse the userAgent string manually for detailed version information (e.g., XP, Vista, 7, 8, 10, 11). ```typescript device.isWindows // true device.windowsVersion // undefined ``` -------------------------------- ### Configure Custom Default User Agent Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/03-api-module.md Configure a custom default user agent for static generation within the Nuxt Device module settings. ```typescript export default defineNuxtConfig({ modules: ['@nuxtjs/device'], device: { // Use a custom default user agent for static generation defaultUserAgent: 'Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34' } }) ``` -------------------------------- ### Responsive Rendering with useDevice Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/01-api-useDevice.md Illustrates using the isMobile property from useDevice to conditionally render different layouts (mobile or desktop) within a Vue template. ```vue ``` -------------------------------- ### Define ModuleOptions Type Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/04-types.md Defines the configuration options for the Nuxt Device module. Use `defaultUserAgent` to set a fallback user agent string, especially for SSR generation. ```typescript export 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 } ``` -------------------------------- ### Troubleshoot CDN Headers with Curl Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/09-cdn-support.md Use this command to verify if a specific CDN header is being sent by your domain. Replace 'your-domain.com' with your actual domain. ```bash curl -v https://your-domain.com | grep -i cloudfront ``` -------------------------------- ### Access Device Detection in Browser DevTools Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/07-ssr-and-csr.md Access the device detection properties directly from the browser's console during client-side rendering. This allows for interactive inspection of device details. ```javascript // In browser console console.log(useNuxtApp().$device) // Or access individual properties console.log('Is mobile:', useNuxtApp().$device.isMobile) ``` -------------------------------- ### Configure Default User Agent for Production SSR Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/07-ssr-and-csr.md Configure a default User-Agent for the Nuxt Device module in production SSR environments. Note that actual User-Agent headers from real requests will be used. ```typescript export default defineNuxtConfig({ device: { // Actual User-Agent headers are used from real requests defaultUserAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2)...' } }) ``` -------------------------------- ### Destructuring useDevice Properties Source: https://github.com/nuxt-modules/device/blob/main/_autodocs/01-api-useDevice.md Shows how to destructure specific device properties (isMobile, isTablet, isDesktop) directly from the useDevice composable for easier access in the script. ```vue ```