Skip to the content.

Configuration Reference

Complete reference for all Quagga2 configuration options.

Configuration Object Structure

The configuration object passed to Quagga.init() defines all aspects of barcode detection and decoding:

{
  locate: true,
  inputStream: { ... },
  frequency: 10,
  decoder: { ... },
  locator: { ... },
  debug: false
}

Top-Level Properties

locate

Type: boolean

Default: true

Description: Controls whether Quagga attempts to locate the barcode in the image.

When to use true (default):

When to use false:

Example:

Quagga.init({
  locate: false,  // Expect barcode in center
  inputStream: {
    area: {  // Define scan area
      top: "25%",
      right: "25%",
      left: "25%",
      bottom: "25%"
    }
  }
});

Performance Impact: Disabling locate significantly improves performance but requires barcode to be properly positioned.

inputStream

Type: object

Description: Defines the source of images/video for barcode detection.

See inputStream Configuration below for complete details.

frequency

Type: number (optional)

Default: unlimited (processes as fast as possible, limited by requestAnimationFrame which typically matches display refresh rate)

Description: Maximum scans per second. Controls how often frames are processed.

Important: frequency specifies a maximum rate, not an absolute rate. If the system cannot achieve the requested frequency due to CPU limitations, decoding complexity, or other factors, scans will occur as fast as the system allows. For example, if you set frequency: 10 but your system can only process 8 scans per second, you will get approximately 8 scans per second.

Example:

Quagga.init({
  frequency: 10  // Process max 10 frames per second
});

Use cases:

decoder

Type: object

Description: Configuration for barcode decoding.

See Decoder Configuration below for complete details.

locator

Type: object

Description: Configuration for barcode localization algorithm.

See Locator Configuration below for complete details.

debug

Type: boolean

Default: false

Description: Enables global debug mode. When true and running development build:

Note: More fine-grained debug control is available via inputStream.debug, decoder.debug, and locator.debug. See Debug Flags Guide.

canvas

Type: object

Description: Configuration for canvas elements used by Quagga.

See Canvas Configuration below for complete details.

inputStream Configuration

Controls the source and properties of the image/video stream.

inputStream Structure

inputStream: {
  type: "LiveStream",
  target: document.querySelector('#scanner'),  // or '#scanner'
  constraints: {
    width: 640,
    height: 480,
    facingMode: "environment",
    deviceId: "abc123...",
    aspectRatio: 1.333
  },
  area: {
    top: "0%",
    right: "0%",
    left: "0%",
    bottom: "0%"
  },
  singleChannel: false,
  debug: {
    showImageDetails: false
  }
}

inputStream.type

Type: string

Options: "LiveStream" "VideoStream" "ImageStream"

Description: Type of input source.

LiveStream (default):

VideoStream:

ImageStream:

inputStream.target

Type: HTMLElement | string

Description: DOM element or CSS selector where Quagga renders the video/canvas.

Examples:

// Direct element reference
target: document.querySelector('#scanner-container')

// CSS selector
target: '#scanner-container'

// Default if omitted: '#interactive.viewport'

inputStream.constraints

Type: object

Description: MediaStream constraints for camera selection and configuration. Follows MediaTrackConstraints spec.

Common Properties:

constraints: {
  width: { ideal: 1280 },      // Preferred width
  height: { ideal: 720 },      // Preferred height
  facingMode: "environment",    // "user" (front) or "environment" (back)
  deviceId: "abc123...",        // Specific camera by ID
  aspectRatio: { ideal: 1.777 } // 16:9 aspect ratio
}

Constraint Types:

// Exact value (strict)
width: { exact: 1920 }

// Ideal value (preferred, not required)
width: { ideal: 1920 }

// Range
width: { min: 640, max: 1920 }

// Simple value (treated as ideal)
width: 1280

facingMode:

Example - High Resolution:

constraints: {
  width: { ideal: 1920 },
  height: { ideal: 1080 },
  facingMode: "environment"
}

Example - Specific Camera:

// First, enumerate devices
const devices = await Quagga.CameraAccess.enumerateVideoDevices();
const backCamera = devices.find(d => d.label.includes('back'));

// Then use deviceId
constraints: {
  deviceId: { exact: backCamera.deviceId }
}

inputStream.area

Type: object

Description: Defines rectangular region for detection/localization as percentage offsets. Also supports visual styling options for the scan area.

Structure:

area: {
  top: "0%",     // Offset from top
  right: "0%",   // Offset from right
  left: "0%",    // Offset from left
  bottom: "0%",  // Offset from bottom
  borderColor: undefined,  // Border color (draws border when defined)
  borderWidth: undefined,  // Border width in pixels (draws border when > 0)
  backgroundColor: undefined  // Background fill color
}

Example - Center Rectangle with Border:

area: {
  top: "25%",
  right: "25%",
  left: "25%",
  bottom: "25%",
  borderColor: "rgba(0, 255, 0, 0.7)",  // Green border
  borderWidth: 3
}
// Results in a 50% x 50% rectangle in the center with a green border

Example - Scan Area with Background Tint:

area: {
  top: "10%",
  right: "10%",
  left: "10%",
  bottom: "10%",
  borderColor: "red",
  borderWidth: 2,
  backgroundColor: "rgba(0, 255, 0, 0.1)"  // Light green tint
}

Use cases:

inputStream.area.borderColor

Type: string

Default: undefined (no border drawn)

Description: Color of the area border. When defined, draws a rectangle on the overlay canvas showing the scan area boundaries. Requires canvas.createOverlay: true (default). Can be any valid CSS color value.

Example:

area: {
  top: '25%',
  bottom: '25%',
  borderColor: 'red'  // Red border
  // or: 'rgba(255, 0, 0, 0.7)'  // Semi-transparent red
}

inputStream.area.borderWidth

Type: number

Default: undefined (uses default of 2 when borderColor is defined)

Description: Width of the area border line in pixels. When defined with a value > 0, draws a rectangle on the overlay canvas.

Example:

area: {
  top: '25%',
  bottom: '25%',
  borderColor: 'green',
  borderWidth: 5  // Thicker border for visibility
}

inputStream.area.backgroundColor

Type: string

Default: undefined (no background fill)

Description: Background color to fill the scan area. Can be any valid CSS color value. Useful for tinting the scan area to make it more visible.

Example:

area: {
  top: '10%',
  right: '10%',
  bottom: '10%',
  left: '10%',
  backgroundColor: 'rgba(0, 255, 0, 0.1)'  // Light green tint
}

Drawing Behavior

Note: When locate: false, the actual adjusted scanning area dimensions (after patch alignment) are available in result.boxes[0] within callbacks like onProcessed. These dimensions may differ slightly from percentage-based calculations due to rounding to patch size multiples. See Result Properties in the API reference for details.

inputStream.singleChannel

Type: boolean

Default: false

Description: When true, only reads the red color channel instead of converting to grayscale.

Use cases:

inputStream.size

Type: number

Default: 800 when using decodeSingle(); 0 (original image dimensions) otherwise

Description: Scales the input image so that the longest side (width or height) equals this value, maintaining aspect ratio.

Important: When using decodeSingle(), the default is size: 800. This means images are automatically scaled to 800px on their longest side (both larger and smaller images are scaled to match this value) unless you explicitly specify a different value. When using init(), no default scaling is applied - original dimensions are used unless you specify a size. The box, boxes, and line coordinates in the result are returned in the scaled coordinate space, not the original image dimensions. To use the original image size without any scaling, set inputStream.size to 0. See Working with Box Coordinates for details on handling scaled coordinates.

Note on Scaling: This parameter scales images both up and down. While upscaling typically introduces interpolation artifacts, testing has shown that moderate upscaling can actually improve barcode detection accuracy, even with halfSample:false. The benefits include:

Scaling Guidelines:

Recommended approach: Experiment with different scaling factors. Start with 2x (e.g., 1600-2200 for typical barcode images), then try lower values if needed. The optimal value varies by image content and quality.

Example:

// Default behavior: decodeSingle uses size: 800 by default
Quagga.decodeSingle({
  src: "./large-image.jpg",  // 3000x2000 image
  // size defaults to 800, so this scales down to 800x533
  // Result coordinates (box, line) will be in 800x533 space
});

// Override to preserve larger processing resolution
Quagga.decodeSingle({
  src: "./large-image.jpg",  // 3000x2000 image
  inputStream: {
    size: 1600  // Scales down to 1600x1067
  }
});

// Disable scaling entirely - use original image dimensions
Quagga.decodeSingle({
  src: "./medium-image.jpg",  // 1280x720 image
  inputStream: {
    size: 0  // Zero disables scaling, uses original 1280x720
  }
});

// Upscale for fine details (can improve detection)
Quagga.decodeSingle({
  src: "./small-barcode.jpg",  // 1100x658 image with fine barcode
  inputStream: {
    size: 1600  // Scales up to 1600x957, may improve detection
  }
});

Performance Note: Higher values increase processing time. Balance detection accuracy against speed based on your use case. Test different values to find the optimal setting for your specific images.

inputStream.debug

Type: object

Description: Enable console logging for input stream diagnostics.

debug: {
  showImageDetails: false  // Log frame grabber operations
}

inputStream.debug.showImageDetails

Type: boolean

Default: false

Description: Logs frame grabber info, canvas size adjustments, and image loading details to the console.

See Debug Flags Guide for details.

inputStream.sequence (ImageStream only)

Type: boolean (default: false)

Description: When set to true and used with type: 'ImageStream', Quagga will load a sequence of images named image-001.jpg, image-002.jpg, etc., from the base path specified by src, starting at the offset index and loading size images.

Note: Sequence mode currently only supports .jpg files. Images with other extensions (e.g., .png) will not be loaded. If you need support for other formats, see the related feature request or use single image mode.

Related Properties:

Example:

Quagga.init({
  inputStream: {
    type: 'ImageStream',
    src: '/path/to/images/', // Base path for images
    sequence: true,
    size: 3, // Number of images to load
    offset: 1 // Starting index (optional)
  },
  decoder: { readers: ['code_128_reader'] }
});

This will load /path/to/images/image-001.jpg, /path/to/images/image-002.jpg, /path/to/images/image-003.jpg.

Sequence mode is ideal for batch testing or processing multiple images with predictable filenames.

Decoder Configuration

Controls barcode detection and decoding behavior.

Decoder Structure

decoder: {
  readers: ["code_128_reader"],
  debug: {
    drawBoundingBox: false,
    showFrequency: false,
    drawScanline: false,
    showPattern: false,
    printReaderInfo: false
  },
  multiple: false
}

decoder.readers

Type: Array<string | object>

Required: Yes

Description: Array of barcode reader types to use.

Available Readers:

See Supported Barcode Types for complete details.

Simple Example:

readers: ["code_128_reader", "ean_reader"]

With Configuration (e.g., EAN extensions):

readers: [
  "ean_reader",  // Regular EAN without extensions
  {
    format: "ean_reader",
    config: {
      supplements: ['ean_5_reader', 'ean_2_reader']
    }
  }  // EAN with 2 or 5 digit extensions
]

Important: Readers are processed in the exact order specified. The first reader to successfully decode wins. List most common/expected formats first for better performance and accuracy. See Reader Priority for details.

decoder.debug

Type: object

Description: Enable visual debug overlays and console logging for decoder.

debug: {
  drawBoundingBox: false,    // Draw box around detected barcode
  showFrequency: false,      // Display frequency data
  drawScanline: false,       // Draw the scan line
  showPattern: false,        // Display pattern data
  printReaderInfo: false     // Log reader registration to console
}

