---
title: "EAN-13 and Code 128 in plain TypeScript, with a test that scans them back"
description: "Businesses on Bookatu sell things next to their bookings. A studio sells mats, a salon sells the shampoo it uses. To print shelf labels we wrote EAN-13, UPC-A and Code 128 encoders by hand, with no dependency. Here is how each symbol is built and drawn as SVG, and the test that proves a printed label scans back to the right code."
url: "https://bookatu.com/engineering/ean-13-and-code-128-in-plain-typescript-with-a-test-that-scans-them-back"
language: "en"
section: "Engineering"
category: "Engineering"
author: "The Bookatu engineering team"
published: "2026-11-11"
updated: "2026-11-11"
tags: ["typescript", "barcodes", "svg", "testing", "engineering"]
---

# EAN-13 and Code 128 in plain TypeScript, with a test that scans them back

Businesses on Bookatu sell things next to their bookings. A studio sells mats, a salon sells the shampoo it uses. To print shelf labels we wrote EAN-13, UPC-A and Code 128 encoders by hand, with no dependency. Here is how each symbol is built and drawn as SVG, and the test that proves a printed label scans back to the right code.

> **The short version**
>
> - An EAN-13 is 95 modules: three guards and twelve digits of seven modules each. The first digit has no bars of its own. It is carried by the pattern of the left half.
> - A UPC-A is an EAN-13 that starts with 0, with the same bars. Scanners report it either way, so the point of sale looks a code up under both forms.
> - Code 128 switches between set B for text and set C for pairs of digits, which halves the width of a long number.
> - The SVG is measured in modules, quiet zones included, so one drawing prints on a small roll label or a full sheet.
> - A test paints the SVG's own bars onto a bitmap and decodes it with ZXing, asking for the same formats the point of sale's camera scanner asks for.

Bookatu has a point of sale and stock for the things a business sells next to its services. A yoga studio sells mats and blocks. A surf school sells wax. Most of these arrive with a barcode on the box. Some do not, and some shelves need a label anyway. So the Products page has Print labels, and a product with no code can get one with Make a barcode.

We could have added a barcode library. We wrote the encoders instead. The two files are just over 200 lines together, they run the same in the browser and in Node, and writing them meant we know exactly what we print.

## EAN-13: twelve digits you see in the bars, one you do not

An EAN-13 is drawn as 95 modules. A module is the narrowest bar or space. The symbol opens with a guard, 101. Then come six digits of seven modules each, a centre guard, 01010, six more digits, and a closing 101.

That is only twelve digits of bars. The thirteenth, the first one printed, has no bars of its own. It is carried by which of two patterns, L or G, each of the six left digits uses. The right half always uses R. R is L with every module flipped, and G is R read backwards.

```ts
const L = ["0001101", "0011001", "0010011", "0111101", "0100011",
           "0110001", "0101111", "0111011", "0110111", "0001011"];
const G = ["0100111", "0110011", "0011011", "0100001", "0011101",
           "0111001", "0000101", "0010001", "0001001", "0010111"];
const R = ["1110010", "1100110", "1101100", "1000010", "1011100",
           "1001110", "1010000", "1000100", "1001000", "1110100"];

// Which set each of the six left digits uses, by the first digit.
const PARITY = ["LLLLLL", "LLGLGG", "LLGGLG", "LLGGGL", "LGLLGG",
                "LGGLLG", "LGGGLL", "LGLGLG", "LGLGGL", "LGGLGL"];

export function ean13Modules(code: string): string | null {
  if (!isValidEan13(code)) return null;
  const parity = PARITY[Number(code[0])];
  let out = "101";
  for (let i = 0; i < 6; i++) {
    const d = Number(code[1 + i]);
    out += parity[i] === "L" ? L[d] : G[d];
  }
  out += "01010";
  for (let i = 0; i < 6; i++) out += R[Number(code[7 + i])];
  return out + "101";
}
```

