# JavaScript tokenizer libraries

JavaScript tokenizer libraries split text into the tokens a language model reads and map each token to an integer ID. A byte-pair encoder merges frequent character sequences into tokens from the vocabulary of one model family. These libraries let apps and AI agents count tokens before a model call.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [js-tiktoken](#js-tiktoken) | 49.4M | 1.1K | Aug 2025 | MIT |
| [Transformers.js](#transformers-js) | 19.1M | 16.4K | Oct 2026 | Apache-2.0 |
| [Tokenizers.js](#huggingface-tokenizers) | 15.4M | 62 | Sep 2026 | Apache-2.0 |
| [gpt-tokenizer](#gpt-tokenizer) | 10.6M | 862 | Nov 2026 | MIT |
| [tiktoken](#tiktoken) | 8.7M | 1.1K | Aug 2025 | MIT |
| [@anthropic-ai/tokenizer](#anthropic-ai-tokenizer) | 1.4M | 108 | Jul 2023 | Apache-2.0 |
| [GPT-3-Encoder](#gpt-encoder) | 640.1K | 722 | Jan 2023 | MIT |

Downloads: npm, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[js-tiktoken](#js-tiktoken) has the most monthly downloads in this comparison, at 49.4M.

## Capabilities

| Library | Chat message formatting | Hugging Face configs |
| --- | --- | --- |
| [js-tiktoken](#js-tiktoken) | No | No |
| [Transformers.js](#transformers-js) | Yes | Yes |
| [Tokenizers.js](#huggingface-tokenizers) | No | Yes |
| [gpt-tokenizer](#gpt-tokenizer) | Yes | No |
| [tiktoken](#tiktoken) | No | No |
| [@anthropic-ai/tokenizer](#anthropic-ai-tokenizer) | No | No |
| [GPT-3-Encoder](#gpt-encoder) | No | No |

## Libraries

### js-tiktoken

[GitHub](https://github.com/dqbd/tiktoken) · [npm](https://www.npmjs.com/package/js-tiktoken) · [Docs](https://raw.githubusercontent.com/dqbd/tiktoken/main/js/README.md)

Provides a JavaScript port of the tiktoken tokenizer for OpenAI models.

- Downloads / mo: 49.4M
- Stars: 1.1K
- Last release: 1.0.21
- License: MIT
- Capabilities: [From the js-tiktoken docs](https://raw.githubusercontent.com/dqbd/tiktoken/main/js/README.md)

```sh
npm install js-tiktoken@1.0.21
```

**langchain-ai/langchainjs** (18.4K stars)

[langchain-ai/langchainjs](https://github.com/langchain-ai/langchainjs) 

```javascript
export async function getEncoding(encoding: TiktokenEncoding) {
  if (!(encoding in cache)) {
    cache[encoding] = caller
      .fetch(`https://tiktoken.pages.dev/js/${encoding}.json`)
      .then((res) => res.json())
      .then((data) => new Tiktoken(data))
      .catch((e) => {
        delete cache[encoding];
        throw e;
      });
  }

  return await cache[encoding];
}

```

[libs/langchain-core/src/utils/tiktoken.ts](https://github.com/langchain-ai/langchainjs/blob/7309848b94f1c9940197e3ebfc9a63bf508b3f15/libs/langchain-core/src/utils/tiktoken.ts#L13) · [More projects using js-tiktoken →](https://dashboard.exa.ai/playground/search?q=js-tiktoken%20GitHub%20projects)

**Quickstart**

```javascript
import { getEncoding } from "js-tiktoken";
const tokenizer = getEncoding("o200k_base");
console.log(tokenizer.encode("Hello world"));

```

From [README.md](https://raw.githubusercontent.com/dqbd/tiktoken/main/js/README.md)

### Transformers.js

[GitHub](https://github.com/huggingface/transformers.js) · [npm](https://www.npmjs.com/package/@huggingface/transformers) · [Docs](https://huggingface.co/docs/transformers.js/api/tokenizers)

Loads pretrained model tokenizers and formats model-specific chat prompts.

- Downloads / mo: 19.1M
- Stars: 16.4K
- Last release: 4.3.2
- License: Apache-2.0
- Capabilities: [From the Transformers.js docs](https://huggingface.co/docs/transformers.js/api/tokenizers)

**Strengths**

- **Loads tokenizers by model ID.** AutoTokenizer selects an implementation from tokenizer_config.json.
- **Applies model-specific chat templates.** Render roles and control tokens in the model’s prompt format.

**Watch out for**

- **Tool formatting depends on templates.** Tools have no effect when templates lack function-calling support.
- **Requires pretrained tokenizer files.** Loading fails when required tokenizer files are missing.

```sh
npm install @huggingface/transformers@4.3.2
```

**can1357/oh-my-pi** (39.2K stars)

[can1357/oh-my-pi](https://github.com/can1357/oh-my-pi) 

```typescript
export function renderTextChatTemplate(
	tokenizer: TextGenerationPipeline["tokenizer"],
	messages: readonly { role: string; content: string }[],
	options: TextChatTemplateOptions,
): string {
	const source: unknown = tokenizer.get_chat_template();
	const chatTemplate = typeof source === "string" ? source.replace(GENERATION_STATEMENT, "") : undefined;
	const templateOptions: {
		chat_template?: string;
		add_generation_prompt: boolean;
		tokenize: false;
		enable_thinking: boolean;
	} = {
		...(chatTemplate === undefined ? {} : { chat_template: chatTemplate }),
		add_generation_prompt: options.addGenerationPrompt,
		tokenize: false,
		enable_thinking: options.enableThinking,
	};
	return tokenizer.apply_chat_template([...messages], templateOptions);
}

```

[packages/coding-agent/src/tiny/completion-prompt.ts](https://github.com/can1357/oh-my-pi/blob/1bdbf6d242d99ca62bdf2feeff4519ff992f647d/packages/coding-agent/src/tiny/completion-prompt.ts#L14) · [More projects using Transformers.js →](https://dashboard.exa.ai/playground/search?q=JavaScript%20applications%20using%20%40huggingface/transformers%20to%20count%20model%20tokens%2C%20inspect%20encoded%20text%20or%20format%20model%20chat%20prompts&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```typescript
import { AutoTokenizer } from "@huggingface/transformers";
const tokenizer = await AutoTokenizer.from_pretrained("Xenova/bert-base-uncased");
const { input_ids } = await tokenizer("Hello world");
console.log(input_ids);

```

From [tokenizers.md](https://huggingface.co/docs/transformers.js/api/tokenizers)

### Tokenizers.js

[GitHub](https://github.com/huggingface/tokenizers.js) · [npm](https://www.npmjs.com/package/@huggingface/tokenizers) · [Docs](https://app.unpkg.com/@huggingface/tokenizers@0.2.0/files/README.md)

Implements common model tokenizers in pure JavaScript and TypeScript.

- Downloads / mo: 15.4M
- Stars: 62
- Last release: 0.2.0
- License: Apache-2.0
- Capabilities: [From the Tokenizers.js docs](https://app.unpkg.com/@huggingface/tokenizers@0.2.0/files/README.md)

```sh
npm install @huggingface/tokenizers@0.2.0
```

**samanhappy/mcphub** (2.7K stars)

[samanhappy/mcphub](https://github.com/samanhappy/mcphub) 

```javascript
const tokenizeAndTruncate = (tokenizer: HFTokenizer): string => {
    const encoded = tokenizer.encode(text);
    const rawIds: ArrayLike<number | bigint> = encoded.ids;
    const ids = Array.from(rawIds as ArrayLike<number>).map(Number);
    if (ids.length <= maxTokens) {
      return text;
    }
    const truncatedIds = ids.slice(0, maxTokens);
    return tokenizer.decode(truncatedIds, { skip_special_tokens: true });
  };

```

[src/utils/tokenTruncation.ts](https://github.com/samanhappy/mcphub/blob/874b72a65c688069bf0d096b01efd448073de9f7/src/utils/tokenTruncation.ts#L301) · [More projects using Tokenizers.js →](https://dashboard.exa.ai/playground/search?q=%40huggingface/tokenizers%20GitHub%20projects)

**Quickstart**

```javascript
import { Tokenizer } from "@huggingface/tokenizers";
const base = "https://huggingface.co/HuggingFaceTB/SmolLM3-3B/resolve/main";
const json = await fetch(`${base}/tokenizer.json`).then(response => response.json());
const config = await fetch(`${base}/tokenizer_config.json`).then(response => response.json());
const tokenizer = new Tokenizer(json, config);
console.log(tokenizer.encode("Hello world").ids);

```

From [README.md](https://app.unpkg.com/@huggingface/tokenizers@0.2.0/files/README.md)

### gpt-tokenizer

[GitHub](https://github.com/niieani/gpt-tokenizer) · [npm](https://www.npmjs.com/package/gpt-tokenizer) · [Docs](https://raw.githubusercontent.com/niieani/gpt-tokenizer/main/README.md)

Encodes and decodes model text with a pure-JavaScript byte-pair tokenizer.

- Downloads / mo: 10.6M
- Stars: 862
- Last release: 4.1.2
- License: MIT
- Capabilities: [From the gpt-tokenizer docs](https://raw.githubusercontent.com/niieani/gpt-tokenizer/main/README.md)

**Strengths**

- **Checks budgets before full encoding.** Check text or chat limits without encoding the entire input.
- **Updates counts after text edits.** Track appended text and edits with an incremental counter.

**Watch out for**

- **Reserved tokens require explicit permission.** Configure allowedSpecial when reserved token strings should be accepted.
- **Incremental edits can rescan text.** Long words or whitespace runs can require rescanning a large region.

```sh
npm install gpt-tokenizer@4.1.2
```

**continuedev/continue** (36.5K stars)

[continuedev/continue](https://github.com/continuedev/continue) 

```typescript
function countToolCallFunctionTokens(
  toolCallFunction: { name?: string; arguments?: string } | undefined,
): number {
  if (!toolCallFunction) {
    return 0;
  }

  let tokenCount = 0;
  tokenCount += encode(toolCallFunction.name ?? "").length + 10; // Function name and structure overhead
  tokenCount += encode(toolCallFunction.arguments ?? "").length; // Arguments
  return tokenCount;
}

```

[extensions/cli/src/util/tokenizer.ts](https://github.com/continuedev/continue/blob/5522c6f44ca0ac3528b37244818fbfa39b5af470/extensions/cli/src/util/tokenizer.ts#L67) · [More projects using gpt-tokenizer →](https://dashboard.exa.ai/playground/search?q=JavaScript%20applications%20using%20gpt-tokenizer%20to%20count%20model%20tokens%2C%20inspect%20encoded%20text%20or%20format%20model%20chat%20prompts&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```typescript
import { encode, decode } from "gpt-tokenizer";
const ids = encode("Hello world");
console.log(ids, decode(ids));

```

From [README.md](https://raw.githubusercontent.com/niieani/gpt-tokenizer/main/README.md)

### tiktoken

[GitHub](https://github.com/dqbd/tiktoken) · [npm](https://www.npmjs.com/package/tiktoken) · [Docs](https://raw.githubusercontent.com/dqbd/tiktoken/main/README.md)

Provides JavaScript and WASM bindings to OpenAI-model byte-pair tokenizers.

- Downloads / mo: 8.7M
- Stars: 1.1K
- Last release: 1.0.22
- License: MIT
- Capabilities: [From the tiktoken docs](https://raw.githubusercontent.com/dqbd/tiktoken/main/README.md)

**Strengths**

- **Maps models to their encodings.** Resolve a model tokenizer with encoding_for_model.
- **Loads individual encoding tables.** Use tiktoken/lite to avoid loading every encoder at once.

**Watch out for**

- **Encoders need explicit cleanup.** Call free() when an encoder is no longer needed.
- **Vite requires extra build plugins.** Add WASM and top-level-await plugins when bundling with Vite.

```sh
npm install tiktoken@1.0.22
```

**enricoros/big-AGI** (7.2K stars)

[enricoros/big-AGI](https://github.com/enricoros/big-AGI) 

```typescript
export function textTokensForEncodingId(text: string, encodingId: string, debugFrom: string): Array<UITokenChunk> | null {
  // The library shall have been preloaded - if not, attempt to start its loading and return null to indicate we're not ready to count
  if (!get_encoding) {
    if (!informTheUser) {
      console.warn('textTokensForEncodingId: Tiktoken library is not yet loaded, loading now...');
      informTheUser = true;
    }
    void preloadTiktokenLibrary().catch(() => {}); // preload without waiting; swallow rejection (already logged, falls back to approximate counting) to avoid an unhandled-rejection report
    return null;
  }

  if (!(encodingId in tokenizerCache)) {
    try {
      tokenizerCache[encodingId] = get_encoding(encodingId as TiktokenEncoding);
    } catch (e) {
      console.error(`textTokensForEncodingId: Error initializing tokenizer "${encodingId}": ${e}`);
      return null;
    }
  }

  try {
    const tokens = tokenizerCache[encodingId]?.encode(text, 'all', []) || new Uint32Array();
    if (DEBUG_TOKEN_COUNT)
      console.log(`textTokensForEncodingId: ${debugFrom}, ${encodingId}, "${text.slice(0, 10)}": ${tokens.length}`);

    // for every token create an object {t:token, b: bytes}
    const tokenDetails: UITokenChunk[] = [];
    for (let i = 0; i < tokens.length; i++) {
      const bytesForToken = tokenizerCache[encodingId].decode_single_token_bytes(tokens[i]);
      const stringForToken = String.fromCharCode(...bytesForToken);
      tokenDetails.push({
        token: tokens[i],
        chunk: stringForToken,
        bytes: bytesForToken.join(', '),
      });
    }
    return tokenDetails;
  } catch (e) {
    console.error(`textTokensForEncodingId: Error tokenizing "${text.slice(0, 10)}..." with tokenizer '${encodingId}': ${e}`);
    return null;
  }
}

```

[src/common/tokens/tokens.text.ts](https://github.com/enricoros/big-AGI/blob/f157841f5c644e42a55f548a1ebf401488c45565/src/common/tokens/tokens.text.ts#L107) · [More projects using tiktoken →](https://dashboard.exa.ai/playground/search?q=JavaScript%20applications%20using%20tiktoken%20to%20count%20model%20tokens%2C%20inspect%20encoded%20text%20or%20format%20model%20chat%20prompts&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```typescript
import { get_encoding } from "tiktoken";
const tokenizer = get_encoding("o200k_base");
console.log(tokenizer.encode("Hello world"));
tokenizer.free();

```

From [README.md](https://raw.githubusercontent.com/dqbd/tiktoken/main/README.md)

### @anthropic-ai/tokenizer

[GitHub](https://github.com/anthropics/anthropic-tokenizer-typescript) · [npm](https://www.npmjs.com/package/@anthropic-ai/tokenizer) · [Docs](https://raw.githubusercontent.com/anthropics/anthropic-tokenizer-typescript/main/README.md)

Tokenizes text for Claude models.

- Downloads / mo: 1.4M
- Stars: 108
- Last release: 0.0.4
- License: Apache-2.0
- Capabilities: [From the @anthropic-ai/tokenizer docs](https://raw.githubusercontent.com/anthropics/anthropic-tokenizer-typescript/main/README.md)

```sh
npm install @anthropic-ai/tokenizer@0.0.4
```

**Quickstart**

```javascript
import { countTokens } from "@anthropic-ai/tokenizer";
console.log(countTokens("Hello world"));

```

From [README.md](https://raw.githubusercontent.com/anthropics/anthropic-tokenizer-typescript/main/README.md) · [Find projects using @anthropic-ai/tokenizer →](https://dashboard.exa.ai/playground/search?q=%40anthropic-ai/tokenizer%20GitHub%20projects)

### GPT-3-Encoder

[GitHub](https://github.com/latitudegames/GPT-3-Encoder) · [npm](https://www.npmjs.com/package/gpt-3-encoder) · [Docs](https://raw.githubusercontent.com/AIDungeon/GPT-3-Encoder/master/README.md)

Implements the original GPT-2/GPT-3 text encoder and decoder in JavaScript.

- Downloads / mo: 640.1K
- Stars: 722
- Last release: 1.1.4
- License: MIT
- Capabilities: [From the GPT-3-Encoder docs](https://raw.githubusercontent.com/AIDungeon/GPT-3-Encoder/master/README.md)

**Strengths**

- **Fits legacy GPT-2/3 workflows.** Encode text and decode token IDs for those model families.
- **Exposes individual decoded token pieces.** Decode token IDs separately when inspecting a sequence.

**Watch out for**

- **Targets legacy GPT-2/3 encodings.** Match the model tokenizer before relying on context-budget estimates.

```sh
npm install gpt-3-encoder@1.1.4
```

**mckaywrigley/paul-graham-gpt** (2.7K stars)

[mckaywrigley/paul-graham-gpt](https://github.com/mckaywrigley/paul-graham-gpt) 

```typescript
const chunkEssay = async (essay: PGEssay) => {
  const { title, url, date, thanks, content, ...chunklessSection } = essay;

  let essayTextChunks = [];

  if (encode(content).length > CHUNK_SIZE) {
    const split = content.split(". ");
    let chunkText = "";

    for (let i = 0; i < split.length; i++) {
      const sentence = split[i];
      const sentenceTokenLength = encode(sentence);
      const chunkTextTokenLength = encode(chunkText).length;

      if (chunkTextTokenLength + sentenceTokenLength.length > CHUNK_SIZE) {
        essayTextChunks.push(chunkText);
        chunkText = "";
      }

      if (sentence[sentence.length - 1].match(/[a-z0-9]/i)) {
        chunkText += sentence + ". ";
      } else {
        chunkText += sentence + " ";
      }
    }

    essayTextChunks.push(chunkText.trim());
  } else {
    essayTextChunks.push(content.trim());
  }

  const essayChunks = essayTextChunks.map((text) => {
    const trimmedText = text.trim();

    const chunk: PGChunk = {
      essay_title: title,
      essay_url: url,
      essay_date: date,
      essay_thanks: thanks,
      content: trimmedText,
      content_length: trimmedText.length,
      content_tokens: encode(trimmedText).length,
      embedding: []
    };

    return chunk;
  });

  if (essayChunks.length > 1) {
    for (let i = 0; i < essayChunks.length; i++) {
      const chunk = essayChunks[i];
      const prevChunk = essayChunks[i - 1];

      if (chunk.content_tokens < 100 && prevChunk) {
        prevChunk.content += " " + chunk.content;
        prevChunk.content_length += chunk.content_length;
        prevChunk.content_tokens += chunk.content_tokens;
        essayChunks.splice(i, 1);
        i--;
      }
    }
  }

  const chunkedSection: PGEssay = {
    ...essay,
    chunks: essayChunks
  };

  return chunkedSection;
};

```

[scripts/scrape.ts](https://github.com/mckaywrigley/paul-graham-gpt/blob/795be559a058e578c92e8260242d4d3847a4e238/scripts/scrape.ts#L110) · [More projects using GPT-3-Encoder →](https://dashboard.exa.ai/playground/search?q=JavaScript%20applications%20using%20gpt-3-encoder%20to%20count%20model%20tokens%2C%20inspect%20encoded%20text%20or%20format%20model%20chat%20prompts&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```typescript
const { encode, decode } = require("gpt-3-encoder");
const ids = encode("Hello world");
console.log(ids, decode(ids));

```

From [README.md](https://raw.githubusercontent.com/AIDungeon/GPT-3-Encoder/master/README.md)

## FAQ

### Which JavaScript tokenizer library should I use?

[js-tiktoken](#js-tiktoken) and [gpt-tokenizer](#gpt-tokenizer) suit counting tokens for OpenAI models in pure JavaScript. [Transformers.js](#transformers-js) suits open models that publish their own tokenizer on Hugging Face. [tiktoken](#tiktoken) suits Node.js code that can load WASM bindings.

### How do I count tokens in JavaScript?

Encode the text with the tokenizer for the target model and take the length of the result. [js-tiktoken](#js-tiktoken) and [gpt-tokenizer](#gpt-tokenizer) do this for OpenAI encodings.

### What is tiktoken?

[tiktoken](#tiktoken) is the byte-pair tokenizer for OpenAI models. Its npm package provides WASM bindings, and [js-tiktoken](#js-tiktoken) is a pure JavaScript port.

### What is byte pair encoding?

Byte pair encoding builds a vocabulary by repeatedly merging the most frequent pair of adjacent symbols. A tokenizer applies those merges to split new text into tokens.

### How do I count Claude tokens?

The Claude API's token counting endpoint counts tokens for current models. [@anthropic-ai/tokenizer](#anthropic-ai-tokenizer) tokenizes text locally but matches only older Claude models.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best JavaScript tokenizer libraries tiktoken gpt-tokenizer GPT-3-Encoder Transformers.js code examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
