https://github.com/sumitsahoo/modern-barcode-scanner
A modern barcode scanner library
https://github.com/sumitsahoo/modern-barcode-scanner
barcode-scanner library typescript wasm zbar
Last synced: 2 months ago
JSON representation
A modern barcode scanner library
- Host: GitHub
- URL: https://github.com/sumitsahoo/modern-barcode-scanner
- Owner: sumitsahoo
- License: mit
- Created: 2026-03-02T10:11:25.000Z (3 months ago)
- Default Branch: main
- Last Pushed: 2026-03-25T15:10:44.000Z (3 months ago)
- Last Synced: 2026-03-26T17:41:24.107Z (2 months ago)
- Topics: barcode-scanner, library, typescript, wasm, zbar
- Language: TypeScript
- Homepage: https://www.npmjs.com/package/modern-barcode-scanner
- Size: 170 KB
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Funding: .github/FUNDING.yml
- License: LICENSE
Awesome Lists containing this project
README
đˇ Modern Barcode Scanner
A high-performance barcode scanner React component with optimized detection, camera switching, torch control, and automatic phone detection.



[](https://badge.socket.dev/npm/package/modern-barcode-scanner)
[](https://opensource.org/licenses/MIT)
---
## ⨠Features
- đ **High Performance**: Web Worker-based scanning with optimized grayscale conversion.
- đą **Mobile Optimized**: Automatic phone detection with appropriate camera selection.
- đĻ **Torch Control**: Built-in torch/flash support for low-light scanning.
- đ **Camera Switching**: Easy switching between front and back cameras.
- đˇ **Smart Camera Selection**: Automatically selects the best rear camera (avoids ultra-wide/telephoto).
- đ¯ **Session Management**: Prevents stale results with session-based tracking.
- đ¨ **Customizable UI**: CSS-based styling with sensible defaults and CSS variables.
- đĻ **TypeScript Support**: Full type definitions included out of the box.
- đŗ **Haptic Feedback**: Standard [Web Vibration API](https://developer.mozilla.org/en-US/docs/Web/API/Vibration_API) support for successful scans (Android/Desktop).
- đ **Sound Feedback**: Optional audio cues on successful scans.
---
## đˇī¸ Supported Barcode Formats
- **2D Codes**: QR Code, PDF417
- **Retail Codes**: EAN-13, EAN-8, UPC-A, UPC-E
- **Industrial/Standard Codes**: Code 128, Code 39, Code 93, Codabar, ITF (Interleaved 2 of 5)
- **Books**: ISBN-10, ISBN-13
- **DataBar (GS1)**
- *And more! (Powered by ZBar)*
---
## đĻ Installation
Choose your preferred package manager:
```bash
# npm
npm install modern-barcode-scanner
# yarn
yarn add modern-barcode-scanner
# pnpm
pnpm add modern-barcode-scanner
```
---
## đ Quick Start
Here's a minimal example to get the scanner up and running in your React application:
```tsx
import { useRef, useEffect } from 'react';
import { BarcodeScanner, BarcodeScannerRef, ScanResult } from 'modern-barcode-scanner';
// Styles are auto-imported, but you can also import manually if needed:
// import 'modern-barcode-scanner/styles.css';
function App() {
const scannerRef = useRef(null);
const handleScan = (result: ScanResult) => {
console.log('đĻ Barcode type:', result.typeName);
console.log('đ Barcode data:', result.scanData);
// Scanner automatically stops after detection.
// Call scannerRef.current?.start() to scan again!
};
const handleError = (error: Error) => {
console.error('â Scanner error:', error.message);
};
useEffect(() => {
// Start scanning when component mounts
scannerRef.current?.start();
}, []);
return (
);
}
```
### WebAssembly (WASM) Configuration
Under 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.
**Vite Example (`vite.config.ts`):**
```typescript
export default defineConfig({
// ... other config
optimizeDeps: {
exclude: ['@undecaf/zbar-wasm']
}
});
```
---
## đ API Reference
### `` Component
#### Props
| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `onScan` | `(result: ScanResult) => void` | **Required** | Callback fired when a barcode is detected. |
| `onError` | `(error: Error) => void` | `undefined` | Callback fired when an error occurs. |
| `onStateChange` | `(state: ScannerState) => void` | `undefined` | Callback fired when scanner state changes. |
| `themeColor` | `string` | `'#4db8a8'` | Primary theme color for UI elements and scan line. |
| `scanInterval` | `number` | `100` | Time between scan attempts (in ms). |
| `enableVibration` | `boolean` | `true` | Enable haptic feedback on scan (uses `navigator.vibrate`). |
| `vibrationDuration`| `number` | `200` | Vibration duration (in ms). |
| `enableSound` | `boolean` | `false` | Enable sound feedback on scan. |
| `initialFacingMode`| `'user' \| 'environment'` | `'environment'`| Initial camera to use. |
| `showScanLine` | `boolean` | `true` | Show scanning animation line. |
| `showCameraSwitch` | `boolean` | `true` | Show camera switch button. |
| `showTorchButton` | `boolean` | `true` | Show torch button (if supported). |
| `className` | `string` | `''` | Custom CSS class for the container. |
| `style` | `React.CSSProperties` | `undefined` | Custom inline styles for the container. |
#### Ref Methods
Exposed via `useImperativeHandle` for direct control:
```tsx
interface BarcodeScannerRef {
start: () => Promise; // Starts the camera and scanning
stop: () => void; // Stops the camera and scanning
switchCamera: () => Promise; // Toggles between front and back camera
toggleTorch: () => Promise; // Toggles the torch/flash (if supported)
getState: () => ScannerState; // Returns current state
}
```
### TypeScript Types
```tsx
interface ScanResult {
typeName: string; // e.g., 'QRCODE', 'EAN13', 'CODE128'
scanData: string; // The decoded barcode string
}
interface ScannerState {
isScanning: boolean;
facingMode: 'user' | 'environment';
isTorchOn: boolean;
}
```
---
## đ ī¸ Advanced Usage
### Using the `useScanner` Hook
If you need complete control over the UI, you can use the internal hook directly:
```tsx
import { useScanner } from 'modern-barcode-scanner';
function CustomScanner() {
const {
scannerState,
videoRef,
canvasRef,
handleScan,
handleStopScan,
handleSwitchCamera,
handleToggleTorch,
} = useScanner({
onScan: (result) => console.log('Scanned:', result),
onError: (error) => console.error('Error:', error),
enableVibration: true,
});
return (
âļī¸ Start
âšī¸ Stop
đ Switch
{scannerState.isTorchOn ? 'đĻ On' : 'đĻ Off'}
);
}
```
### Helper Utilities
The library exports several useful utilities:
```tsx
import {
isPhone,
getBestRearCamera,
getMediaConstraints
} from 'modern-barcode-scanner';
// đą Check if device is a phone/tablet
const isMobile = isPhone();
// đˇ Get the optimal rear camera device ID (avoids ultra-wide lenses)
const cameraId = await getBestRearCamera();
// âī¸ Get optimized media constraints based on facing mode
const constraints = await getMediaConstraints('environment');
```
---
## đ¨ Styling
The component uses CSS prefix `mbs-` (Modern Barcode Scanner) and supports native CSS variables for easy theming.
### CSS Variables
You can easily override the primary color globally or via the `themeColor` prop:
```css
:root {
--mbs-primary: #ff0055; /* Changes scan line and active icon colors */
}
```
### Overriding Classes
```css
/* Custom container styling */
.mbs-container {
border-radius: 1rem;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}
/* Custom scan line */
.mbs-scan-line {
height: 3px;
box-shadow: 0 0 15px 3px var(--mbs-primary);
}
/* Custom control buttons */
.mbs-control-btn {
background-color: rgba(255, 255, 255, 0.2);
backdrop-filter: blur(4px);
}
```
---
## đ Browser Support
| Browser / OS | Version |
|--------------|---------|
| đĸ Google Chrome | 79+ |
| đĩ Microsoft Edge | 79+ |
| đ Mozilla Firefox | 79+ |
| đ§ Safari (macOS) | 14.1+ |
| đą Chrome for Android | Supported |
| đ Safari on iOS | 14.5+ |
> **â ī¸ Note**: Camera access requires a secure context (**HTTPS**) in production environments!
---
## ⥠Performance Optimizations
This library is built for speed and reliability:
1. **Web Worker Processing**: Barcode detection runs entirely off the main thread.
2. **Grayscale Conversion**: Uses bitwise operations for incredibly fast image matrix processing.
3. **Frame Throttling**: Configurable `scanInterval` perfectly balances detection speed with device battery/CPU usage.
4. **Session Management**: Strictly prevents processing out-of-date or stale video frames.
5. **Smart Downscaling**: Intelligently reduces image resolution for faster processing while maintaining read quality.
6. **Canvas Optimizations**: Utilizes `willReadFrequently` and `desynchronized` rendering hints where supported.
---
## đ License
MIT Š [Sumit Sahoo](https://github.com/sumitsahoo)
Please refer to the [LICENSE](./LICENSE) file for the full text.
---
## đ¤ Credits
- Powerful barcode detection engine powered by [ZBar WASM](https://github.com/nickinchern/nickinchern-undecaf-zbar-wasm).