qr-code.js

QRCode.js Documentation

Introduction

QRCode.js is a professional JavaScript/TypeScript library for creating customized QR codes, offering a blend of simplicity and sophistication. With versatile styling options—dot shapes, colors, gradients, embedded images, borders, and text—it enables you to design unique, visually appealing QR codes that work flawlessly with standard scanners. QRCode.js is part of QR-Platform: All-in-One QR Codes Management Solution.

This documentation provides a comprehensive overview of all available options to help you create the perfect QR code for your needs.

Installation

# Using npm
npm install @qr-platform/qr-code.js

# Using yarn
yarn add @qr-platform/qr-code.js

# Using pnpm
pnpm add @qr-platform/qr-code.js

Basic Usage

import { QRCodeJs } from '@qr-platform/qr-code.js';

// Create a basic QR code
const qrCode = new QRCodeJs({
  data: 'https://example.com',
});

// Render the QR code to a container
qrCode.append(document.getElementById('qr-container'));

Core Options

data

shape

margin

isResponsive

qrOptions

Options that affect the QR code generation algorithm.

typeNumber

mode

errorCorrectionLevel

Layout Options

Options controlling the positioning and scaling of the QR code within its container.

scale

offset

verticalOffset

horizontalOffset

Styling Options

Dots (dotsOptions)

Controls the appearance of individual QR code dots.

type

color

size

gradient

Corner Squares (cornersSquareOptions)

These options override dotsOptions for the three large corner squares of the QR code.

type

color

gradient

Corner Dots (cornersDotOptions)

These options override cornersSquareOptions for the smaller dots within the corner squares.

type

color

gradient

Background (backgroundOptions)

Controls the QR code background.

color

round

gradient

Image Embedding

image

imageOptions

Options for the embedded image.

mode

imageSize

margin

crossOrigin

fill

Gradients

Gradients can be applied to multiple elements: dotsOptions, cornersSquareOptions, cornersDotOptions, backgroundOptions, and imageOptions.fill.

Gradient Structure

Example

{
  dotsOptions: {
    gradient: {
      type: 'linear',
      rotation: Math.PI / 4, // 45 degrees
      colorStops: [
        { offset: 0, color: '#8F00FF' }, // Start color
        { offset: 1, color: '#0080FF' }  // End color
      ]
    }
  }
}

Borders

Free vs. Premium Features

QRCode.js provides border features in both the free and premium versions, with some important differences:

borderOptions

Options for adding decorative borders around the QR code.

hasBorder

thickness

color

radius

noBorderThickness (Premium)

background (Premium)

inner (Premium)

borderOuter (Premium)

borderInner (Premium)

decorations (Premium)

Each decoration object can have these properties:

Free vs. Premium Border Examples

Free Version (with QR-Platform branding)

// Free version border - will show "QR-Platform" in bottom border
const qrCode = new QRCodeJs({
  data: 'https://example.com',
  borderOptions: {
    hasBorder: true,
    thickness: 40,
    color: '#0033CC',
    radius: '10%'
  }
});

Premium Version (license required)

// First activate license
await QRCodeJs.license('YOUR-LICENSE-KEY');

// Then create QR code with custom border text
const qrCode = new QRCodeJs({
  data: 'https://example.com',
  borderOptions: {
    hasBorder: true,
    thickness: 40,
    color: '#0033CC',
    radius: '10%',
    decorations: {
      bottom: {
        enableText: true,
        type: 'text',
        value: 'YOUR CUSTOM TEXT', // This only works with a license
        style: {
          fontFace: 'Arial',
          fontSize: 24,
          fontColor: '#FFFFFF'
        }
      }
    }
  }
});

Error Handling for Borders

When attempting to use premium border features without a license, the library will:

  1. Not throw errors, but gracefully fall back to the free version behavior
  2. Display “QR-Platform” branding in the bottom border regardless of your decorations settings
  3. Ignore certain premium-only properties like inner, borderOuter, and borderInner

To check if your license is active and premium features are available:

// Check detailed license information
const licenseDetails = QRCodeJs.getLicenseDetails();
if (licenseDetails) {
  console.log('License plan:', licenseDetails.plan);
  console.log('License expires:', new Date(licenseDetails.exp * 1000));
}

