Skip to content
jshacks.dev
Browser

Encoding APIs: TextEncoder and TextDecoder

How TextEncoder and TextDecoder convert strings and UTF-8 bytes in JavaScript: encodeInto, other encodings, fatal mode, BOMs and chunked decoding.

8 min read
Summarize in AI
Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, JavaScript, Swagger and Postman logos.

JavaScript strings are sequences of UTF-16 code units, and every network, file and binary API deals in bytes. Somewhere between them there has to be a conversion, and getting it wrong is the source of a long list of bugs: mojibake like é in place of é, emoji split in half, byte counts that disagree with string.length, and uploads that exceed a limit because a counted character took four bytes. TextEncoder and TextDecoder are the standard, built-in tools for that conversion. They convert between strings and bytes, mostly in UTF-8, and they handle the details, such as surrogate pairs and byte order marks, that hand-written code gets wrong. This post explains how TextEncoder and TextDecoder work in JavaScript: encoding a string to UTF-8, decoding bytes, how encodeInto() avoids an allocation, which other encodings TextDecoder supports, the fatal and ignoreBOM options, decoding in chunks with the stream option, the stream variants for use in pipelines, how string length differs from byte length, and the common mistakes. They are defined in the WHATWG Encoding Standard, documented on MDN, and available in all browsers, in workers and in Node.js, Deno and Bun as globals.

Encoding a string

new TextEncoder().encode(string) returns a Uint8Array of the UTF-8 bytes. TextEncoder always uses UTF-8, and takes no arguments.

encode.jsJavaScript
const encoder = new TextEncoder();

const bytes = encoder.encode("héllo");

console.log(bytes);
console.log(bytes.length, "héllo".length);
console.log(encoder.encoding);
Text
Uint8Array(6) [ 104, 195, 169, 108, 108, 111 ]
6 5
utf-8

The accented é takes two bytes, 195 and 169, so the string has five characters and six bytes. A character in UTF-8 takes between one and four bytes: ASCII takes one, most European accented letters take two, most other scripts and symbols take three and emoji and rare characters take four. That is why string.length is the wrong number for a byte limit.

lengths.jsJavaScript
const samples = ["a", "é", "€", "😀"];

for (const s of samples) {
  console.log(s, s.length, new TextEncoder().encode(s).length);
}
Text
a 1 1
é 1 2
€ 1 3
😀 2 4

The emoji has a string length of 2, since it is stored as a surrogate pair of two UTF-16 code units, and four UTF-8 bytes. To count bytes, encode and read the length, and to count what a user perceives as characters, use Intl.Segmenter, which understands grapheme clusters such as flags and emoji with skin tones.

Decoding bytes

new TextDecoder().decode(bytes) converts bytes back to a string. The default encoding is UTF-8. The input can be an ArrayBuffer or any typed array or DataView.

decode.jsJavaScript
const decoder = new TextDecoder();

const text = decoder.decode(new Uint8Array([104, 195, 169, 108, 108, 111]));

console.log(text);
console.log(decoder.encoding, decoder.fatal, decoder.ignoreBOM);
Text
héllo
utf-8 false false

The properties report the settings: encoding is the canonical label, fatal says whether invalid bytes throw, and ignoreBOM says whether a leading byte order mark is kept in the output.

Invalid bytes: replacement or error

Not every byte sequence is valid UTF-8. By default the decoder is forgiving: it replaces each invalid sequence with the replacement character U+FFFD, which looks like �, and carries on. That is good for display and bad for correctness, since corruption is silent. With fatal: true, the decoder throws a TypeError instead, which is what you want when you must reject bad data.

fatal.jsJavaScript
const bad = new Uint8Array([104, 105, 0xff, 33]);

console.log(new TextDecoder().decode(bad));

try {
  new TextDecoder("utf-8", { fatal: true }).decode(bad);
} catch (error) {
  console.log(error.name);
}
Text
hi�!
TypeError

Use fatal: true for parsing protocols and files where invalid text means the data is damaged, and the default for showing arbitrary text that you cannot fix. A well-known source of invalid bytes is cutting a UTF-8 buffer at an arbitrary byte position, such as slicing a download in the middle of a character, which is the reason for the stream option below.

Byte order marks

A byte order mark, EF BB BF in UTF-8, is an optional marker at the start of a file, which Windows tools often add. TextDecoder removes it by default, so the text starts at the first real character. Set ignoreBOM: true to keep it as the character U+FEFF in the output, which matters when you must reproduce the bytes exactly.

bom.jsJavaScript
const withBom = new Uint8Array([0xef, 0xbb, 0xbf, 104, 105]);

console.log(JSON.stringify(new TextDecoder().decode(withBom)));
console.log(JSON.stringify(new TextDecoder("utf-8", { ignoreBOM: true }).decode(withBom)));
Text
"hi"
"hi"

The option name is confusing: ignoreBOM: true means "do not ignore it, keep it", because the flag describes whether the decoder's BOM handling is ignored. When parsing JSON or CSV from a file, leaving the default is what you want, since a leading  makes JSON.parse() fail.

Other encodings

TextEncoder is UTF-8 only, by design, but TextDecoder accepts a label for many legacy encodings: "utf-16le", "utf-16be", "iso-8859-1" (which the standard maps to windows-1252), "windows-1252", "shift_jis", "euc-kr", "gbk", "big5" and more. That is what you need to read old files and some HTTP responses with a non-UTF-8 charset.

legacy.jsJavaScript
const latin = new Uint8Array([99, 97, 102, 233]);

console.log(new TextDecoder("windows-1252").decode(latin));
console.log(new TextDecoder("utf-8").decode(latin));

const utf16 = new Uint8Array([104, 0, 105, 0]);
console.log(new TextDecoder("utf-16le").decode(utf16));
Text
café
caf�
hi

