Skip to content

Builder and matrix

qrcode() from @qrcodesdk/core creates an immutable builder. Each options method returns a new builder and leaves the original unchanged.

For how modes, versions, error correction, and masks shape the symbol, see How QR codes work.

The builder accepts a string or a non-negative safe integer. Use a string for values with leading zeroes or values beyond JavaScript’s safe-integer range.

import {QRCodeBuilder, qrcode} from '@qrcodesdk/core';
qrcode('https://qrcodesdk.dev');
qrcode(1234567890);
qrcode().payload('payload supplied later');
QRCodeBuilder.create('https://qrcodesdk.dev', {errorCorrectionLevel: 'H'});
  • QRCodeBuilder.create(payload, options?) equals qrcode(payload) plus matrix options in one call. Without arguments, it equals qrcode().
  • Typed payload helpers turn email, phone, SMS, geographic, and Wi-Fi values into a payload string.

QRCodeSDK generates QR Code Model 2 symbols and, with microQR(), Micro QR symbols. It supports numeric, alphanumeric, UTF-8 octet, and opt-in Kanji payloads, with optional mixed-mode segmentation. It targets payloads in a single symbol and does not support:

  • structured append, which splits one payload across several symbols;
  • rMQR (rectangular Micro QR) symbols;
  • GS1 data;
  • raw binary segments. Octet segments always contain the UTF-8 bytes of a string.

If your scanner or industry standard requires one of these, use a library that implements it.

Mode Accepted payload Use it for
numeric Digits only Numeric identifiers and digit-only payloads
alphanumeric QR alphanumeric character set Uppercase text such as HELLO WORLD
octet UTF-8 bytes URLs, JSON, emoji, lowercase, and general text
kanji Double-byte Shift JIS characters Japanese text, with the Kanji table
auto or omitted Any supported payload Single-mode detection; optional mixed-mode optimization
  • auto encodes the whole payload as one segment. It picks numeric for digits, alphanumeric for the QR alphanumeric character set, Kanji for Kanji mode characters when the Kanji table is supplied, and octet for everything else.
  • A concrete mode forces the whole payload into that mode.

Import automaticSegmenter to split the payload into the shortest combination of numeric, alphanumeric, and octet segments, plus Kanji segments when the Kanji table is supplied:

import {qrcode} from '@qrcodesdk/core';
import {automaticSegmenter} from '@qrcodesdk/core/segmenter';
const payload = 'ABCD12345678901234567890abcd';
qrcode(payload).mode('auto').matrix(); // Single segment, version 3.
qrcode(payload).mode('auto').segmenter(automaticSegmenter).matrix(); // Mixed segments, version 2.
qrcode(payload).options({segmenter: automaticSegmenter}).matrix(); // Auto is the default.
  • The optimizer is opt-in. Applications that don’t import it skip its bundle size and processing cost.
  • Single-mode detection can produce a larger symbol. A payload that fits a pinned version with optimization can exceed it without.
  • Explicit modes, such as numeric or kanji, ignore the segmenter.
  • .mode('auto') or .mode() returns to auto selection.
  • .segmenter() or .options({segmenter: undefined}) clears the segmenter.

Framework components take the same callback as options.matrix.segmenter. The React, Vue, Svelte, and Angular packages re-export automaticSegmenter, so import it from the framework package.

Kanji mode packs each double-byte Shift JIS character into 13 bits. UTF-8 needs 24 bits for most Japanese characters, so Japanese text fits a smaller symbol. Kanji mode needs the Shift JIS table from @qrcodesdk/core/kanji, which adds about 13 kB gzipped. Applications that don’t import it don’t load the table.