Scan Validation (Premium Feature)

Note: This is a Premium Feature requiring a license.

The QRCode.js library offers functionality to validate that generated QR codes are scannable.

validateScanning()

Node.js Usage

QRCode.js can also be used in Node.js environments.

Installation

Follow the standard installation steps using npm or yarn.

Basic Usage

import { QRCodeJs, Options } from '@qr-platform/qr-code.js/node'; // Import from '@qr-platform/qr-code.js/node'
import fs from 'fs';

const options: Options = {
  data: 'https://example.com',
};

const qrCode = new QRCodeJs(options);

qrCode.serialize().then(svgString => {
  if (svgString) {
    fs.writeFileSync('qrcode.svg', svgString);
    console.log('QR Code saved to qrcode.svg');
  }
});

Key Differences & Considerations

License Management

QRCode.js provides a comprehensive licensing system for premium features like advanced border controls and scan validation.

Free vs. Premium Features

Border Limitations in Free Version

When using the basic border features in the free version, the library will automatically add “QR-Platform” branding text in the bottom border. This branded text cannot be removed or modified without a valid license. With a premium license, you gain full control over border text and can use borders without any branding.

Activation Timing

Initialization

Persistence

Browser Environment

Node.js Environment

Activation Methods

Using a License Key (QRCodeJs.license())

Using a Pre-fetched Token (QRCodeJs.token())

Checking License Status

Getting License Details

Configuration

Setting License URL

Custom License Fetcher

Using Templates

Templates offer a convenient way to apply a consistent set of styling and configuration options across multiple QR codes. QRCode.js provides two primary methods for working with templates:

Setting Global Defaults (setTemplate)

The static method QRCodeJs.setTemplate(templateNameOrOptions) allows you to define a default template that will be automatically applied to all QRCodeJs instances created after the template is set. This is useful for establishing a baseline style for your application.

// Set a global template
QRCodeJs.setTemplate('dots');

// This QR code will use the 'dots' template
const qr1 = new QRCodeJs({ data: 'Uses global dots template' });

// Override the global template's color for this instance
const qr2 = new QRCodeJs({
  data: 'Overrides global dots color',
  dotsOptions: { color: '#FF4500' } // OrangeRed
});

// Reset to basic template
QRCodeJs.setTemplate('basic');

Using the Builder Pattern (useTemplate)

The static method QRCodeJs.useTemplate(templateNameOrOptions) initiates a builder pattern. It returns a builder object pre-configured with the specified template (either by name or by providing a partial options object directly).

// Start with the 'rounded' template, provide data and override color
const qrBuilder1 = QRCodeJs.useTemplate('rounded').options({
  data: 'Built with rounded template',
  dotsOptions: { color: '#007BFF' } // Blue override
});

// Start with inline custom options, then provide data
const qrBuilder2 = QRCodeJs.useTemplate({
  shape: 'circle',
  dotsOptions: { type: 'star', color: '#DC3545' } // Red stars
}).options({
  data: 'Built with inline circle/star template'
});

Choosing between setTemplate and useTemplate depends on whether you need a persistent global default or a one-off configuration based on a template.

Complete Examples

Basic QR Code with Custom Dots

const qrCode = new QRCodeJs({
  data: 'https://example.com',
  dotsOptions: {
    type: 'rounded',
    color: '#0033CC',
    size: 12
  }
});

qrCode.append(document.getElementById('qr-container'));

QR Code with Custom Corners and Background

const qrCode = new QRCodeJs({
  data: 'https://example.com',
  shape: 'square',
  qrOptions: {
    errorCorrectionLevel: 'H'
  },
  dotsOptions: {
    type: 'classy',
    color: '#000000'
  },
  cornersSquareOptions: {
    type: 'outpoint',
    color: '#FF0000'
  },
  cornersDotOptions: {
    type: 'dot',
    color: '#FF0000'
  },
  backgroundOptions: {
    color: '#FFECDB',
    round: 0.2
  }
});
const qrCode = new QRCodeJs({
  data: 'https://example.com',
  image: 'https://example.com/logo.png',
  imageOptions: {
    mode: 'center',
    imageSize: 0.3,
    margin: 1,
    crossOrigin: 'anonymous',
    fill: {
      color: 'rgba(255,255,255,1)'
    }
  },
  dotsOptions: {
    type: 'dot',
    color: '#4267B2'
  }
});

