Build peer-to-peer file transfer in JavaScript
When sender and recipient are online at the same time, WebRTC can move files directly between their browsers without uploading to object storage first. Trystero handles peer discovery, chunking, backpressure, and reassembly; your app handles transfer approval, progress UI, and saving the file.
When peer-to-peer file transfer fits
Uploading to a server makes sense when recipients download later. When both peers are present simultaneously—dropping a video export between two laptops, sharing assets inside a live collaborative session, or moving large files across local Wi-Fi where LAN speed beats internet upload—a direct WebRTC data channel transfers encrypted bytes straight from sender to receiver without storing copies anywhere.
Both tabs must stay open during the transfer, the receiving browser needs enough memory to buffer the reassembled payload, and the ~10–15% of networks that block direct peer connections require a TURN server (which relays encrypted bytes and incurs bandwidth).
Approval, progress, and cancellation
Before sending chunks, Trystero transmits a header carrying
byteLength and your metadata. The receiver’s
onReceive callback approves or declines the transfer; once
accepted, chunks stream with progress callbacks on both ends and land in
onMessage as a Uint8Array. Register
onReceive synchronously on setup so the gate is active before
peers offer files.
import {joinRoom} from 'trystero'
const room = joinRoom({appId: 'dropzone.example.com'}, transferId)
const files = room.makeAction('file')
// 1. Gate incoming transfers before file bytes are sent
files.onReceive(({byteLength, userId, metadata, signal}) => {
if (byteLength > 100 * 1024 ** 2) return false
return askToAcceptFile({from: userId, metadata, byteLength, signal})
})
// 2. Track incoming progress (0 to 1)
files.onReceiveProgress((progress, {userId, metadata}) => {
renderIncomingProgress(userId, metadata.name, progress)
})
// 3. Save the reassembled Uint8Array
files.onMessage((bytes, {userId, metadata}) => {
const blob = new Blob([bytes], {type: metadata.type})
addDownload({
from: userId,
url: URL.createObjectURL(blob),
name: metadata.name,
size: blob.size
})
})
// 4. Send with progress and cancellation
fileInput.onchange = async () => {
const file = fileInput.files?.[0]
if (!file) return
const controller = new AbortController()
cancelButton.onclick = () => controller.abort()
try {
await files.send(file, {
target: recipientUserId,
metadata: {name: file.name, type: file.type},
onProgress: progress => renderSendProgress(file.name, progress),
signal: controller.signal
})
} catch (err) {
if (err.kind === 'rejected') showDeclined(recipientUserId)
else if (err.kind !== 'aborted') showTransferError(err)
}
} askToAcceptFile() resolves to true or
false, and should close its prompt if signal
aborts because the sender cancelled or disconnected. Returning
false rejects the sender’s send() promise with
err.kind === 'rejected'; the other ActionError
kinds are 'disconnected', 'timeout', and
'aborted'.
Verifying the sender
Every incoming transfer carries a verified userId derived
from the sender’s ECDSA keypair and checked against their DTLS
certificate during connection setup. Combine it with a
makeUserState('profile') display name so your approval
prompt can show who is offering mix-final-v7.flac and verify
subsequent files come from the same key.
Batches and memory limits
Each send() call tracks a single payload. To send multiple
files concurrently, attach a unique id in
metadata so progress indicators stay distinct:
await Promise.all(
[...fileInput.files].map(file =>
files.send(file, {
target: recipientUserId,
metadata: {id: crypto.randomUUID(), name: file.name, type: file.type},
onProgress: p => renderSendProgress(file.name, p)
})
)
)
Rooms default to a 256 MiB concurrent receive budget across all in-flight
transfers; offers exceeding available budget wait until earlier transfers
finish. Raise maxReceiveBytes on the receiving room for
larger payloads, keeping in mind that Trystero reassembles incoming files
in memory as a Uint8Array rather than streaming chunks to
disk:
const room = joinRoom(
{
appId: 'dropzone.example.com',
maxReceiveBytes: 2 * 1024 ** 3 // allow up to 2 GiB in flight at once
},
transferId
)Implementation notes
-
A resolved
send()promise confirms the chunks left the sender’s buffer and were reassembled by the peer, not that the user clicked download. Use akind: 'request'action if you need an explicit receipt. -
Binary buffers larger than 16 KiB stream directly from your
ArrayBufferwithout copying. Avoid mutating the buffer untilsend()settles (passing aFileorBlobavoids shared-buffer mutation). -
Treat
metadataas untrusted peer input: sanitize filenames before rendering or saving, and callURL.revokeObjectURL()when download links are removed. -
In an experimental
scale()room, transfers larger than 16 KiB automatically promote a direct WebRTC connection to the recipient instead of forwarding chunks through intermediate peers.