The first call prints café. The second shows the replacement character, because byte 233 is not valid UTF-8 on its own. The third decodes the two UTF-16 little-endian code units to hi.

An unknown label throws a RangeError, and the list of supported labels is in the Encoding Standard. Encoding to anything other than UTF-8 is not supported by the API, since the standard intentionally discourages creating new data in legacy encodings. For utf-16, you can write the code units yourself with a Uint16Array built from charCodeAt(), though be careful about byte order.

encodeInto: no allocation

encode() allocates a new array each time. For hot paths, such as encoding many strings into one buffer, encodeInto(string, destination) writes into an existing Uint8Array and returns how much it read and wrote.

into.jsJavaScript
const buffer = new Uint8Array(16);
const encoder = new TextEncoder();

const { read, written } = encoder.encodeInto("héllo wörld, long text", buffer);

console.log(read, written);
console.log(new TextDecoder().decode(buffer.subarray(0, written)));
Text
14 16
héllo wörld, l

The read value counts UTF-16 code units taken from the string, and written counts bytes put into the buffer. The method never writes half a character: when the next character would not fit, it stops, so the buffer always holds valid UTF-8, and read tells you where to continue. The output here has 16 bytes for 14 characters because é and ö take two each, and the string was cut at the buffer's end.

Decoding in chunks

When bytes arrive in pieces, as from a network stream, a chunk can end in the middle of a multi-byte character. Decoding each chunk separately corrupts those characters. The stream: true option tells the decoder to keep the incomplete bytes for the next call.

chunks.jsJavaScript
const bytes = new TextEncoder().encode("héllo");
const first = bytes.slice(0, 2);
const second = bytes.slice(2);

const wrong = new TextDecoder();
console.log(wrong.decode(first) + wrong.decode(second));

const right = new TextDecoder();
console.log(right.decode(first, { stream: true }) + right.decode(second));
Text
h��llo
héllo

The first slice ends after the first byte of the two-byte é, so decoding it alone produces a replacement character, and the remaining byte produces another. With stream: true the decoder holds the lone byte and combines it with the next chunk. The last call omits the option, which flushes the decoder, and every stream must end with a call without stream: true, or with no arguments, to get any pending bytes.

Streams

For pipelines, TextEncoderStream and TextDecoderStream wrap the same logic as transform streams, which handle chunk boundaries for you. They fit between a fetch() body and your code, and in the file and compression examples.

stream.jsJavaScript
async function readLines(response) {
  const stream = response.body.pipeThrough(new TextDecoderStream());
  let carry = "";

  for await (const chunk of stream) {
    const lines = (carry + chunk).split("\n");
    carry = lines.pop();
    for (const line of lines) console.log(line);
  }
  if (carry) console.log(carry);
}

readLines(new Response("one\ntwo\nthree"));
Text
one
two
three

TextDecoderStream takes the same label and options as TextDecoder. TextEncoderStream turns a stream of strings into a stream of UTF-8 bytes, for instance when you write text to a compressed or network stream.

Base64 and other byte conversions

Encoding text to bytes is a separate step from encoding bytes to base64 or hex. btoa() works on strings of Latin-1 characters only, so btoa("héllo €") throws for the euro sign. The correct path for arbitrary text is to encode to UTF-8 bytes first, and then turn the bytes into base64. Current engines provide Uint8Array.prototype.toBase64() and Uint8Array.fromBase64(), which are part of ES2026, while older environments need a manual step.

base64.jsJavaScript
function toBase64(text) {
  const bytes = new TextEncoder().encode(text);
  let binary = "";
  for (const byte of bytes) binary += String.fromCharCode(byte);
  return btoa(binary);
}

function fromBase64(base64) {
  const binary = atob(base64);
  const bytes = Uint8Array.from(binary, (c) => c.charCodeAt(0));
  return new TextDecoder().decode(bytes);
}

const packed = toBase64("héllo €");
console.log(packed);
console.log(fromBase64(packed));
Text
aMOpbGxvIOKCrA==
héllo €

The loop builds a binary string one byte at a time, since String.fromCharCode(...bytes) can overflow the argument limit for large arrays. Where the newer methods exist, bytes.toBase64() does the job in one call and is faster.

Common mistakes

Counting bytes with string.length. Cutting a byte array at an arbitrary point and decoding the pieces. Decoding with the default settings and never noticing the � in the output. Using btoa() directly on text outside Latin-1. Saving a file as UTF-16 when the reader expects UTF-8. Forgetting the BOM when exporting a CSV for Excel, which needs EF BB BF at the start to detect UTF-8, and which you can write with new Uint8Array([0xef, 0xbb, 0xbf]) before the encoded bytes. And reaching for escape and unescape or encodeURIComponent tricks, which were the workaround before these APIs existed.

Testing

Round trips and edge cases make good tests: the empty string, ASCII, multi-byte characters, a surrogate pair, a lone surrogate and invalid bytes. A lone surrogate, which is invalid in a well-formed string, is replaced by U+FFFD when encoded, so a round trip of an ill-formed string does not return the original, and String.prototype.isWellFormed() in current engines tells you in advance.

test.jsJavaScript
const cases = ["", "plain", "héllo €", "😀", "\ud83d"];

for (const value of cases) {
  const back = new TextDecoder().decode(new TextEncoder().encode(value));
  console.log(JSON.stringify(value), back === value, value.isWellFormed());
}
Text
"" true true
"plain" true true
"héllo €" true true
"😀" true true
"\ud83d" false false
Share

Keep reading

Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, Swagger, Postman and NGINX logos.
Browser

The DOM Tree: Nodes, Elements and Text

Understand the DOM tree: node types, the difference between nodes and elements, text and comment nodes, tree navigation properties and how whitespace shows up.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.