QR Code with Free Border (includes QR-Platform branding)

const qrCode = new QRCodeJs({
  data: 'https://example.com',
  dotsOptions: {
    type: 'rounded',
    color: '#0033CC'
  },
  borderOptions: {
    hasBorder: true,
    thickness: 50,
    color: '#002683',
    radius: '5%'
    // Note: Bottom border will automatically show "QR-Platform" text
    // This cannot be changed in the free version
  }
});

QR Code with Premium Border Features (requires license)

// Must activate license before creating QR code
await QRCodeJs.license('YOUR-LICENSE-KEY');

const qrCode = new QRCodeJs({
  data: 'https://example.com',
  dotsOptions: {
    type: 'extraRounded',
    gradient: {
      type: 'radial',
      colorStops: [
        { offset: 0, color: '#8F00FF' },
        { offset: 1, color: '#0080FF' }
      ]
    }
  },
  backgroundOptions: {
    color: '#FFFFFF',
    round: 0.1
  },
  borderOptions: {
    hasBorder: true,
    thickness: 50,
    color: '#002683',
    radius: '40%',
    // Premium feature: custom border text (no branding)
    decorations: {
      top: {
        enableText: true,
        type: 'text',
        value: 'SCAN ME',
        style: {
          fontFace: 'Helvetica',
          fontSize: 28,
          fontColor: '#ffffff',
          letterSpacing: 2,
          fontWeight: 'bold'
        }
      },
      bottom: {
        enableText: true,
        type: 'text',
        value: 'CUSTOM BOTTOM TEXT', // With license this replaces "QR-Platform"
        style: {
          fontFace: 'Arial',
          fontSize: 20,
          fontColor: '#ffffff'
        }
      }
    },
    // Premium feature: additional borders
    borderOuter: {
      color: '#001255',
      thickness: 10
    },
    borderInner: {
      color: '#334499',
      thickness: 5
    }
  }
});

QR Code with Gradients

const qrCode = new QRCodeJs({
  data: 'Gradient Example',
  dotsOptions: {
    type: 'rounded',
    gradient: {
      type: 'linear',
      rotation: Math.PI / 4,
      colorStops: [
        { offset: 0, color: '#ff5733' },
        { offset: 1, color: '#c70039' }
      ]
    }
  },
  backgroundOptions: {
    gradient: {
      type: 'radial',
      colorStops: [
        { offset: 0, color: '#ffffff' },
        { offset: 1, color: '#e0e0e0' }
      ]
    }
  },
  cornersSquareOptions: {
    type: 'dot',
    gradient: {
      type: 'linear',
      rotation: 0,
      colorStops: [
        { offset: 0, color: '#c70039' },
        { offset: 1, color: '#900c3f' }
      ]
    }
  }
});

QR Code with Border Layout Adjustments

const qrCode = new QRCodeJs({
  data: 'Layout within Border',
  scale: 0.75, // Scale the QR code down to 75% within the border
  offset: -15, // Move the QR code up slightly within the border
  dotsOptions: {
    type: 'square',
    color: '#333333'
  },
  borderOptions: {
    hasBorder: true,
    thickness: 60,
    color: '#CCCCCC',
    radius: '10%',
    decorations: {
      bottom: {
        enableText: true,
        type: 'text',
        value: 'SCALED & OFFSET',
        style: {
          fontFace: 'Arial',
          fontSize: 24,
          fontColor: '#555555',
          fontWeight: 'normal'
        }
      }
    }
  }
});

Circular QR Code with Custom Styling

const qrCode = new QRCodeJs({
  data: 'https://example.com',
  shape: 'circle',
  dotsOptions: {
    type: 'rounded',
    color: '#6200EA'
  },
  cornersDotOptions: {
    type: 'dot',
    color: '#00C853'
  },
  cornersSquareOptions: {
    type: 'rounded',
    color: '#00C853'
  },
  backgroundOptions: {
    color: '#FFFFFF'
  }
});

API Reference

Constructors

new QRCodeJs(options: QRCodeJsOptions)