See Debug Flags Guide for details.

decoder.multiple

Type: boolean

Default: false

Description: When true, continues decoding after finding a barcode to detect multiple barcodes in a single image.

Example:

decoder: {
  readers: ["code_128_reader"],
  multiple: true
}

Result format: When true, the result is an array of result objects:

Quagga.onDetected(function(results) {
  // results is an array
  results.forEach(function(result) {
    if (result.codeResult) {
      console.log("Found:", result.codeResult.code);
    }
  });
});

Locator Configuration

Controls the barcode localization algorithm. Only relevant when locate: true.

Locator Structure

locator: {
  halfSample: true,
  patchSize: "medium",
  debug: {
    showCanvas: false,
    showPatches: false,
    showFoundPatches: false,
    showSkeleton: false,
    showLabels: false,
    showPatchLabels: false,
    showRemainingPatchLabels: false,
    showPatchSize: false,
    showImageDetails: false,
    boxFromPatches: {
      showTransformed: false,
      showTransformedBox: false,
      showBB: false
    }
  }
}

locator.halfSample

Type: boolean

Default: true

Description: When true, operates on image scaled to half width/height (quarter pixel count).

Benefits of true (recommended):

When to use false:

Recommendation: Keep true and increase camera resolution if needed, rather than disabling half-sampling.

locator.patchSize

Type: string

Options: "x-small" "small" "medium" "large" "x-large"

Default: "medium"

Description: Controls search grid density. Affects how the locator divides the image for analysis.

Size Guidelines:

Patch Size Barcode Distance Use Case
x-small Far away Small barcodes, poor focus, low resolution
small Moderately far Small to medium barcodes
medium Normal General purpose (recommended default)
large Close up Large barcodes held close to camera
x-large Very close Very large barcodes, macro shots

Relationship to Resolution:

Example - Small Distant Barcodes:

locator: {
  patchSize: "small",
  halfSample: true  // Keep half-sampling on
},
inputStream: {
  constraints: {
    width: { ideal: 1280 },  // Higher resolution compensates
    height: { ideal: 720 }
  }
}

Example - Large Close-Up Barcodes:

locator: {
  patchSize: "large",
  halfSample: true
}

locator.debug

Type: object

Description: Enable visual debug overlays and console logging for locator.

Console logging flags:

debug: {
  showPatchSize: false,      // Log calculated patch dimensions
  showImageDetails: false    // Log image wrapper and canvas details
}

Visual overlay flags:

debug: {
  showCanvas: false,                 // Show locator's internal canvas
  showPatches: false,                // Draw all extracted patches
  showFoundPatches: false,           // Highlight candidate patches
  showSkeleton: false,               // Show skeleton structure
  showLabels: false,                 // Show component labels
  showPatchLabels: false,            // Show patch labels
  showRemainingPatchLabels: false,   // Show post-filter labels
  boxFromPatches: {
    showTransformed: false,          // Show transformed coordinates
    showTransformedBox: false,       // Show transformed box
    showBB: false                    // Show final bounding box
  }
}

See Debug Flags Guide for complete details on all debug options.

Canvas Configuration

Controls the creation and management of canvas elements.

Canvas Structure

canvas: {
  createOverlay: true  // Set to false to disable overlay canvas creation
}

canvas.createOverlay

Type: boolean

Default: true

Description: Controls whether Quagga creates the overlay canvas (drawingBuffer). The overlay canvas is used for drawing bounding boxes, scan lines, and other visual feedback on top of the video stream.

When to set false:

When to keep true (default):

Example - Disable overlay canvas:

Quagga.init({
  canvas: {
    createOverlay: false  // No overlay canvas created
  },
  inputStream: {
    type: "LiveStream",
    target: '#scanner'
  },
  decoder: {
    readers: ["code_128_reader"]
  }
}, function(err) {
  if (err) {
    console.error(err);
    return;
  }
  Quagga.start();
});

