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.00
# Nuxt Device
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: @nuxtjs/device
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npx nuxi@latest module add device`
10
11
## Core Imports
12
13
```typescript
14
import { useDevice } from '#imports';
15
```
16
17
The module also provides global access via `$device` in templates and throughout the Nuxt application.
18
19
## Basic Usage
20
21
```vue
22
<template>
23
<div>
24
<div v-if="$device.isDesktop">Desktop View</div>
25
<div v-else-if="$device.isTablet">Tablet View</div>
26
<div v-else>Mobile View</div>
27
28
<p>User Agent: {{ $device.userAgent }}</p>
29
<p>Browser: {{ $device.isChrome ? 'Chrome' : 'Other' }}</p>
30
</div>
31
</template>
32
33
<script setup>
34
const { isMobile, isIos, isAndroid } = useDevice();
35
36
if (isMobile) {
37
console.log('Mobile device detected');
38
}
39
</script>
40
```
41
42
## Architecture
43
44
Nuxt Device operates through several key components:
45
46
- **Nuxt Module**: Integrates device detection into the Nuxt build and runtime system
47
- **Device Detection Engine**: Core logic for analyzing user agents and CDN headers
48
- **Composable API**: Vue composition API integration via `useDevice()`
49
- **Global Plugin**: Provides `$device` object throughout the application
50
- **Type System**: Complete TypeScript definitions for all device properties
51
- **CDN Integration**: Enhanced detection using CloudFront and Cloudflare headers
52
53
## Capabilities
54
55
### Device Detection Composable
56
57
The primary API for accessing device information in Vue components using the composition API.
58
59
```typescript { .api }
60
/**
61
* Vue composable that provides device detection information
62
* @returns Device object with all detection flags and user agent
63
*/
64
function useDevice(): Device;
65
66
/**
67
* Core device detection function for server-side usage
68
* @param userAgent - User agent string to analyze
69
* @param headers - Optional HTTP headers for CDN detection
70
* @returns Device object with all detection flags
71
*/
72
function generateFlags(userAgent: string, headers?: Record<string, string>): Device;
73
```
74
75
### Global Device Object
76
77
Device information is available globally throughout the Nuxt application via the `$device` property.
78
79
```typescript { .api }
80
/**
81
* Global device object available in templates, plugins, and throughout Nuxt app
82
* Accessible as this.$device in options API or $device in templates
83
*/
84
declare global {
85
interface NuxtApp {
86
$device: Device;
87
}
88
89
interface ComponentCustomProperties {
90
$device: Device;
91
}
92
}
93
```
94
95
### Module Configuration
96
97
Configure the device detection module behavior.
98
99
```typescript { .api }
100
/**
101
* Configuration options for @nuxtjs/device module
102
*/
103
interface ModuleOptions {
104
/**
105
* Sets the default value for the user-agent header (useful when running npm run generate)
106
* @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'
107
*/
108
defaultUserAgent?: string;
109
110
/**
111
* @deprecated This option will be removed in the next major release
112
*/
113
enabled?: boolean;
114
115
/**
116
* @deprecated This option will be removed in the next major release
117
*/
118
refreshOnResize?: boolean;
119
}
120
```
121
122
**Configuration Example:**
123
124
```typescript
125
// nuxt.config.ts
126
export default defineNuxtConfig({
127
modules: ['@nuxtjs/device'],
128
device: {
129
defaultUserAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
130
}
131
});
132
```
133
134
### Device Information Interface
135
136
Complete device detection information with all supported flags and properties.
137
138
```typescript { .api }
139
/**
140
* Complete device detection information object
141
*/
142
interface Device {
143
/** Original user agent string */
144
userAgent: string;
145
146
/** True if desktop device (not mobile or tablet) */
147
isDesktop: boolean;
148
149
/** True if iOS device (iPhone, iPad, iPod) */
150
isIos: boolean;
151
152
/** True if Android device */
153
isAndroid: boolean;
154
155
/** True if mobile device (phone) */
156
isMobile: boolean;
157
158
/** True if mobile phone or tablet */
159
isMobileOrTablet: boolean;
160
161
/** True if desktop or tablet (not mobile phone) */
162
isDesktopOrTablet: boolean;
163
164
/** True if tablet device */
165
isTablet: boolean;
166
167
/** True if Windows operating system */
168
isWindows: boolean;
169
170
/** True if macOS operating system */
171
isMacOS: boolean;
172
173
/** True if Apple device (iOS or macOS) */
174
isApple: boolean;
175
176
/** True if Safari browser */
177
isSafari: boolean;
178
179
/** True if Firefox browser */
180
isFirefox: boolean;
181
182
/** True if Edge browser */
183
isEdge: boolean;
184
185
/** True if Chrome browser */
186
isChrome: boolean;
187
188
/** True if Samsung browser */
189
isSamsung: boolean;
190
191
/** True if web crawler/bot (powered by crawler-user-agents) */
192
isCrawler: boolean;
193
}
194
```
195
196
### CDN Integration
197
198
Enhanced device detection using CDN-provided headers for improved performance and accuracy.
199
200
**Amazon CloudFront Support:**
201
202
When the user agent is `Amazon CloudFront`, the module automatically detects these headers:
203
204
- `cloudfront-is-mobile-viewer`: Sets `isMobile` and `isMobileOrTablet` flags
205
- `cloudfront-is-tablet-viewer`: Sets `isTablet` and `isMobileOrTablet` flags
206
- `cloudfront-is-desktop-viewer`: Sets `isDesktop` flag
207
- `cloudfront-is-ios-viewer`: Sets `isIos` flag
208
- `cloudfront-is-android-viewer`: Sets `isAndroid` flag
209
210
**Cloudflare Support:**
211
212
The module detects the `CF-Device-Type` header with values:
213
- `mobile`: Sets mobile device flags
214
- `tablet`: Sets tablet device flags
215
- `desktop`: Sets desktop device flags
216
217
**Usage with CDN:**
218
219
```typescript
220
// The detection happens automatically when CDN headers are present
221
// No additional configuration required
222
const { isTablet, isMobile } = useDevice();
223
224
// CDN detection takes precedence over user agent parsing
225
if (isTablet) {
226
// This could be set by cloudfront-is-tablet-viewer header
227
// or by Cloudflare cf-device-type: tablet header
228
}
229
```
230
231
### Advanced Integration Patterns
232
233
The module provides several advanced integration patterns for complex applications.
234
235
**Plugin Extension:**
236
237
```typescript
238
// plugins/device-analytics.ts
239
export default defineNuxtPlugin((nuxtApp) => {
240
const { $device } = nuxtApp;
241
242
// Track device analytics
243
if (!$device.isCrawler) {
244
analytics.track('device_type', {
245
isMobile: $device.isMobile,
246
isTablet: $device.isTablet,
247
browser: $device.isChrome ? 'chrome' :
248
$device.isSafari ? 'safari' :
249
$device.isFirefox ? 'firefox' : 'other'
250
});
251
}
252
});
253
```
254
255
**Middleware Integration:**
256
257
```typescript
258
// middleware/device-redirect.ts
259
export default defineNuxtRouteMiddleware((to) => {
260
const { $device } = useNuxtApp();
261
262
// Redirect mobile users to mobile-optimized routes
263
if ($device.isMobile && !to.path.startsWith('/mobile')) {
264
return navigateTo('/mobile' + to.path);
265
}
266
});
267
```
268
269
**Server-Side API Usage:**
270
271
```typescript
272
// server/api/device-info.ts
273
export default defineEventHandler(async (event) => {
274
const device = await generateFlags(
275
getHeader(event, 'user-agent') || '',
276
getHeaders(event)
277
);
278
279
return {
280
deviceType: device.isMobile ? 'mobile' :
281
device.isTablet ? 'tablet' : 'desktop',
282
platform: device.isIos ? 'ios' :
283
device.isAndroid ? 'android' : 'other'
284
};
285
});
286
```
287
288
### Conditional Rendering Patterns
289
290
Common patterns for responsive design and device-specific functionality.
291
292
**Layout Selection:**
293
294
```vue
295
<template>
296
<NuxtLayout :name="$device.isMobile ? 'mobile' : 'default'">
297
<!-- page content -->
298
</NuxtLayout>
299
</template>
300
301
<script setup>
302
definePageMeta({
303
layout: false
304
});
305
</script>
306
```
307
308
**Progressive Enhancement:**
309
310
```vue
311
<template>
312
<div>
313
<!-- Show simplified interface for mobile -->
314
<MobileNavigation v-if="$device.isMobile" />
315
316
<!-- Show full interface for desktop/tablet -->
317
<DesktopNavigation v-else />
318
319
<!-- Browser-specific optimizations -->
320
<VideoPlayer
321
:use-hardware-acceleration="$device.isChrome"
322
:fallback-format="$device.isSafari ? 'mp4' : 'webm'"
323
/>
324
</div>
325
</template>
326
```
327
328
**Crawler Detection:**
329
330
```vue
331
<template>
332
<div>
333
<!-- Skip heavy JavaScript for crawlers -->
334
<StaticContent v-if="$device.isCrawler" />
335
<InteractiveContent v-else />
336
</div>
337
</template>
338
```
339
340
### Runtime Configuration
341
342
The module extends Nuxt's runtime configuration for server-side and client-side access.
343
344
```typescript { .api }
345
/**
346
* Device configuration in Nuxt runtime config
347
*/
348
declare module '@nuxt/schema' {
349
interface PublicRuntimeConfig {
350
device: Required<ModuleOptions>;
351
}
352
}
353
```
354
355
**Accessing Runtime Config:**
356
357
```typescript
358
// In plugins, middleware, or composables
359
const config = useRuntimeConfig();
360
const defaultUserAgent = config.public.device.defaultUserAgent;
361
```
362
363
### Error Handling and Edge Cases
364
365
The module gracefully handles various edge cases and provides fallback behavior:
366
367
- **Missing User Agent**: Falls back to the configured `defaultUserAgent` when no user agent is available
368
- **Malformed Headers**: Invalid CDN headers are ignored, falling back to user agent parsing
369
- **Server-Client Hydration**: Device flags are computed server-side and hydrated on the client without conflicts
370
- **Unknown Devices**: Unrecognized devices default to desktop with appropriate fallback flags
371
372
### Performance Considerations
373
374
- **Zero Runtime Dependencies**: No external libraries loaded on the client side
375
- **Server-Side Detection**: Device flags are computed during SSR, reducing client-side computation
376
- **Static Analysis**: User agent parsing uses optimized regular expressions for fast detection
377
- **CDN Integration**: When available, CDN headers provide faster detection than user agent parsing
378
- **Lazy Evaluation**: Device flags are computed once per request and cached throughout the application lifecycle