Building Browser-to-Browser File Transfers with WebRTC, Chunking and AES-GCM
Browsers are capable of much more than rendering websites and making API requests. With WebRTC and the Web Crypto API, it's possible to build browser-to-browser file sharing systems without requiring users to install app
Browsers are capable of much more than rendering websites and making API requests. With WebRTC and the Web Crypto API, it's possible to build browser-to-browser file sharing systems without requiring users to install applications or create accounts.
While building SendlyShare, a browser-based tool for transferring files and text between devices using a 6-digit code, I faced a few interesting engineering challenges:
- Establishing direct peer-to-peer connections between devices.
- Handling large files without overwhelming the WebRTC data channel.
- Supporting transfers when network restrictions prevent direct connections.
- Encrypting files in the browser before they reach a relay server.
In this article, I'll explain how these pieces work together and share some practical implementation patterns.
1. Building a hybrid transfer architecture
WebRTC allows browsers to communicate directly using peer-to-peer connections. Once two peers exchange session descriptions (SDP) and ICE candidates through a signaling mechanism, they can establish a connection using RTCDataChannel.
But direct connectivity isn't guaranteed in every network environment.
When devices are on the same network
When two devices are connected to the same Wi-Fi network, WebRTC may establish a direct connection using local network candidates.
This allows files to move directly between devices without uploading them to cloud storage.
When devices are on different networks
Things become more complicated when devices are connected through mobile networks, corporate firewalls, or restrictive NAT configurations.
In these situations, direct peer-to-peer connectivity may not always be possible.
A hybrid architecture can help:
- Use WebRTC for direct transfers whenever connectivity allows.
- Fall back to an HTTPS relay when direct connectivity fails.
- Use expiring relay storage to avoid keeping transferred files indefinitely.
Architecture
Device A ───────── WebRTC ───────── Device B
Direct P2P Transfer
Device A ── HTTPS Relay ────────── Device B
Fallback Transfer
The idea is simple: prefer direct communication, but don't make the entire transfer experience dependent on it.
2. Sending large files through RTCDataChannel
One of the challenges with WebRTC file transfers is handling large files efficiently.
Sending an entire file in a single dataChannel.send() call isn't a reliable approach for large payloads. Message-size limitations and buffer pressure can vary depending on browser implementation and negotiated connection parameters.
Instead, files can be split into smaller chunks and sent incrementally.
We can use bufferedAmount and bufferedAmountLowThreshold to monitor the outgoing buffer and apply backpressure.
File transfer implementation
const CHUNK_SIZE = 16 * 1024; // 16 KB
async function sendFileOverDataChannel(file, dataChannel) {
dataChannel.bufferedAmountLowThreshold = 65536;
let offset = 0;
// Send file metadata
dataChannel.send(JSON.stringify({
type: "meta",
name: file.name,
size: file.size,
mime: file.type
}));
// Send file chunks
while (offset < file.size) {
if (
dataChannel.bufferedAmount >
dataChannel.bufferedAmountLowThreshold
) {
await new Promise((resolve) => {
dataChannel.onbufferedamountlow = () => resolve();
});
}
const slice = file.slice(
offset,
offset + CHUNK_SIZE
);
const buffer = await slice.arrayBuffer();
dataChannel.send(buffer);
offset += buffer.byteLength;
}
// Signal completion
dataChannel.send(JSON.stringify({
type: "eof"
}));
}
Why backpressure matters
Without backpressure handling, the sender may continuously push data into the channel's outgoing buffer faster than the network can transmit it.
This can lead to excessive buffering, memory pressure, and unstable transfers.
By waiting for the buffer to drain before sending more data, we can make file transfers more manageable.
On the receiving side, incoming chunks can be collected and assembled into a Blob for downloading once the transfer is complete.
In production, it's also important to handle channel closure, errors, cancellation, timeouts, and memory management on both sides.
3. Encrypting files on the client side using Web Crypto API
When a transfer falls back to a relay server, privacy becomes an important consideration.
HTTPS protects data in transit, but application-level encryption can provide an additional layer of protection by encrypting the file before it is uploaded to the relay.
The browser's native Web Crypto API makes this possible.
In this example, we'll use:
- PBKDF2 to derive a key from a password.
- AES-GCM with a 256-bit key for encryption.
- A random 16-byte salt.
- A random 12-byte initialization vector (IV).
Encryption implementation
async function encryptFileBuffer(arrayBuffer, password) {
const encoder = new TextEncoder();
const salt = crypto.getRandomValues(
new Uint8Array(16)
);
const iv = crypto.getRandomValues(
new Uint8Array(12)
);
// Import password
const keyMaterial = await crypto.subtle.importKey(
"raw",
encoder.encode(password),
"PBKDF2",
false,
["deriveKey"]
);
// Derive AES-GCM key
const aesKey = await crypto.subtle.deriveKey(
{
name: "PBKDF2",
salt,
iterations: 100000,
hash: "SHA-256"
},
keyMaterial,
{
name: "AES-GCM",
length: 256
},
false,
["encrypt"]
);
// Encrypt the file
const encryptedBuffer = await crypto.subtle.encrypt(
{
name: "AES-GCM",
iv
},
aesKey,
arrayBuffer
);
// Pack salt + IV + ciphertext
const packed = new Uint8Array(
salt.byteLength +
iv.byteLength +
encryptedBuffer.byteLength
);
packed.set(salt, 0);
packed.set(iv, salt.byteLength);
packed.set(
new Uint8Array(encryptedBuffer),
salt.byteLength + iv.byteLength
);
return packed.buffer;
}
How the encrypted payload is structured
The resulting buffer contains:
[ Salt (16 bytes) ]
[ IV (12 bytes) ]
[ Encrypted File Data ]
The receiver can extract the salt and IV, derive the same encryption key from the password, and decrypt the file locally.
AES-GCM also provides authenticated encryption. If the password is incorrect or the encrypted data has been modified, decryption will fail.
Security note: The PBKDF2 iteration count should be reviewed and benchmarked for the target devices. Avoid reusing an IV with the same AES-GCM key.
4. Putting everything together
A practical browser-based file sharing system needs more than a connection and an encryption function.
The architecture combines several technologies:
- WebRTC DataChannel: Direct peer-to-peer communication.
- Chunking: Sending large files in manageable pieces.
- Backpressure: Preventing outgoing buffers from growing uncontrollably.
- HTTPS relay fallback: Supporting transfers when direct connectivity isn't available.
- Web Crypto API: Encrypting files on the client side.
The goal is to keep the user experience as simple as possible while handling the complexity behind the scenes.
Try it yourself
I built these ideas into SendlyShare, a browser-based tool for transferring files and text snippets between devices using a 6-digit code.
It supports file sharing and a real-time synced notepad for moving links, text, and JSON snippets between screens.
No signup. No native app installation.
What would you do differently?
Have you implemented WebRTC file transfers in production?
I'd be interested to know:
- What chunk size works best for your use case?
- How do you handle large files on mobile browsers?
- Have you used streaming APIs to avoid assembling large Blobs in memory?
- What approach do you use when direct peer-to-peer connectivity fails?
Let's discuss in the comments.
Additional discussion: One edge case I noticed during mobile browser testing is that Safari on iOS can behave differently from desktop Chrome when handling large Blob assemblies. Has anyone explored practical streaming-to-disk approaches on mobile browsers?
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.