Important: When createOverlay is false:

Note about debug flags: The decoder.debug.drawBoundingBox and decoder.debug.drawScanline flags only work in development builds and require the overlay canvas to exist. These flags draw on the overlay canvas when it’s available.

Example - Using overlay canvas for drawing:

// With createOverlay: true (default)
Quagga.onProcessed(function(result) {
  const ctx = Quagga.canvas.ctx.overlay;
  const canvas = Quagga.canvas.dom.overlay;

  // Check if overlay exists before using
  if (ctx && canvas) {
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    if (result && result.box) {
      Quagga.ImageDebug.drawPath(result.box, {x: 0, y: 1}, ctx, {
        color: "green",
        lineWidth: 2
      });
    }
  }
});

Complete Configuration Examples

Example 1: Live Camera Scanning

Quagga.init({
  inputStream: {
    type: "LiveStream",
    target: document.querySelector('#scanner'),
    constraints: {
      width: { ideal: 1280 },
      height: { ideal: 720 },
      facingMode: "environment"
    }
  },
  locate: true,
  frequency: 10,
  decoder: {
    readers: ["code_128_reader", "ean_reader"]
  },
  locator: {
    halfSample: true,
    patchSize: "medium"
  }
}, function(err) {
  if (err) {
    console.error(err);
    return;
  }
  Quagga.start();
});

Example 2: Static Image Processing

Quagga.decodeSingle({
  src: "/images/barcode.jpg",
  locate: true,
  decoder: {
    readers: ["code_128_reader"]
  },
  locator: {
    patchSize: "medium",
    halfSample: true
  }
}, function(result) {
  if (result && result.codeResult) {
    console.log("Code:", result.codeResult.code);
  }
});

Example 3: Guided Scanning (No Localization)

Quagga.init({
  inputStream: {
    type: "LiveStream",
    target: '#scanner',
    constraints: {
      width: 640,
      height: 480,
      facingMode: "environment"
    },
    area: {
      top: "30%",
      right: "20%",
      left: "20%",
      bottom: "30%"
    }
  },
  locate: false,  // Barcode must be centered in defined area
  decoder: {
    readers: ["ean_reader", "upc_reader"]
  }
});

Example 4: Multiple Barcode Detection

Quagga.init({
  inputStream: {
    type: "LiveStream",
    target: '#scanner'
  },
  decoder: {
    readers: ["code_128_reader"],
    multiple: true  // Detect multiple barcodes per frame
  },
  locate: true,
  locator: {
    patchSize: "medium"
  }
});

Quagga.onDetected(function(results) {
  // results is an array when multiple: true
  console.log(`Found ${results.length} barcodes`);
  results.forEach(r => {
    if (r.codeResult) {
      console.log("Code:", r.codeResult.code);
    }
  });
});

Example 5: Node.js Processing

const Quagga = require('@ericblade/quagga2').default;

Quagga.decodeSingle({
  src: "./barcode.jpg",
  inputStream: {
    size: 800  // Scale to max 800px
  },
  locate: true,
  decoder: {
    readers: ["code_128_reader", "ean_reader"]
  }
}, function(result) {
  if (result && result.codeResult) {
    console.log("Detected:", result.codeResult.code);
  } else {
    console.log("No barcode found");
  }
});

Configuration Best Practices

  1. Start simple: Use defaults, only add specific readers you need
  2. Test thoroughly: Different devices and lighting require different settings
  3. Optimize iteratively: Start with patchSize: "medium", adjust based on results
  4. Limit readers: Only enable barcode formats you actually expect
  5. Consider performance: Balance quality vs. speed based on use case
  6. Use constraints wisely: Higher resolution helps but costs performance
  7. Debug systematically: Enable debug flags to understand behavior

← Back to Reference