{"id":48434957,"url":"https://github.com/sumitsahoo/modern-barcode-scanner","last_synced_at":"2026-04-06T12:04:28.494Z","repository":{"id":341567814,"uuid":"1170609736","full_name":"sumitsahoo/modern-barcode-scanner","owner":"sumitsahoo","description":"A modern barcode scanner library","archived":false,"fork":false,"pushed_at":"2026-03-25T15:10:44.000Z","size":174,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-03-26T17:41:24.107Z","etag":null,"topics":["barcode-scanner","library","typescript","wasm","zbar"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/modern-barcode-scanner","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/sumitsahoo.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null},"funding":{"github":"sumitsahoo"}},"created_at":"2026-03-02T10:11:25.000Z","updated_at":"2026-03-04T06:45:19.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/sumitsahoo/modern-barcode-scanner","commit_stats":null,"previous_names":["sumitsahoo/modern-barcode-scanner"],"tags_count":1,"template":false,"template_full_name":null,"purl":"pkg:github/sumitsahoo/modern-barcode-scanner","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sumitsahoo%2Fmodern-barcode-scanner","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sumitsahoo%2Fmodern-barcode-scanner/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sumitsahoo%2Fmodern-barcode-scanner/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sumitsahoo%2Fmodern-barcode-scanner/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/sumitsahoo","download_url":"https://codeload.github.com/sumitsahoo/modern-barcode-scanner/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sumitsahoo%2Fmodern-barcode-scanner/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31471493,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-06T08:36:52.050Z","status":"ssl_error","status_checked_at":"2026-04-06T08:36:51.267Z","response_time":112,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["barcode-scanner","library","typescript","wasm","zbar"],"created_at":"2026-04-06T12:04:27.828Z","updated_at":"2026-04-06T12:04:28.481Z","avatar_url":"https://github.com/sumitsahoo.png","language":"TypeScript","funding_links":["https://github.com/sponsors/sumitsahoo"],"categories":[],"sub_categories":[],"readme":"\u003cdiv align=\"center\"\u003e\n  \u003ch1\u003e📷 Modern Barcode Scanner\u003c/h1\u003e\n  \u003cp\u003eA high-performance barcode scanner React component with optimized detection, camera switching, torch control, and automatic phone detection.\u003c/p\u003e\n\n  ![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/sumitsahoo/modern-barcode-scanner/publish.yml)\n  ![NPM Version](https://img.shields.io/npm/v/modern-barcode-scanner)\n  ![NPM Downloads](https://img.shields.io/npm/dw/modern-barcode-scanner)\n  [![Socket Badge](https://badge.socket.dev/npm/package/modern-barcode-scanner)](https://badge.socket.dev/npm/package/modern-barcode-scanner)\n  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n  \n\u003c/div\u003e\n\n---\n\n## ✨ Features\n\n- 🚀 **High Performance**: Web Worker-based scanning with optimized grayscale conversion.\n- 📱 **Mobile Optimized**: Automatic phone detection with appropriate camera selection.\n- 🔦 **Torch Control**: Built-in torch/flash support for low-light scanning.\n- 🔄 **Camera Switching**: Easy switching between front and back cameras.\n- 📷 **Smart Camera Selection**: Automatically selects the best rear camera (avoids ultra-wide/telephoto).\n- 🎯 **Session Management**: Prevents stale results with session-based tracking.\n- 🎨 **Customizable UI**: CSS-based styling with sensible defaults and CSS variables.\n- 📦 **TypeScript Support**: Full type definitions included out of the box.\n- 📳 **Haptic Feedback**: Standard [Web Vibration API](https://developer.mozilla.org/en-US/docs/Web/API/Vibration_API) support for successful scans (Android/Desktop).\n- 🔊 **Sound Feedback**: Optional audio cues on successful scans.\n\n---\n\n## 🏷️ Supported Barcode Formats\n\n- **2D Codes**: QR Code, PDF417\n- **Retail Codes**: EAN-13, EAN-8, UPC-A, UPC-E\n- **Industrial/Standard Codes**: Code 128, Code 39, Code 93, Codabar, ITF (Interleaved 2 of 5)\n- **Books**: ISBN-10, ISBN-13\n- **DataBar (GS1)**\n- *And more! (Powered by ZBar)*\n\n---\n\n## 📦 Installation\n\nChoose your preferred package manager:\n\n```bash\n# npm\nnpm install modern-barcode-scanner\n\n# yarn\nyarn add modern-barcode-scanner\n\n# pnpm\npnpm add modern-barcode-scanner\n```\n\n---\n\n## 🚀 Quick Start\n\nHere's a minimal example to get the scanner up and running in your React application:\n\n```tsx\nimport { useRef, useEffect } from 'react';\nimport { BarcodeScanner, BarcodeScannerRef, ScanResult } from 'modern-barcode-scanner';\n\n// Styles are auto-imported, but you can also import manually if needed:\n// import 'modern-barcode-scanner/styles.css';\n\nfunction App() {\n  const scannerRef = useRef\u003cBarcodeScannerRef\u003e(null);\n\n  const handleScan = (result: ScanResult) =\u003e {\n    console.log('📦 Barcode type:', result.typeName);\n    console.log('📄 Barcode data:', result.scanData);\n    \n    // Scanner automatically stops after detection.\n    // Call scannerRef.current?.start() to scan again!\n  };\n\n  const handleError = (error: Error) =\u003e {\n    console.error('❌ Scanner error:', error.message);\n  };\n\n  useEffect(() =\u003e {\n    // Start scanning when component mounts\n    scannerRef.current?.start();\n  }, []);\n\n  return (\n    \u003cdiv style={{ width: '100vw', height: '100vh' }}\u003e\n      \u003cBarcodeScanner\n        ref={scannerRef}\n        onScan={handleScan}\n        onError={handleError}\n        themeColor=\"#4db8a8\" // Customize the primary UI color!\n      /\u003e\n    \u003c/div\u003e\n  );\n}\n```\n\n### WebAssembly (WASM) Configuration\n\nUnder the hood, this library uses `@undecaf/zbar-wasm` which relies on WebAssembly. Depending on your bundler, you may need to explicitly exclude it from dependency optimization or configure it to serve `.wasm` files correctly.\n\n**Vite Example (`vite.config.ts`):**\n\n```typescript\nexport default defineConfig({\n  // ... other config\n  optimizeDeps: {\n    exclude: ['@undecaf/zbar-wasm']\n  }\n});\n```\n\n---\n\n## 📖 API Reference\n\n### `\u003cBarcodeScanner /\u003e` Component\n\n#### Props\n\n| Prop | Type | Default | Description |\n|------|------|---------|-------------|\n| `onScan` | `(result: ScanResult) =\u003e void` | **Required** | Callback fired when a barcode is detected. |\n| `onError` | `(error: Error) =\u003e void` | `undefined` | Callback fired when an error occurs. |\n| `onStateChange` | `(state: ScannerState) =\u003e void` | `undefined` | Callback fired when scanner state changes. |\n| `themeColor` | `string` | `'#4db8a8'` | Primary theme color for UI elements and scan line. |\n| `scanInterval` | `number` | `100` | Time between scan attempts (in ms). |\n| `enableVibration` | `boolean` | `true` | Enable haptic feedback on scan (uses `navigator.vibrate`). |\n| `vibrationDuration`| `number` | `200` | Vibration duration (in ms). |\n| `enableSound` | `boolean` | `false` | Enable sound feedback on scan. |\n| `initialFacingMode`| `'user' \\| 'environment'` | `'environment'`| Initial camera to use. |\n| `showScanLine` | `boolean` | `true` | Show scanning animation line. |\n| `showCameraSwitch` | `boolean` | `true` | Show camera switch button. |\n| `showTorchButton` | `boolean` | `true` | Show torch button (if supported). |\n| `className` | `string` | `''` | Custom CSS class for the container. |\n| `style` | `React.CSSProperties` | `undefined` | Custom inline styles for the container. |\n\n#### Ref Methods\n\nExposed via `useImperativeHandle` for direct control:\n\n```tsx\ninterface BarcodeScannerRef {\n  start: () =\u003e Promise\u003cvoid\u003e;        // Starts the camera and scanning\n  stop: () =\u003e void;                  // Stops the camera and scanning\n  switchCamera: () =\u003e Promise\u003cvoid\u003e; // Toggles between front and back camera\n  toggleTorch: () =\u003e Promise\u003cvoid\u003e;  // Toggles the torch/flash (if supported)\n  getState: () =\u003e ScannerState;      // Returns current state\n}\n```\n\n### TypeScript Types\n\n```tsx\ninterface ScanResult {\n  typeName: string;  // e.g., 'QRCODE', 'EAN13', 'CODE128'\n  scanData: string;  // The decoded barcode string\n}\n\ninterface ScannerState {\n  isScanning: boolean;\n  facingMode: 'user' | 'environment';\n  isTorchOn: boolean;\n}\n```\n\n---\n\n## 🛠️ Advanced Usage\n\n### Using the `useScanner` Hook\n\nIf you need complete control over the UI, you can use the internal hook directly:\n\n```tsx\nimport { useScanner } from 'modern-barcode-scanner';\n\nfunction CustomScanner() {\n  const {\n    scannerState,\n    videoRef,\n    canvasRef,\n    handleScan,\n    handleStopScan,\n    handleSwitchCamera,\n    handleToggleTorch,\n  } = useScanner({\n    onScan: (result) =\u003e console.log('Scanned:', result),\n    onError: (error) =\u003e console.error('Error:', error),\n    enableVibration: true,\n  });\n\n  return (\n    \u003cdiv\u003e\n      \u003cvideo ref={videoRef} autoPlay muted playsInline /\u003e\n      \u003ccanvas ref={canvasRef} hidden /\u003e\n      \n      \u003cdiv className=\"controls\"\u003e\n        \u003cbutton onClick={handleScan}\u003e▶️ Start\u003c/button\u003e\n        \u003cbutton onClick={handleStopScan}\u003e⏹️ Stop\u003c/button\u003e\n        \u003cbutton onClick={handleSwitchCamera}\u003e🔄 Switch\u003c/button\u003e\n        {scannerState.isTorchOn ? '🔦 On' : '🔦 Off'}\n      \u003c/div\u003e\n    \u003c/div\u003e\n  );\n}\n```\n\n### Helper Utilities\n\nThe library exports several useful utilities:\n\n```tsx\nimport { \n  isPhone, \n  getBestRearCamera, \n  getMediaConstraints \n} from 'modern-barcode-scanner';\n\n// 📱 Check if device is a phone/tablet\nconst isMobile = isPhone();\n\n// 📷 Get the optimal rear camera device ID (avoids ultra-wide lenses)\nconst cameraId = await getBestRearCamera();\n\n// ⚙️ Get optimized media constraints based on facing mode\nconst constraints = await getMediaConstraints('environment');\n```\n\n---\n\n## 🎨 Styling\n\nThe component uses CSS prefix `mbs-` (Modern Barcode Scanner) and supports native CSS variables for easy theming.\n\n### CSS Variables\n\nYou can easily override the primary color globally or via the `themeColor` prop:\n```css\n:root {\n  --mbs-primary: #ff0055; /* Changes scan line and active icon colors */\n}\n```\n\n### Overriding Classes\n\n```css\n/* Custom container styling */\n.mbs-container {\n  border-radius: 1rem;\n  box-shadow: 0 4px 6px rgba(0,0,0,0.1);\n}\n\n/* Custom scan line */\n.mbs-scan-line {\n  height: 3px;\n  box-shadow: 0 0 15px 3px var(--mbs-primary);\n}\n\n/* Custom control buttons */\n.mbs-control-btn {\n  background-color: rgba(255, 255, 255, 0.2);\n  backdrop-filter: blur(4px);\n}\n```\n\n---\n\n## 🌐 Browser Support\n\n| Browser / OS | Version |\n|--------------|---------|\n| 🟢 Google Chrome | 79+ |\n| 🔵 Microsoft Edge | 79+ |\n| 🟠 Mozilla Firefox | 79+ |\n| 🧭 Safari (macOS) | 14.1+ |\n| 📱 Chrome for Android | Supported |\n| 🍎 Safari on iOS | 14.5+ |\n\n\u003e **⚠️ Note**: Camera access requires a secure context (**HTTPS**) in production environments!\n\n---\n\n## ⚡ Performance Optimizations\n\nThis library is built for speed and reliability:\n1. **Web Worker Processing**: Barcode detection runs entirely off the main thread.\n2. **Grayscale Conversion**: Uses bitwise operations for incredibly fast image matrix processing.\n3. **Frame Throttling**: Configurable `scanInterval` perfectly balances detection speed with device battery/CPU usage.\n4. **Session Management**: Strictly prevents processing out-of-date or stale video frames.\n5. **Smart Downscaling**: Intelligently reduces image resolution for faster processing while maintaining read quality.\n6. **Canvas Optimizations**: Utilizes `willReadFrequently` and `desynchronized` rendering hints where supported.\n\n---\n\n## 📝 License\n\nMIT © [Sumit Sahoo](https://github.com/sumitsahoo)\n\nPlease refer to the [LICENSE](./LICENSE) file for the full text.\n\n---\n\n## 🤝 Credits\n\n- Powerful barcode detection engine powered by [ZBar WASM](https://github.com/nickinchern/nickinchern-undecaf-zbar-wasm).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsumitsahoo%2Fmodern-barcode-scanner","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsumitsahoo%2Fmodern-barcode-scanner","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsumitsahoo%2Fmodern-barcode-scanner/lists"}