barcode-forge
v1.1.1
Published
Production-ready TypeScript library for generating barcodes in multiple formats with customizable output and React support
Maintainers
Readme
barcode-forge
Production-ready TypeScript library for generating barcodes in multiple formats with customizable output, extensible architecture, and React support.
Features
✨ Multiple Formats - CODE128, EAN13, EAN8, UPC-A, UPC-E
🎨 Customizable - Colors, sizes, margins, fonts
📦 Multiple Outputs - PNG, SVG, Data URL
⚛️ React Ready - <Barcode> component and useBarcode hook
🔍 Logo Support - Embed logos in barcodes (SVG)
✅ Validation - Auto-checksum calculation and validation
🔧 Extensible - Register custom formats and validators
📘 TypeScript - Full type safety with strict mode
🌳 Tree-shakable - ESM + CommonJS, optimized builds
🧪 Well-tested - Comprehensive test coverage
Installation
npm install barcode-forgeQuick Start
import { generateBarcode } from 'barcode-forge';
// Generate a basic barcode
const result = await generateBarcode({
value: 'TEST123',
format: 'CODE128',
});
// result.buffer contains PNG buffer
console.log(result.buffer);Usage Examples
Basic CODE128 Barcode
import { generateBarcode } from 'barcode-forge';
const result = await generateBarcode({
value: 'HELLO-WORLD',
format: 'CODE128',
});
// Save to file (Node.js)
import { writeFile } from 'fs/promises';
await writeFile('barcode.png', result.buffer!);EAN13 Product Barcode
// EAN13 with automatic checksum calculation
const result = await generateBarcode({
value: '123456789012', // 12 digits, checksum added automatically
format: 'EAN13',
width: 250,
height: 120,
});SVG Output
const result = await generateBarcode({
value: 'SVG-EXAMPLE',
format: 'CODE128',
output: 'svg',
});
console.log(result.svg); // SVG stringData URL for Browser
const result = await generateBarcode({
value: 'DATA-URL',
format: 'CODE128',
output: 'dataurl',
});
// Use in HTML
const img = document.createElement('img');
img.src = result.dataUrl!;
document.body.appendChild(img);Custom Colors and Size
const result = await generateBarcode({
value: '123456789012',
format: 'EAN13',
width: 300,
height: 150,
lineColor: '#FF0000', // Red bars
background: '#FFFF00', // Yellow background
margin: 20,
fontSize: 14,
});Hide Text Display
const result = await generateBarcode({
value: 'NO-TEXT',
format: 'CODE128',
displayValue: false, // Hide human-readable text
});Barcode with Logo (SVG only)
const result = await generateBarcode({
value: 'BRANDED',
format: 'CODE128',
output: 'svg',
logo: './company-logo.png', // Local path, URL, or data URL
logoWidth: 50,
logoHeight: 50,
logoPosition: 'center', // 'top', 'center', or 'bottom'
});UPC-A Barcode
const result = await generateBarcode({
value: '12345678901', // 11 digits, checksum added automatically
format: 'UPC-A',
});All Available Options
const result = await generateBarcode({
// Required
value: 'YOUR-DATA',
// Optional
format: 'CODE128', // 'CODE128' | 'EAN13' | 'EAN8' | 'UPC-A' | 'UPC-E' | string
width: 200, // Width in pixels
height: 100, // Height in pixels
margin: 10, // Margin in pixels
displayValue: true, // Show text under barcode
fontSize: 10, // Font size for text
lineColor: '#000000', // Barcode color (hex)
background: '#FFFFFF', // Background color (hex)
output: 'png', // 'png' | 'svg' | 'dataurl'
// Logo options (SVG output only)
logo: './logo.png', // Path, URL, or data URL
logoWidth: 50, // Logo width
logoHeight: 50, // Logo height
logoPosition: 'center', // 'top' | 'center' | 'bottom'
});API Reference
generateBarcode(options: BarcodeOptions): Promise<BarcodeResult>
Generate a barcode with the specified options.
Parameters
options.value(string, required) - The data to encodeoptions.format(BarcodeFormat) - Barcode format (default: 'CODE128')options.width(number) - Width in pixels (default: 200)options.height(number) - Height in pixels (default: 100)options.margin(number) - Margin in pixels (default: 10)options.displayValue(boolean) - Show text (default: true)options.fontSize(number) - Font size (default: 10)options.lineColor(string) - Bar color (default: '#000000')options.background(string) - Background color (default: '#FFFFFF')options.output(OutputFormat) - Output format (default: 'png')options.logo(string) - Logo path/URL (optional)options.logoWidth(number) - Logo width (default: 50)options.logoHeight(number) - Logo height (default: 50)options.logoPosition(LogoPosition) - Logo position (default: 'center')options.scale(number) - Scale multiplier for higher-DPI output (default: auto)
Returns
Promise resolving to BarcodeResult:
interface BarcodeResult {
format: 'png' | 'svg' | 'dataurl';
buffer?: Buffer; // PNG output
svg?: string; // SVG output
dataUrl?: string; // Data URL output
width: number;
height: number;
}Throws
BarcodeValidationError- Invalid value for the formatBarcodeGenerationError- Barcode generation failedLogoEmbedError- Logo embedding failed
Supported Formats
| Format | Description | Length | Checksum | |--------|-------------|--------|----------| | CODE128 | High-density linear barcode | Variable | Auto | | EAN13 | European Article Number | 12-13 digits | Auto | | EAN8 | Compact EAN for small products | 7-8 digits | Auto | | UPC-A | Universal Product Code | 11-12 digits | Auto | | UPC-E | Compressed UPC | 7-8 digits | Auto |
Validation
The library automatically validates input values:
// ✅ Valid - checksum added automatically
await generateBarcode({ value: '123456789012', format: 'EAN13' });
// ❌ Invalid - wrong length
await generateBarcode({ value: '12345', format: 'EAN13' });
// Throws: BarcodeValidationError: EAN13 must be 12 or 13 digits
// ❌ Invalid - wrong checksum
await generateBarcode({ value: '1234567890120', format: 'EAN13' });
// Throws: BarcodeValidationError: EAN13 check digit is invalid
// ❌ Invalid - non-ASCII characters
await generateBarcode({ value: 'TEST™', format: 'CODE128' });
// Throws: BarcodeValidationError: CODE128 can only encode ASCII charactersReact
The library ships with first-class React bindings. Import from barcode-forge/react:
npm install barcode-forge react<Barcode> Component
import { Barcode } from 'barcode-forge/react';
function App() {
return (
<Barcode
value="HELLO-WORLD"
format="CODE128"
output="svg"
lineColor="#003366"
className="my-barcode"
fallback={<span>Loading…</span>}
onError={(err) => <span>Error: {err.message}</span>}
/>
);
}Props
All BarcodeOptions fields are accepted as props, plus:
| Prop | Type | Description |
|------|------|-------------|
| id | string | HTML id for the wrapper element |
| className | string | CSS class for the wrapper element |
| style | React.CSSProperties | Inline styles |
| fallback | React.ReactNode | Shown while loading |
| onError | (error: Error) => ReactNode | Shown on error |
Defaults to SVG output in the browser (no Node Buffer needed).
useBarcode Hook
import { useBarcode } from 'barcode-forge/react';
function MyBarcode() {
const { svg, loading, error } = useBarcode({
value: '1234567890128',
format: 'EAN13',
output: 'svg',
});
if (loading) return <span>Generating…</span>;
if (error) return <span>Error: {error.message}</span>;
if (!svg) return null;
return <div dangerouslySetInnerHTML={{ __html: svg }} />;
}Return Value
interface UseBarcodeReturn {
result: BarcodeResult | null; // Full result object
svg: string | null; // SVG string shortcut
dataUrl: string | null; // Data-URL shortcut
loading: boolean; // Generation in progress
error: Error | null; // Error if failed
}The hook automatically regenerates the barcode when any option changes.
Extensibility
Adding Custom Formats
import { registerFormat, generateBarcode } from 'barcode-forge';
// Register a custom format
registerFormat('CODE39', {
bcid: 'code39',
description: 'CODE39 barcode format',
options: {
includecheck: true,
},
});
// Use the custom format — no type assertion needed
const result = await generateBarcode({
value: 'CUSTOM',
format: 'CODE39',
});Custom Validators
import { registerValidator, BarcodeValidator } from 'barcode-forge';
class MyValidator implements BarcodeValidator {
validate(value: string): void {
if (value.length < 5) {
throw new Error('Value too short');
}
}
addChecksum(value: string): string {
return value + '0';
}
}
registerValidator('CODE128', new MyValidator());TypeScript Support
Full TypeScript support with strict mode enabled:
import type {
BarcodeOptions,
BarcodeResult,
BarcodeFormat,
OutputFormat,
} from 'barcode-forge';
const options: BarcodeOptions = {
value: 'TEST',
format: 'CODE128',
};
const result: BarcodeResult = await generateBarcode(options);Error Handling
import {
generateBarcode,
BarcodeValidationError,
BarcodeGenerationError,
LogoEmbedError,
} from 'barcode-forge';
try {
const result = await generateBarcode({
value: 'invalid',
format: 'EAN13',
});
} catch (error) {
if (error instanceof BarcodeValidationError) {
console.error('Validation failed:', error.message);
console.error('Format:', error.format);
console.error('Value:', error.value);
} else if (error instanceof BarcodeGenerationError) {
console.error('Generation failed:', error.message);
} else if (error instanceof LogoEmbedError) {
console.error('Logo embedding failed:', error.message);
}
}Browser Support
The library supports both Node.js and browsers:
Node.js
import { generateBarcode } from 'barcode-forge';
import { writeFile } from 'fs/promises';
const result = await generateBarcode({ value: 'TEST' });
await writeFile('barcode.png', result.buffer!);Browser (with bundler)
import { generateBarcode } from 'barcode-forge';
const result = await generateBarcode({
value: 'TEST',
output: 'dataurl',
});
const img = document.createElement('img');
img.src = result.dataUrl!;
document.body.appendChild(img);Performance Tips
- Use SVG for scalability - SVG output is smaller and scales without quality loss
- Reuse configurations - Create a config object and reuse it
- Batch operations - Generate multiple barcodes in parallel with
Promise.all() - Optimize logo size - Use appropriately sized logos to avoid performance issues
// Good: Parallel generation
const barcodes = await Promise.all([
generateBarcode({ value: 'ITEM1' }),
generateBarcode({ value: 'ITEM2' }),
generateBarcode({ value: 'ITEM3' }),
]);Contributing
Contributions are welcome! Please read our Contributing Guide for details on the development setup, workflow, how to add new barcode formats, and pull request guidelines.
- Fork the repo
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'feat: add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
See CONTRIBUTING.md for the full guide.
License
MIT © jahidulsaeid
Credits
Built with bwip-js - Barcode Writer in Pure JavaScript