The last digit is a check digit. Weights of 3 and 1 alternate from the right, starting with 3, and the check digit brings the sum up to the next multiple of ten:

```ts
export function gs1CheckDigit(body: string): number {
  let sum = 0;
  for (let i = 0; i < body.length; i++) {
    const fromRight = body.length - 1 - i;
    sum += Number(body[i]) * (fromRight % 2 === 0 ? 3 : 1);
  }
  return (10 - (sum % 10)) % 10;
}
```

Because it counts from the right, the same function works for the twelve digit body of an EAN-13 and the eleven digit body of a UPC-A.

## UPC-A is the same symbol

A twelve digit UPC-A is drawn exactly as the EAN-13 of a 0 followed by it. With a first digit of 0 the parity pattern is all L, which is how UPC-A was laid out before EAN extended it. So our UPC-A encoder is one line: ean13Modules("0" + code).

This has a practical side. The bars are identical, so a scanner has to choose what to report. Some decoders report an EAN-13 that starts with 0 as its twelve digit UPC-A. Many USB scanners send a UPC-A as thirteen digits. Neither is wrong. So the point of sale looks a scanned code up under both forms, the exact one first:

```ts
export function scanMatchKeys(scanned: string): string[] {
  const code = scanned.trim();
  if (!code) return [];
  if (isValidUpcA(code)) return [code, "0" + code];
  if (code.startsWith("0") && isValidEan13(code)) return [code, code.slice(1)];
  return [code];
}
```

## Code 128 for everything else

Not every product code is a retail number. A supplier may use its own code, such as MAT-PRO-6MM. Anything that is not a valid EAN-13 or UPC-A prints as Code 128, with the text exactly as stored. That includes thirteen digits with a wrong check digit, which we print as the text it is rather than guess at.

Code 128 has three code sets. Set B carries printable ASCII, one character per symbol. Set C carries two digits per symbol, so a long number takes half the width. Set A carries control characters, which a code typed or scanned never contains, so we left it out and refuse any code that would need it.

Choosing between B and C follows the usual rules from the standard, ISO/IEC 15417, annex E. Start in C when the text opens with four or more digits, or is exactly two digits. Otherwise start in B.

From B, switch to C for a run of six or more digits, or four or more that end the text. An odd run spends its first digit in B before switching. From C, go back to B as soon as fewer than two digits are left in the run.

Every symbol is eleven modules wide, and the stop is thirteen. The check symbol is the start value plus each symbol's value times its position, modulo 103:

```ts
let sum = values[0]; // the start symbol
for (let k = 1; k < values.length; k++) sum += values[k] * k;
values.push(sum % 103, STOP);
```

Each value maps to six widths, bar first, from the Code 128 table. We did not trust our own copy of a 107 row table. A unit test holds it against the table inside ZXing, the open source decoder our point of sale's camera scanner falls back to. The EAN sets are checked against ZXing the same way, and against full module strings for two well-known example codes, worked out by hand from the GS1 tables.

## Drawing it

The encoders return a string of 1s and 0s. The SVG layer turns each run of 1s into a rectangle, and adds what a scanner and a person need around the bars.

- Quiet zones. A scanner finds the start of a symbol by the blank space before it. EAN-13 gets 11 modules on the left and 7 on the right. UPC-A gets 11 on each side, room for its outside digits. Code 128 gets 10.
- Guard bars. On EAN-13 and UPC-A the guards reach a few modules lower than the rest, framing the digits.
- Digits. The EAN-13's first digit sits in the left quiet zone, before any bar. UPC-A prints its first and last digits outside the bars, a little smaller.
- Units. Everything is in modules in the viewBox. The label sheet decides how many millimetres a module is, so the same drawing fills a 25 mm roll label or a cell on an A4 sheet.

Two small details matter more than they look. The bars are drawn with shape-rendering="crispEdges", so a printer driver does not blur one bar into the next. And the text under the bars is escaped, because a stored code is user input and an SVG is markup. A test feeds it a code full of angle brackets and quotes and checks no tag gets through.

