WebTorrent Client
WebTorrent is a versatile streaming BitTorrent client designed for both Node.js environments and web browsers. Currently stable at version 2.8.5, it receives frequent minor updates and bug fixes, with new features introduced periodically. Its primary differentiator is its ability to operate directly within a web browser using WebRTC data channels for peer-to-peer communication, making it the "streaming torrent client for the web." In Node.js, it functions as a standard torrent client utilizing TCP and UDP. This pure JavaScript library exposes torrent files as streams, supporting on-demand piece fetching, and can seamlessly switch between sequential and rarest-first piece selection strategies. WebTorrent facilitates connecting "web peers" (browser clients) with other WebTorrent-compatible clients, including desktop applications and specialized command-line tools like `webtorrent-hybrid`.
Common errors
-
Uncaught Error: Error downloading torrent: XHR error
cause This error often occurs in browser environments when trying to fetch a .torrent file from a URL without proper CORS (Cross-Origin Resource Sharing) headers from the server.fixEnsure the server hosting the .torrent file has `Access-Control-Allow-Origin` headers configured to permit requests from your domain. -
No peers found
cause In a browser, this typically means there are no WebRTC-compatible seeders for the given torrent. Traditional BitTorrent peers are not visible to browser clients.fixVerify that the torrent is being seeded by a client that supports WebTorrent/WebRTC (e.g., WebTorrent Desktop, instant.io). -
The torrent ID format is invalid. Supported formats: Magnet URI: magnet:?xt=urn:btih:... Info hash: 08ada5a7a6183aae1e09d831df6748d566095a10. HTTP URL to .torrent file: https://example.com/file.torrent. File path (Node.js only): /path/to/file.torrent. Buffer (Node.js only): Buffer containing .torrent file.
cause The input provided to `client.add()` does not match one of the supported torrent identifier formats.fixDouble-check the magnet URI, info hash, or URL for correctness and ensure it adheres to the specified formats. For Node.js, file paths and Buffers are also accepted. -
Write to disk: access denied
cause In Node.js, the WebTorrent client attempted to write downloaded files to a directory where the process lacks write permissions.fixEnsure the target download directory (specified in `client.add({ path: './downloads' })`) has appropriate write permissions for the Node.js process. Try using a different, accessible directory or running the process with elevated privileges if necessary.
Warnings
- breaking WebTorrent v2.0+ is ESM-only. CommonJS `require()` syntax is no longer supported and will lead to errors in modern Node.js environments or bundled browser applications.
- breaking WebTorrent v2.0+ requires Node.js version 16 or later. Older Node.js versions (12, 14, etc.) are no longer supported and will cause runtime issues.
- breaking The `file.getBuffer()` method has been deprecated and removed in favor of standard Web APIs. Attempts to use it will fail.
- gotcha WebTorrent clients running in a web browser can only connect to other WebTorrent-compatible clients (known as 'web peers') that support WebRTC. They cannot directly connect to traditional BitTorrent clients using TCP or UDP, unless a 'hybrid' client acts as a bridge.
- gotcha Starting with v2.0, WebTorrent in the browser uses persistent storage (File System Access API + IndexedDB) instead of memory-only. This means torrent data can persist across sessions but requires explicit cleanup to free up space.
Install
-
npm install webtorrent -
yarn add webtorrent -
pnpm add webtorrent
Imports
- WebTorrent
const WebTorrent = require('webtorrent')import WebTorrent from 'webtorrent'
- WebTorrent.WEBRTC_SUPPORT
import WebTorrent from 'webtorrent'; const supportsWebRTC = WebTorrent.WEBRTC_SUPPORT
- Torrent
import WebTorrent, { Torrent } from 'webtorrent'; // or import type { Torrent } from 'webtorrent' for TS
Quickstart
import WebTorrent from 'webtorrent';
import fs from 'node:fs';
const client = new WebTorrent();
const magnetURI = 'magnet:?xt=urn:btih:08ada5a7a6183aae1e09d831df6748d566095a10'; // Example Sintel torrent (public domain)
client.add(magnetURI, { path: './downloads' }, (torrent) => {
console.log(`Client is downloading torrent: ${torrent.infoHash}`);
torrent.on('download', () => {
console.log(`Downloaded: ${torrent.downloaded} bytes of ${torrent.length} total`);
});
torrent.on('done', () => {
console.log('Torrent download finished!');
torrent.files.forEach((file) => {
console.log(`File name: ${file.name}, length: ${file.length}`);
// Example: Stream a file to disk (Node.js only)
const source = file.createReadStream();
const destination = fs.createWriteStream(`./downloads/${file.name}`);
source.pipe(destination);
source.on('end', () => {
console.log(`Finished writing ${file.name} to disk.`);
});
});
client.destroy(); // Clean up client after download
});
torrent.on('error', (err) => {
console.error('Torrent error:', err.message);
client.destroy();
});
});
client.on('error', (err) => {
console.error('WebTorrent client error:', err.message);
});