Skip to main content
Make sure you have WebTorrent installed. If not, see the Installation Guide.

Basic Concepts

Before diving in, let’s understand the key components:
  • Client - The main WebTorrent instance that manages all torrents
  • Torrent - Represents a torrent being downloaded or seeded
  • File - Individual files within a torrent
  • Peer - Other clients you’re connected to

Your First Torrent Download

Let’s download a file using WebTorrent. This example works in both Node.js and the browser.
1

Create a WebTorrent client

First, import WebTorrent and create a client instance:
import WebTorrent from 'webtorrent'

const client = new WebTorrent()
2

Add a torrent

Use a magnet URI to start downloading:
const magnetURI = 'magnet:?xt=urn:btih:08ada5a7a6183aae1e09d831df6748d566095a10&dn=Sintel&tr=udp%3A%2F%2Fexplodie.org%3A6969&tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969'

client.add(magnetURI, torrent => {
  console.log('Client is downloading:', torrent.infoHash)
})
3

Access the files

Once metadata is received, you can access the files:
client.add(magnetURI, torrent => {
  console.log('Torrent files:')
  for (const file of torrent.files) {
    console.log(`  - ${file.name} (${file.length} bytes)`)
  }
})

Complete Examples

Stream a video torrent directly in the browser:
import WebTorrent from 'webtorrent'

const client = new WebTorrent()

// Register service worker for HTTP streaming
const controller = await navigator.serviceWorker.register('./sw.min.js', {
  scope: './'
})
await navigator.serviceWorker.ready
client.createServer({ controller })

// Add the torrent
const magnetURI = 'magnet:...'

client.add(magnetURI, torrent => {
  // Find the video file
  const file = torrent.files.find(file => file.name.endsWith('.mp4'))

  // Stream to a video element
  const video = document.querySelector('video')
  file.streamTo(video)
})
Make sure to copy sw.min.js from node_modules/webtorrent/dist/sw.min.js to your public directory.

Working with Files

Getting File Data

WebTorrent provides multiple ways to access file data:
const file = torrent.files[0]

// As a Blob (browser)
const blob = await file.blob()
const url = URL.createObjectURL(blob)

// As an ArrayBuffer
const buffer = await file.arrayBuffer()

// As a stream
const stream = file.createReadStream()
stream.on('data', chunk => {
  console.log('Got chunk:', chunk.length)
})

Streaming to a Video Element

In the browser, you can stream directly to a <video> or <audio> element:
const file = torrent.files.find(f => f.name.endsWith('.mp4'))
const video = document.querySelector('video')

file.streamTo(video)

Monitoring Progress

Track download progress and stats in real-time:
client.add(magnetURI, torrent => {
  // Progress updates
  const interval = setInterval(() => {
    console.log('Progress: ' + (torrent.progress * 100).toFixed(1) + '%')
    console.log('Download speed: ' + (torrent.downloadSpeed / 1024).toFixed(1) + ' KB/s')
    console.log('Upload speed: ' + (torrent.uploadSpeed / 1024).toFixed(1) + ' KB/s')
    console.log('Peers: ' + torrent.numPeers)
  }, 1000)

  torrent.on('done', () => {
    clearInterval(interval)
    console.log('Download complete!')
  })
})

Event Handling

WebTorrent uses events to notify you of important changes:
// Client events
client.on('error', err => {
  console.error('Client error:', err)
})

client.on('torrent', torrent => {
  console.log('Torrent added:', torrent.infoHash)
})

// Torrent events
torrent.on('ready', () => {
  console.log('Torrent ready!')
})

torrent.on('done', () => {
  console.log('Torrent downloaded!')
})

torrent.on('warning', err => {
  console.warn('Torrent warning:', err)
})

torrent.on('error', err => {
  console.error('Torrent error:', err)
})
See the Events Reference for all available events.

Configuration Options

Customize the client and torrent behavior:
// Client options
const client = new WebTorrent({
  maxConns: 100,           // Maximum connections per torrent
  downloadLimit: 1000000,  // Bytes per second (-1 = unlimited)
  uploadLimit: 500000,     // Bytes per second (-1 = unlimited)
})

// Torrent options
client.add(magnetURI, {
  path: './downloads',     // Where to save files (Node.js only)
  announce: ['tracker'],   // Additional trackers
  strategy: 'sequential',  // Download strategy
}, torrent => {
  console.log('Torrent added with options')
})
See Configuration Options for all available settings.

Common Patterns

Pausing and Resuming

// Pause all downloads
torrent.pause()

// Resume downloads
torrent.resume()

Selective File Download

client.add(magnetURI, torrent => {
  // Deselect all files first
  torrent.deselect(0, torrent.pieces.length - 1, false)

  // Select only the first file
  const file = torrent.files[0]
  file.select()
})

Destroying Torrents

// Remove torrent and keep files
torrent.destroy()

// Remove torrent and delete files
torrent.destroy({ destroyStore: true })

Cleanup

Always destroy the client when you’re done:
client.destroy(err => {
  if (err) console.error('Error destroying client:', err)
  else console.log('Client destroyed')
})

Next Steps

Browser Usage

Learn about browser-specific features and setup

Node.js Usage

Explore Node.js specific capabilities

API Reference

Dive into the complete API documentation

Examples

See more real-world examples and use cases

Build docs developers (and LLMs) love