## The test that scans it back

Pattern tests prove the encoder matches our reading of the spec. They do not prove a label scans. For that we wanted the whole path: the SVG markup we actually ship, read by a real decoder.

So the test ignores the encoder's internals. It parses the rectangles out of the SVG string, paints them onto a white bitmap at three pixels per module, and hands that to ZXing. It asks ZXing for exactly the formats the point of sale's camera scanner asks for, read from one shared list, so the test and the point of sale cannot drift apart.

```ts
const PX = 3;
const ROWS = 40;

function decodeSvg(svg: string): { text: string; format: string } {
  const widthModules = Number(/viewBox="0 0 ([\d.]+)/.exec(svg)![1]);
  const group = /<g fill="#000" shape-rendering="crispEdges">(.*?)<\/g>/.exec(svg)![1];
  const bars = [...group.matchAll(/<rect x="([\d.]+)" y="0" width="([\d.]+)"/g)]
    .map((m) => ({ x: Number(m[1]), w: Number(m[2]) }));

  const width = Math.round(widthModules * PX);
  const row = new Uint8ClampedArray(width).fill(255);
  for (const b of bars) {
    for (let px = Math.round(b.x * PX); px < Math.round((b.x + b.w) * PX); px++) row[px] = 0;
  }
  const lum = new Uint8ClampedArray(width * ROWS);
  for (let y = 0; y < ROWS; y++) lum.set(row, y * width);

  const reader = new MultiFormatReader();
  reader.setHints(new Map([[DecodeHintType.POSSIBLE_FORMATS, SCANNER_FORMATS]]));
  const bitmap = new BinaryBitmap(new HybridBinarizer(new RGBLuminanceSource(lum, width, ROWS)));
  const result = reader.decode(bitmap);
  return { text: result.getText(), format: BarcodeFormat[result.getBarcodeFormat()] };
}
```

Every case must come back as the stored code, character for character, in the expected format. The point of sale finds a product by an exact match on its code, so close is not good enough.

```ts
expect(scan("5901234123457")).toEqual({ text: "5901234123457", format: "EAN_13" });
expect(scan("036000291452")).toEqual({ text: "036000291452", format: "UPC_A" });

for (const code of ["MAT-PRO-6MM", "123456", "12345", "AB12345678", "AB1234567", "X123456Y", "sku 42/b", "A"]) {
  expect(scan(code)).toEqual({ text: code, format: "CODE_128" });
}

// Short bars, as on a small roll label.
expect(scan("2000000000015", { barHeight: 12 }).text).toBe("2000000000015");
```

The Code 128 cases are picked to hit each switching rule. There are digits only, in an even and an odd count. There are runs that end the text after letters, again even and odd. A six digit run in the middle switches to C and back, a short one stays in B, and a single letter is the smallest case.

## Codes for products that have none

Make a barcode gives a product with no code an EAN-13 of the business's own. GS1 keeps the prefixes 20 to 29 for restricted circulation: numbers a shop uses inside its own walls, which no manufacturer is ever given. So one of ours can never collide with a real product's code.

Ours all start with 20, then a ten digit running number, then the check digit: 2000000000015, 2000000000022 and on. We picked 20 because some point of sale systems read the other prefixes in the range as a code with a weight or a price inside it, and 20 is the one most often left plain.

```ts
export function inStoreCode(n: number): string {
  const body = "20" + String(n).padStart(10, "0");
  return body + gs1CheckDigit(body);
}
```

The next number is one past the highest the business already has. Two people pressing the button at the same moment would work out the same number, so a unique index on the business and the barcode refuses the second insert.

## What we take from it

- Barcode symbologies are small and well specified. Writing one is a modest job, and it takes a dependency off every page that prints.
- Hold your tables against an independent copy, such as the one inside a decoder.
- Test the thing you ship. Our scan test reads the SVG string, not the encoder's output.
- Share the scanner's format list with the test, so the two cannot disagree.
- When two encodings are one symbol, look a scan up under both.