Methods

append()

Appends the QR code to a container element.

qrCode.append(container: HTMLElement): QRCodeJs | undefined

serialize()

Converts the QR code to an SVG string.

qrCode.serialize(inverted?: boolean): Promise<string | undefined>

download()

Downloads the QR code as a file.

qrCode.download(
  downloadOptions?: { 
    name?: string; 
    extension: 'svg' | 'png' | 'jpeg' | 'webp' 
  },
  canvasOptions?: CanvasOptions
): Promise<void>

update()

Updates the QR code with new options.

qrCode.update(options?: RecursivePartial<Options>): void

validateScanning() (Premium)

Validates that the QR code is scannable.

qrCode.validateScanning(
  validatorId?: string,
  debug?: boolean
): Promise<ScanValidatorResponse>

Static Methods (License Management)

useTemplate()

Creates a QRCodeBuilder instance initialized with a specific template.

QRCodeJs.useTemplate(templateNameOrOptions: string | RecursivePartial<Options>): QRCodeBuilder

useStyle()

Creates a QRCodeBuilder instance initialized with a specific style.

QRCodeJs.useStyle(styleNameOrOptions: string | StyleOptions): QRCodeBuilder

These methods are called directly on the QRCodeJs class (or QRCodeJs imported from qrcode-js/node).

initializeIfNeeded()

Initializes the license manager if needed.

QRCodeJs.initializeIfNeeded(): Promise<boolean>

getLicenseDetails()

Returns the decoded token object if a valid license is active.

QRCodeJs.getLicenseDetails(): DecodedLicenseToken | null

license()

Activates a license using a license key.

QRCodeJs.license(licenseKey: string): Promise<ValidationResult>

token()

Activates a license using a pre-fetched JWT token.

QRCodeJs.token(token: string | null): Promise<ValidationResult>

configureLicenseFetcher()

Configures a custom function for fetching license tokens.

QRCodeJs.configureLicenseFetcher(fetcher: (licenseKey: string) => Promise<string>): void

setLicenseUrl()

Sets the URL endpoint for license key validation.

QRCodeJs.setLicenseUrl(url: string): void

setTemplate()

Sets a global default template for subsequent QRCodeJs instances.

QRCodeJs.setTemplate(templateNameOrOptions: string | RecursivePartial<Options>): void

useTemplate()

Initiates a builder pattern pre-configured with a template.

QRCodeJs.useTemplate(templateNameOrOptions: string | RecursivePartial<Options>): QRCodeBuilder

setStyle()

Sets a global default style for subsequent QRCodeJs instances.

QRCodeJs.setStyle(styleNameOrOptions: string | RecursivePartial<StyleOptions>): void

useStyle()

Initiates a builder pattern pre-configured with a style.

QRCodeJs.useTemplate(styleNameOrOptions: string | RecursivePartial<StyleOptions>): QRCodeBuilder

Fluent Builder Pattern (useTemplate, useStyle, build)

QRCode.js offers a fluent builder pattern for a more readable and chainable way to configure and create QR codes, especially when combining templates, styles, and custom options.

Overview

Instead of passing all options to the constructor, you can start with a base template or style using QRCodeJs.useTemplate() or QRCodeJs.useStyle(). These methods return a QRCodeBuilder instance. You can then chain further .useTemplate(), .useStyle(), and finally .options() or .build() to finalize the configuration.

How useStyle and useTemplate Work Together (Builder Pattern)

You can chain useTemplate and useStyle calls. The options are merged progressively. If both a template and a style define the same option (e.g., dotsOptions.color), the option from the last applied template or style in the chain will take precedence.

Examples

1. Start with a Template, Add Options:

const qrFromTemplate = QRCodeJs.useTemplate('rounded') // Start with 'rounded' template
  .options({ // Merge specific options
    data: 'Data for rounded QR',
    margin: 10
  })
  .build(); // Build the final instance

qrFromTemplate.append(document.getElementById('qr-container-1'));

2. Start with a Style, Add Options:

const myStyle = {
  dotsOptions: { type: 'dots', color: '#FF6347' }, // Tomato dots
  backgroundOptions: { color: '#F0F8FF' } // AliceBlue background
};

