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

> Control Transformers.js model and weight storage by setting custom cache directories via env.cacheDir. Optimize your downloads and organization.

- Repository: [Hugging Face/transformers.js](https://github.com/huggingface/transformers.js)
- Tags: how-to-guide
- Published: 2026-03-03

---

**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](https://github.com/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`](https://github.com/huggingface/transformers.js/blob/main/packages/transformers/src/env.js), the default cache path is constructed conditionally:

```javascript
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:

```javascript
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`](https://github.com/huggingface/transformers.js/blob/main/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:

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

```

This occurs at lines 63-64 of [`cache.js`](https://github.com/huggingface/transformers.js/blob/main/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.

```javascript
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:

```javascript
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:

```javascript
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:

- **[`packages/transformers/src/env.js`](https://github.com/huggingface/transformers.js/blob/main/packages/transformers/src/env.js)** – Defines the global `env` object, detects the runtime environment, and initializes `env.cacheDir` with the default filesystem path.
- **[`packages/transformers/src/utils/cache.js`](https://github.com/huggingface/transformers.js/blob/main/packages/transformers/src/utils/cache.js)** – Implements the `getCache()` factory function that selects between custom, browser, and filesystem cache backends.
- **[`packages/transformers/src/utils/hub/files.js`](https://github.com/huggingface/transformers.js/blob/main/packages/transformers/src/utils/hub/files.js)** – Contains the `FileCache` class that performs the actual file I/O operations within the directory specified by `env.cacheDir`.

## 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`](https://github.com/huggingface/transformers.js/blob/main/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.