import {qrcode} from '@qrcodesdk/core';
import {kanji} from '@qrcodesdk/core/kanji';
import {automaticSegmenter} from '@qrcodesdk/core/segmenter';
qrcode('漢字テスト').mode('kanji').kanji(kanji).matrix(); // Forced Kanji mode.
qrcode('漢字テスト').kanji(kanji).matrix(); // Auto mode picks Kanji for the whole payload.
qrcode('東京タワー 333m').segmenter(automaticSegmenter).kanji(kanji).matrix(); // Kanji and octet.
  • The table covers every character that Kanji mode can encode, as the WHATWG Shift_JIS decoder maps them: kanji, hiragana, katakana, full-width Latin letters and digits, Greek, Cyrillic, box drawing, and symbols. ASCII and half-width katakana are single-byte Shift JIS and use other modes.
  • Kanji mode accepts only characters that decode back unchanged. For example, it rejects − (U+2212), which some Shift JIS encoders replace with - (U+FF0D).
  • Without the table, mode: 'kanji' and Kanji segments throw QRCodeError with code INVALID_OPTIONS. Auto mode and automaticSegmenter then encode Japanese text as UTF-8 octets.
  • Kanji segments never get an ECI header. Scanners decode them as Shift JIS.
  • .kanji() or .options({kanji: undefined}) removes the table.

Framework components take the table as options.matrix.kanji. The React, Vue, Svelte, and Angular packages re-export kanji.

A custom QRCodeSegmenter receives the original payload and {version, eci, kanji}. kanji is present only when the matrix options contain the Kanji table. It returns a non-empty array of QRCodeSegment values. The segments must follow these rules:

  • Each segment has a concrete mode and an unencoded string payload.
  • The segment texts concatenate to the original payload.
  • No segment is empty, unless a single segment encodes an empty payload.
  • No boundary splits a surrogate pair.

Core validates each segment, UTF-8 encodes octet segments, converts Kanji segments with the Kanji table, and packs numeric and alphanumeric segments in their QR modes. Kanji segments require the kanji matrix option.

The callback should be deterministic. With automatic version selection, it runs once per searched character-count group, starting at versions 1, 10, and 27. With a pinned version, it runs once.

QRCodeMatrixOptions contains only options that affect the encoded matrix:

Option Type Default Constraint
mode 'auto' | 'numeric' | 'alphanumeric' | 'octet' | 'kanji' 'auto' Forced mode must accept the entire payload
segmenter QRCodeSegmenter omitted Used only in auto mode
kanji QRCodeKanji omitted Required by Kanji mode and Kanji segments
eci boolean false Only affects symbols containing octet segments
errorCorrectionLevel 'L' | 'M' | 'Q' | 'H' 'M' Higher redundancy reduces payload capacity
version integer 1–40 automatic Pinned version must fit the encoded payload
mask integer 0–7 automatic Pinned mask replaces penalty-based selection
symbol QRCodeSymbol, such as microQR() omitted Generates another symbol type; see below

Set options one by one or together:

import {qrcode} from '@qrcodesdk/core';
const builder = qrcode('Grüße ✅').mode('octet').eci(true).errorCorrection('H').version(4).mask(2);
const equivalent = qrcode('Grüße ✅').options({
mode: 'octet',
eci: true,
errorCorrectionLevel: 'H',
version: 4,
mask: 2,
});

Octet payload bytes are always UTF-8.

  • eci: true adds ECI assignment 26 once, right before the first octet segment. Scanners get an explicit UTF-8 declaration. It costs 12 bits.
  • eci: false leaves scanners to guess the encoding of non-ASCII text.
  • Symbols without octet segments get no ECI header, so the setting changes nothing for them.

The levels L, M, Q, and H add increasing amounts of redundant data. The default is M.

Higher levels survive more damaged or covered modules. They also reduce capacity and may need a larger version. Use H with a center image, as Add a center image explains. How QR codes work lists how much each level can restore.

Leave both automatic in most applications. Automatic selection returns the same result for the same payload and options within one QRCodeSDK release. Pin them only when you must:

  • Pin version when the symbol needs fixed dimensions.
  • Pin mask when a compatibility target or an external fixture needs a specific mask pattern.

If the payload does not fit a pinned version, generation throws QRCodeError with code PAYLOAD_TOO_LARGE and details.version. See the errors reference. Removing the pin helps only if a larger version fits. If automatic selection also fails, shorten or change the payload.

symbol replaces the standard QR code with another symbol type. microQR() from @qrcodesdk/core/micro selects a Micro QR code, and rMQR() from @qrcodesdk/core/rmqr selects a rectangular Micro QR (rMQR) code. The symbol owns its version and mask, so version, mask, eci, and segmenter are typed never next to it and throw INVALID_OPTIONS at runtime:

import {qrcode} from '@qrcodesdk/core';
import {microQR} from '@qrcodesdk/core/micro';
import {rMQR} from '@qrcodesdk/core/rmqr';
qrcode('12345')
.options({symbol: microQR({version: 'M2'})})
.matrix().width; // 13
const {width, height} = qrcode('12345')
.options({symbol: rMQR({version: 'R7'})})
.matrix(); // 43 × 7

QRCodeMatrixOptions is the union of QRCodeStandardMatrixOptions and QRCodeSymbolMatrixOptions. Use QRCodeStandardMatrixOptions when you derive types, such as with Omit, from options that only describe standard QR codes.

Method Returns Effect
.payload(value) a builder with a payload Sets or replaces the payload
.options(options?) a configured builder Merges all supplied matrix options
.mode(mode?) a configured builder Forces or clears the encoding mode
.segmenter(segmenter?) a configured builder Sets or clears optional mixed-mode segmentation
.kanji(kanji?) a configured builder Sets or clears the Kanji table
.eci(enabled?) a configured builder Enables or clears the UTF-8 ECI declaration
.errorCorrection(level?) a configured builder Sets or clears the error correction level
.version(version?) a configured builder Pins or clears the version
.mask(mask?) a configured builder Pins or clears the mask
.matrix() QRCodeMatrix Generates the matrix; TypeScript requires a payload
.renderer(renderer) a builder with a renderer Stores a renderer for a later call
.render(renderer?) renderer output Generates the matrix and invokes a supplied or stored renderer
Static method Returns Effect
QRCodeBuilder.create() a builder Creates a builder without a payload, like qrcode()
QRCodeBuilder.create(payload, options?) a builder Creates a builder with a payload and matrix options
  • qrcode() and the option methods never throw.
  • TypeScript checks matrix option names, types, and literal values.
  • Payload format and capacity are checked when the matrix is first requested. See Errors.

TypeScript also blocks .matrix() and .render() before a payload is set. It blocks .render() when no renderer is stored or passed.

The payload check exists only in the types. From JavaScript, .matrix() without a payload does not throw. It encodes the text undefined. See Payload types are not validated at runtime.

Use QRCodeBuilder without type arguments to type a builder that has a payload. This general type accepts builders with or without a stored renderer. TypeScript therefore allows .render() without arguments, which throws RENDERER_MISSING at runtime if no renderer was stored. Pass a renderer explicitly through this type:

import {QRCodeBuilder, QRCodeSVGRenderer, qrcode} from '@qrcodesdk/core';
function toSVG(builder: QRCodeBuilder): string {
return builder.render(QRCodeSVGRenderer());
}
toSVG(qrcode('https://qrcodesdk.dev'));

.matrix() returns a read-only QRCodeMatrix with flat, row-major module data:

Property Value
width Number of modules per row
height Number of rows; equal to width except for rMQR codes
modules Frozen array: 1 for dark, 0 for light modules
roles Frozen array with the role of every module, such as data, finder, or timing

The module at column x and row y is at index y * width + x in both arrays. See Module roles for every role.

import {type QRCodeMatrix, qrcode} from '@qrcodesdk/core';
const matrix: QRCodeMatrix = qrcode('custom output').matrix();
const isDark = (x: number, y: number) => matrix.modules[y * matrix.width + x] === 1;

A QRCodeRenderer<TOutput> receives that matrix and returns TOutput:

import {type QRCodeRenderer, qrcode} from '@qrcodesdk/core';
const jsonRenderer: QRCodeRenderer<string> = ({width, height, modules}) =>
JSON.stringify({width, height, modules: Array.from(modules)});
const direct = qrcode('renderer output').render(jsonRenderer);
const stored = qrcode('renderer output').renderer(jsonRenderer).render();

Built-in renderers use the same signature. A custom renderer defines its own geometry, styling, validation, and return type. See Custom renderers.

Support QRCodeSDK

If you find QRCodeSDK useful, please consider sponsoring the project!