const qrFromStyle = QRCodeJs.useStyle(myStyle) // Start with custom style
  .options({ // Merge specific options
    data: 'Data for styled QR',
    qrOptions: { errorCorrectionLevel: 'H' }
  })
  .build();

qrFromStyle.append(document.getElementById('qr-container-2'));

3. Chain Template and Style:

const qrCombined = QRCodeJs.useTemplate('dots') // Start with 'dots' template (black dots)
  .useStyle({ dotsOptions: { color: '#4682B4' } }) // Apply style, overriding dot color to SteelBlue
  .options({ data: 'Template + Style' })
  .build();

qrCombined.append(document.getElementById('qr-container-3'));

4. Build without final options:

// Assume 'data' is part of the template or style
const qrBuildDirectly = QRCodeJs.useTemplate({ 
    data: 'Data in template',
    dotsOptions: { type: 'square' }
  })
  .build(); // Build directly if all options are set

qrBuildDirectly.append(document.getElementById('qr-container-4'));

FAQ

General Questions

Can I use SVG output?

Yes, set type: 'svg' and use the .svg property.

Can I use QRCode.js for free without a license?

Yes, QRCode.js can be used for free without a license key. This allows you to create full-featured, styled QR codes with all the basic features including custom dot styles, colors, shapes, and image embedding. The only limitations are on advanced border features and scan validation.

Can I use border features in the free version?

Yes, you can use basic border features in the free version, but the library will automatically add “QR-Platform” branding text in the bottom border of your QR code. This branding cannot be removed or customized in the free version.

Does the QR-Platform branding affect the scannability of the QR code?

No, the QR-Platform branding only appears in the border area, which is outside the actual QR code area. It does not affect the scannability or functionality of the QR code itself. However, it does affect the visual appearance of your QR code.

Do you provide support for licensed users?

Yes, we do provide support for licensed users. If you have any questions or need assistance, please contact us at support@qr-platform.com.

What is QR-Platform?

QR-Platform is a powerful and comprehensive solution for managing and deploying QR codes, it enables businesses to effortlessly Create, Store, Manage, and Deploy Beautiful, Stylish, and Fully Customizable QR codes. QRCode.js library license is included free of charge with all paid QR-Platform plans, offering seamless integration and powerful customization capabilities for businesses of any size.

Can I modify or remove the QR-Platform branding in the free version?

No, the QR-Platform branding in the bottom border is automatically added when using border features in the free version and cannot be modified or removed. This is a limitation of the free version. Purchasing a license allows you to remove the branding and fully customize your border text.

Can I make the QR-Platform branding less noticeable without a license?

While you cannot remove the branding, you can somewhat reduce its visual impact by:

However, the branding will still be present, and these approaches might reduce the aesthetic appeal of your QR code.

What happens if I try to use premium border features without a license?

The library will not throw errors but will instead gracefully fall back to the free version behavior. It will ignore premium-only properties like inner, borderOuter, and borderInner, and will still display the QR-Platform branding in the bottom border.

Do I need to activate the license on every page load?

What happens if the license expires?

getLicenseDetails() returns null; you’ll need to renew with license() or token().

TypeScript Types

Main Options Interface

interface Options {
  // Core Data & QR Algorithm
  data: string; // Required: Content to encode
  qrOptions: {
    typeNumber: number; // Default 0 (auto)
    mode?: Mode; // Default: auto-detected
    errorCorrectionLevel: ErrorCorrectionLevel; // Default 'Q'
  };

  // Overall Shape & Layout
  shape: ShapeType; // Default 'square'
  margin?: number; // Default 0: Space around QR code (pixels)
  isResponsive?: boolean; // Default false: Allow SVG resizing
  scale?: number; // Default 1: Scale QR code within container/border (0-1.5)
  offset?: number; // Default 0: Vertical offset relative to center
  verticalOffset?: number; // Default 0: Absolute vertical offset
  horizontalOffset?: number; // Default 0: Absolute horizontal offset

  // Dot Styling
  dotsOptions: {
    type: DotType; // Default 'square'
    color: string; // Default '#000000'
    gradient?: Gradient;
    size: number; // Default 10 (pixels)
  };

