How to Configure Custom Cache Directories for Models and Weights in Transformers.js

Set env.cacheDir to your desired path before importing any pipelines or models to control where Transformers.js stores downloaded weights and configuration files.

When working with the huggingface/transformers.js library, managing disk space and organizing model artifacts requires configuring custom cache directories for models and weights. By default, the library downloads model files— including configs, tokenizers, and ONNX weights—into a local .cache folder, but production and CI environments often demand explicit control over these storage locations.

How the Cache Directory System Works

Transformers.js determines where to persist downloaded artifacts through a hierarchy of environment checks and backend selection logic defined in the core source files.

Default Cache Location Detection

At module initialization, the library detects whether it is running in a Node.js environment with filesystem access. In packages/transformers/src/env.js, the default cache path is constructed conditionally:

const DEFAULT_CACHE_DIR = RUNNING_LOCALLY ? path.join(dirname__, '/.cache/') : null;

This value is then assigned to the global env object at line 42 of the same file:

cacheDir: DEFAULT_CACHE_DIR,

When running in browsers or restricted environments where fs is unavailable, this defaults to null, disabling filesystem caching.

Cache Backend Selection

When a model is requested, the getCache() function in packages/transformers/src/utils/cache.js selects the first available storage backend. If filesystem caching is enabled, it instantiates a FileCache using the current env.cacheDir value:

cache = new FileCache(file_cache_dir ?? env.cacheDir);

This occurs at lines 63-64 of cache.js, ensuring that all subsequent downloads are written to the directory specified by your environment configuration.

Setting a Custom Cache Directory in Node.js

To override the default ./.cache location, assign a new path to env.cacheDir immediately after importing the library but before constructing any pipelines or model instances.

import { pipeline, env } from '@huggingface/transformers';

// Configure custom cache directory (relative or absolute)
env.cacheDir = './my-model-cache';

// First invocation downloads files to the custom directory
const classifier = await pipeline('text-classification', 'Xenova/distilbert-base-uncased-finetuned-sst-2-english');

const result = await classifier('I love Transformers.js!');
console.log(result);

Critical timing constraint: The assignment to env.cacheDir must execute before any model is instantiated. Once the library initializes the internal cache backend, changing this value has no effect on existing cache instances.

Advanced Cache Configuration

Using Absolute Paths

For production deployments, use absolute paths to ensure the cache location remains consistent regardless of the working directory:

import { env } from '@huggingface/transformers';
import path from 'node:path';

env.cacheDir = path.resolve(process.cwd(), 'shared/.hf-cache');

This approach is essential when running applications within containerized environments where relative paths may resolve unpredictably.

Clearing the Cache Programmatically

To remove cached artifacts—particularly useful in CI pipelines or when updating model versions—use the ModelRegistry.clear_cache() method:

import { ModelRegistry } from '@huggingface/transformers';

// Remove all files for a specific model from env.cacheDir
await ModelRegistry.clear_cache('Xenova/distilbert-base-uncased-finetuned-sst-2-english');

This operation respects your current env.cacheDir setting, ensuring only the custom location is affected.

Key Source Files

Understanding the implementation requires familiarity with these specific modules:

Summary

  • Default behavior: Transformers.js stores models in ./.cache relative to the package root when running in Node.js environments.
  • Configuration method: Assign a string path to env.cacheDir before any model loading occurs.
  • Backend integration: The FileCache class automatically receives the custom path through the getCache() utility.
  • Cache management: Use ModelRegistry.clear_cache() to remove specific models from your configured directory.
  • Environment scope: Custom directories apply only to filesystem-enabled runtimes; browser environments rely on the Cache API instead.

Frequently Asked Questions

Where does Transformers.js store models by default?

By default, the library stores downloaded models in a .cache directory located at the package root, as determined by the dirname__ resolution in packages/transformers/src/env.js. This only applies when the code detects a local Node.js environment with filesystem capabilities.

Can I change the cache directory after loading a model?

No. The env.cacheDir value is read during the first call to getCache(), which typically happens when you instantiate a pipeline or load a model. Changing the value after this point creates a race condition where the original FileCache instance may retain references to the previous path. Always configure env.cacheDir immediately after importing the library.

How do I clear the model cache in Transformers.js?

Import ModelRegistry from the main package and call ModelRegistry.clear_cache(modelName), passing the full model identifier (e.g., Xenova/distilbert-base-uncased-finetuned-sst-2-english). This method deletes the model's directory structure from the location currently specified by env.cacheDir.

Does custom cache configuration work in browser environments?

No. The env.cacheDir setting only affects Node.js or Deno environments where the fs module is available. In browser contexts, Transformers.js automatically switches to the Web Cache API, which does not expose a configurable directory path due to browser security sandboxing.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →