@zedmagdy/user-agent
v1.0.0
Published
A TypeScript library for user agent parsing and detection
Downloads
13
Maintainers
Readme
@zed-magdy/user-agent
A comprehensive TypeScript library for user agent parsing and device detection. This library provides extensive capabilities for identifying browsers, operating systems, devices, and bots from user agent strings.
Installation
npm install @zed-magdy/user-agentQuick Start
import { Agent } from '@zed-magdy/user-agent';
const agent = new Agent();
const userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36';
// Basic device detection
console.log(agent.isMobile(userAgent)); // false
console.log(agent.isDesktop(userAgent)); // true
console.log(agent.deviceType(userAgent)); // 'desktop'
// Browser and platform detection
console.log(agent.browser(userAgent)); // 'Chrome'
console.log(agent.platform(userAgent)); // 'Windows'
// Version extraction
console.log(agent.version('Chrome')); // '91.0.4472.124'Features
🔍 Comprehensive Device Detection
- Mobile Devices: Phones, smartphones from all major manufacturers
- Desktop Devices: Windows, macOS, Linux systems
- Tablets: iPad, Android tablets, Windows tablets, Kindle, and more
- Gaming Consoles: PlayStation, Xbox, Nintendo devices
- Smart TVs: WebOS, Tizen, and other TV platforms
🌐 Extensive Browser Support
- Major Browsers: Chrome, Firefox, Safari, Edge, Opera, Internet Explorer
- Mobile Browsers: Chrome Mobile, Safari Mobile, Samsung Browser, UC Browser
- Alternative Browsers: Vivaldi, Brave, Opera Mini, and many more
- Legacy Browsers: Full support for older browser versions
💻 Operating System Detection
- Desktop OS: Windows (all versions), macOS, Linux distributions
- Mobile OS: Android, iOS, Windows Phone, BlackBerry OS
- Specialized OS: ChromeOS, webOS, Tizen, Symbian, and more
🤖 Bot & Crawler Detection
- Search Engines: Google, Bing, Yahoo, Baidu, Yandex bots
- Social Media: Facebook, Twitter, LinkedIn crawlers
- SEO Tools: Ahrefs, SEMrush, Moz bots
- Custom Patterns: Easily extensible bot detection
🌍 Advanced Features
- Language Detection: Parse Accept-Language headers with priority
- CloudFront Support: Special handling for AWS CloudFront headers
- Version Extraction: Detailed version information for browsers and OS
- TypeScript Support: Full type definitions included
API Reference
Constructor
new Agent(httpHeaders?: HttpHeaders, userAgent?: string)Parameters:
httpHeaders(optional): HTTP headers objectuserAgent(optional): User agent string to parse
Examples:
// Default constructor (uses window.navigator.userAgent in browser)
const agent = new Agent();
// With custom user agent
const agent = new Agent(undefined, 'Mozilla/5.0...');
// With custom headers (useful for server-side)
const agent = new Agent({
'HTTP_USER_AGENT': 'Mozilla/5.0...',
'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.9'
});Device Detection Methods
isMobile(userAgent?: string): boolean
Detects if the user agent is from a mobile device (phone).
agent.isMobile('Mozilla/5.0 (iPhone...)'); // true
agent.isMobile('Mozilla/5.0 (Windows...)'); // falseisDesktop(userAgent?: string): boolean
Detects if the user agent is from a desktop device.
agent.isDesktop('Mozilla/5.0 (Windows NT 10.0...)'); // true
agent.isDesktop('Mozilla/5.0 (iPhone...)'); // falseisTablet(userAgent?: string): boolean
Detects if the user agent is from a tablet device.
agent.isTablet('Mozilla/5.0 (iPad...)'); // true
agent.isTablet('Mozilla/5.0 (iPhone...)'); // falseisPhone(userAgent?: string): boolean
Detects if the user agent is from a phone (mobile but not tablet).
agent.isPhone('Mozilla/5.0 (iPhone...)'); // true
agent.isPhone('Mozilla/5.0 (iPad...)'); // falsedeviceType(userAgent?: string): string
Returns the device type as a string.
Returns: 'desktop' | 'phone' | 'tablet' | 'robot' | 'other'
agent.deviceType('Mozilla/5.0 (Windows...)'); // 'desktop'
agent.deviceType('Mozilla/5.0 (iPhone...)'); // 'phone'
agent.deviceType('Mozilla/5.0 (iPad...)'); // 'tablet'
agent.deviceType('Googlebot/2.1...'); // 'robot'Browser & Platform Detection
browser(userAgent?: string): string | false
Detects the browser name from the user agent.
agent.browser('Mozilla/5.0... Chrome/91.0...'); // 'Chrome'
agent.browser('Mozilla/5.0... Firefox/89.0'); // 'Firefox'
agent.browser('Mozilla/5.0... Safari/605.1'); // 'Safari'platform(userAgent?: string): string | false
Detects the operating system/platform from the user agent.
agent.platform('Mozilla/5.0 (Windows NT 10.0...)'); // 'Windows'
agent.platform('Mozilla/5.0 (Macintosh...)'); // 'OS X'
agent.platform('Mozilla/5.0... Android 11...'); // 'AndroidOS'device(userAgent?: string): string | false
Detects the specific device or device category.
agent.device('Mozilla/5.0 (iPhone...)'); // 'iPhone'
agent.device('Mozilla/5.0 (iPad...)'); // 'iPad'
agent.device('Mozilla/5.0 (Macintosh...)'); // 'Macintosh'Version Detection
version(propertyName: string, type?: string): string | number | false
Extracts version information for browsers, operating systems, or other components.
Parameters:
propertyName: The name of the browser/OS to get version fortype:Agent.VERSION_TYPE_STRING(default) orAgent.VERSION_TYPE_FLOAT
// Browser versions
agent.version('Chrome'); // '91.0.4472.124'
agent.version('Firefox'); // '89.0'
agent.version('Safari'); // '14.1.1'
// OS versions
agent.version('Windows NT'); // '10.0'
agent.version('iPhone'); // '14_7_1'
// Float versions (major.minor only)
agent.version('Chrome', Agent.VERSION_TYPE_FLOAT); // 91.0Bot Detection
isRobot(userAgent?: string): boolean
Detects if the user agent is from a bot or crawler.
agent.isRobot('Googlebot/2.1...'); // true
agent.isRobot('Mozilla/5.0 (Windows...)'); // falserobot(userAgent?: string): string | false
Returns the name of the detected bot/crawler.
agent.robot('Googlebot/2.1...'); // 'Bot'
agent.robot('facebookexternalhit/1.1...'); // 'Bot'
agent.robot('Mozilla/5.0 (Windows...)'); // falseLanguage Detection
languages(acceptLanguage?: string): string[]
Parses Accept-Language header and returns an array of languages ordered by preference.
// From constructor headers
const agent = new Agent({ 'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.9,fr;q=0.8' });
agent.languages(); // ['en-us', 'en', 'fr']
// Custom Accept-Language string
agent.languages('es-ES,es;q=0.9,en;q=0.8'); // ['es-es', 'es', 'en']Specific Device Checks
Convenience methods for common checks:
// Device-specific checks
agent.isIphone(); // boolean
agent.isIpad(); // boolean
agent.isAndroid(); // boolean
// Browser-specific checks
agent.isChrome(); // boolean
agent.isFirefox(); // boolean
agent.isSafari(); // boolean
agent.isIE(); // boolean
agent.isEdge(); // boolean
agent.isOpera(); // boolean
// Generic "is" method for any device/browser/OS
agent.is('iPhone'); // boolean
agent.is('Chrome'); // boolean
agent.is('AndroidOS'); // booleanStatic Methods
Get Detection Rules
Agent.getBrowsers(); // Returns browser detection rules
Agent.getOperatingSystems(); // Returns OS detection rules
Agent.getPlatforms(); // Returns platform detection rules
Agent.getDesktopDevices(); // Returns desktop device rules
Agent.getPhoneDevices(); // Returns phone device rules
Agent.getTabletDevices(); // Returns tablet device rules
Agent.getUtilities(); // Returns utility detection rules
Agent.getProperties(); // Returns version extraction rulesConstants
Agent.VERSION_TYPE_STRING; // 'text'
Agent.VERSION_TYPE_FLOAT; // 'float'
Agent.DETECTION_TYPE_EXTENDED; // 'extended'
Agent.VER; // Version regex patternServer-Side Usage
Perfect for Express.js, Next.js, and other Node.js applications:
import { Agent } from '@zed-magdy/user-agent';
// Express.js middleware
app.use((req, res, next) => {
const agent = new Agent(req.headers, req.headers['user-agent']);
req.deviceInfo = {
isMobile: agent.isMobile(),
isDesktop: agent.isDesktop(),
browser: agent.browser(),
platform: agent.platform(),
languages: agent.languages()
};
next();
});
// Next.js API route
export default function handler(req, res) {
const agent = new Agent(req.headers, req.headers['user-agent']);
res.json({
device: agent.deviceType(),
browser: agent.browser(),
platform: agent.platform()
});
}CloudFront Integration
Special support for AWS CloudFront headers:
const agent = new Agent({
'HTTP_USER_AGENT': 'Amazon CloudFront',
'HTTP_CLOUDFRONT_IS_DESKTOP_VIEWER': 'true',
'HTTP_CLOUDFRONT_IS_MOBILE_VIEWER': 'false'
});
agent.isDesktop(); // true (uses CloudFront header)Real-World Examples
Responsive Content Delivery
import { Agent } from '@zed-magdy/user-agent';
function serveContent(req, res) {
const agent = new Agent(req.headers, req.headers['user-agent']);
if (agent.isMobile()) {
res.render('mobile-template', { data });
} else if (agent.isTablet()) {
res.render('tablet-template', { data });
} else {
res.render('desktop-template', { data });
}
}Analytics and Tracking
import { Agent } from '@zed-magdy/user-agent';
function trackVisitor(userAgent) {
const agent = new Agent(undefined, userAgent);
const analytics = {
browser: agent.browser(),
browserVersion: agent.version(agent.browser()),
platform: agent.platform(),
deviceType: agent.deviceType(),
isBot: agent.isRobot()
};
if (!analytics.isBot) {
sendToAnalytics(analytics);
}
}Feature Detection
import { Agent } from '@zed-magdy/user-agent';
function enableFeatures(userAgent) {
const agent = new Agent(undefined, userAgent);
const features = {
pushNotifications: agent.isChrome() || agent.isFirefox(),
touchEvents: agent.isMobile() || agent.isTablet(),
webGL: !agent.isIE(),
modernJS: !agent.isIE() && agent.version('Chrome', 'float') >= 60
};
return features;
}Testing
The library includes comprehensive tests covering all functionality:
# Run tests
npm test
# Run tests with coverage
npm run test:coverage
# Run tests in watch mode
npm run test:watchDevelopment
# Install dependencies
npm install
# Build the package
npm run build
# Watch for changes during development
npm run dev
# Clean build artifacts
npm run cleanBrowser Support
- ✅ Modern Browsers: Chrome 60+, Firefox 55+, Safari 12+, Edge 79+
- ✅ Mobile Browsers: iOS Safari 12+, Chrome Mobile, Samsung Internet
- ✅ Node.js: 14.0.0+
- ✅ TypeScript: 4.0+
Performance
- 🚀 Zero Dependencies: No external runtime dependencies
- 📦 Small Bundle: ~15KB minified, ~4KB gzipped
- ⚡ Fast Parsing: Optimized regex patterns for quick detection
- 🔧 Tree Shakeable: Use only what you need
Contributing
Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
License
MIT License - see the LICENSE file for details.
Changelog
v1.0.0
- Initial release
- Comprehensive device, browser, and OS detection
- Bot/crawler detection
- Language parsing
- CloudFront header support
- Full TypeScript support
- Extensive test coverage