  // Corner Square Styling (Overrides dotsOptions)
  cornersSquareOptions?: {
    type?: CornerSquareType; // Default: inherits dotsOptions.type or 'dot'
    color?: string; // Default: inherits dotsOptions.color or '#000000'
    gradient?: Gradient;
  };

  // Corner Dot Styling (Overrides cornersSquareOptions)
  cornersDotOptions?: {
    type?: CornerDotType; // Default: inherits cornersSquareOptions.type or 'dot'
    color?: string; // Default: inherits cornersSquareOptions.color or '#000000'
    gradient?: Gradient;
  };

  // Background Styling
  backgroundOptions?: {
    color?: string; // Default '#FFFFFF'
    gradient?: Gradient;
    round?: number | string; // Default 0: Corner rounding (0-1 or %)
  } | false; // Set to false to disable background

  // Image Embedding
  image?: string | Buffer | Blob; // Image source (URL, Buffer, Blob)
  imageOptions: {
    mode?: ImageMode; // Default 'center'
    imageSize: number; // Default 0.4: Relative image size (0-1)
    margin: number; // Default 0: Margin around image (dot units)
    crossOrigin?: string; // Default undefined: CORS setting
    fill?: {
      color: string; // Default 'rgba(255,255,255,1)'
      gradient?: Gradient;
    };
  };

  // Borders (Basic features in free version, advanced in premium)
  borderOptions?: {
    hasBorder: boolean; // Master switch to enable/disable borders
    thickness: number; // Thickness of the main border in pixels
    color: string; // Color of the main border
    radius: string; // Corner rounding of the border (e.g., '10%', '20px')
    noBorderThickness: number; // Thickness for border sides with disabled decorations
    background?: string; // Background color for the border area
    inner?: {
      radius: string;
      scale: number;
      horizontalOffset: number;
      verticalOffset: number;
    };
    borderOuter?: {
      color: string;
      thickness: number;
    };
    borderInner?: {
      color: string;
      thickness: number;
    };
    decorations?: {
      top?: DecorationOptions;
      right?: DecorationOptions;
      bottom?: DecorationOptions;
      left?: DecorationOptions;
    };
  };
}

// Supporting Interfaces
interface Gradient {
  type: 'linear' | 'radial';
  rotation?: number;
  colorStops: Array<{ offset: number; color: string }>;
}

interface DecorationOptions {
  disabled: boolean;
  enableText: boolean;
  offset: number;
  curveAdjustment: number;
  curveDisabled: boolean;
  curveRadius: string;
  type: 'text' | 'image';
  value: string;
  style?: {
    fontFace: string;
    fontSize: number;
    fontColor: string;
    letterSpacing: number;
    fontWeight: 'normal' | 'bold';
  };
}

// Enums
enum ShapeType {
  square = 'square',
  circle = 'circle'
}

enum Mode {
  numeric = 'numeric',
  alphanumeric = 'alphanumeric',
  byte = 'byte',
  kanji = 'kanji',
  unicode = 'unicode'
}

enum ErrorCorrectionLevel {
  L = 'L', // 7% error recovery
  M = 'M', // 15% error recovery
  Q = 'Q', // 25% error recovery
  H = 'H'  // 30% error recovery
}

enum DotType {
  dot = 'dot',
  square = 'square',
  rounded = 'rounded',
  extraRounded = 'extra-rounded',
  classy = 'classy',
  classyRounded = 'classy-rounded',
  verticalLine = 'vertical-line',
  horizontalLine = 'horizontal-line',
  randomDot = 'random-dot',
  smallSquare = 'small-square',
  tinySquare = 'tiny-square',
  star = 'star',
  plus = 'plus',
  diamond = 'diamond'
}

enum CornerSquareType {
  dot = 'dot',
  square = 'square',
  rounded = 'rounded',
  classy = 'classy',
  outpoint = 'outpoint',
  inpoint = 'inpoint'
}

enum CornerDotType {
  dot = 'dot',
  square = 'square',
  heart = 'heart',
  rounded = 'rounded',
  classy = 'classy',
  outpoint = 'outpoint',
  inpoint = 'inpoint'
}

enum ImageMode {
  center = 'center',
  overlay = 'overlay',
  background = 'background'
}

See Also