I want to build a WebSocket chat app with Next.js and Prisma that has end-to-end encryption. I'm thinking of using something like the Signal Protocol or a simplified Double Ratchet algorithm so the server only sees encrypted blobs and never the actual messages.
Assistant
Outlining E2EE with Next.js, WebSockets, and Prisma
A solid approach uses client-side Double Ratchet (e.g., via libsignal-protocol) for end-to-end encryption. The server (Next.js + Prisma) stores only users' public identity and ephemeral keys for key exchanges and relays ciphertext via WebSockets without access to plaintext. The client manages key generation, handshake (X3DH or similar), and ratcheting. I'll provide an overview and a minimal example of client-side key setup plus the server acting as a message relay.
Below is a practical high-level approach to building an end-to-end encrypted (E2EE) WebSocket chat with Next.js and Prisma, using a Signal-style key exchange and Double Ratchet for message encryption. It covers how to store keys in the database with Prisma, how to do the initial key exchange, and how to encrypt/decrypt messages entirely on the client so the server only relays ciphertext.
Core Concepts
Long-Term Identity Keys
Each user generates a long-term identity key pair (e.g., Ed25519 or Curve25519) on their client.
Private key stays on client.
Public key is uploaded to the server so others can initiate conversations.
Store the public key in a “Users” table in Prisma.
Pre-Keys
For each user, you store one or more pre-keys (one-time keys) and a signed pre-key. These are public keys that can be used to bootstrap the first shared secret with another user.
Generated on the client, then uploaded.
Private components of these keys never leave the client.
Stored in a “PreKeys” table.
Session Setup (Initial Key Agreement)
When User A starts chatting with User B, the client fetches B’s identity key, signed pre-key, and one-time pre-key from the server. A runs an X3DH-style handshake (or a simplified version) to derive a shared secret. This initializes the Double Ratchet state.
Message Sending
The sender uses the Double Ratchet state to derive a message key.
Encrypts the plaintext locally.
Sends ciphertext + metadata (e.g., message counter) over the WebSocket to the server.
The server just relays the encrypted blob to the recipient’s WebSocket connection.
Message Receiving
The recipient’s client receives the ciphertext, looks up the correct Double Ratchet state, and decrypts the message locally.
If a new sender/recipient pair doesn’t yet have an active session, it can kick off the handshake and store the ratchet state for subsequent messages.
Key Storage in Prisma
Users table: Stores identity public keys (no private keys).
PreKeys table: Stores signed pre-keys and one-time pre-keys (public only).
You might also keep track of whether each one-time pre-key has been used, but actual private keys stay on clients.
Messages table: If you want to persist messages, store ciphertext and metadata only (no plaintext).
Example Prisma Schema (simplified)
You can adapt this to your needs, but as an example:
prisma
model User {
id String @id @default(cuid())
username String @unique
identityKey String // base64 or hex of public identity key
signedPreKey String? // base64 or hex of public signed pre-key
preKeys PreKey[]
createdAt DateTime @default(now())
}
model PreKey {
id String @id @default(cuid())
userId String
keyValue String // base64 or hex of public one-time pre-key
used Boolean @default(false)
createdAt DateTime @default(now())
user User @relation(fields: [userId], references: [id])
}
model Message {
id String @id @default(cuid())
senderId String
recipientId String
ciphertext String // encrypted message bytes
// any metadata like ratchet message index if you want
createdAt DateTime @default(now())
}
Client-Side Steps
Key Generation (on registration):
ts
import { generateIdentityKeyPair, generateSignedPreKey, generateOneTimePreKeys } from 'your-crypto-lib';
async function registerUser(username) {
const identityKey = await generateIdentityKeyPair(); // returns { publicKey, privateKey }
const signedPreKey = await generateSignedPreKey(identityKey);
const oneTimePreKeys = await generateOneTimePreKeys(10); // for example
// Upload public bits to server
await fetch('/api/register', {
method: 'POST',
body: JSON.stringify({
username,
identityKey: identityKey.publicKey,
signedPreKey: signedPreKey.publicKey,
preKeys: oneTimePreKeys.map(k => k.publicKey)
})
});
// Store private keys locally (e.g. IndexedDB or local storage with strong protection)
localStorage.setItem('identityPrivateKey', identityKey.privateKey);
localStorage.setItem('signedPreKeyPrivate', signedPreKey.privateKey);
// etc.
}
Session Setup (starting a chat):
ts
import { x3dhHandshake, createDoubleRatchet } from 'your-crypto-lib';
async function initiateSession(myKeys, recipientUsername) {
// Fetch recipient’s identity & pre-keys
const recipient = await fetch(`/api/users/${recipientUsername}`).then(res => res.json());
// x3dhHandshake returns a shared secret or initial Double Ratchet state
const { sharedSecret } = await x3dhHandshake({
myIdentityKeyPair: myKeys.identity,
mySignedPreKeyPair: myKeys.signedPreKey,
myOneTimePreKey: myKeys.oneTimePreKey, // you choose an unused one locally
recipientIdentityKey: recipient.identityKey,
recipientSignedPreKey: recipient.signedPreKey,
recipientOneTimePreKey: recipient.preKey // from server
});
const ratchetState = await createDoubleRatchet(sharedSecret, recipient.identityKey);
// Save the ratchet state in memory or in local storage
// Now you can encrypt messages with ratchetState
return ratchetState;
}
Server-Side (Next.js + WebSocket) Outline
Use a WebSocket server (e.g. ws or Next.js 13+ route handlers that upgrade connections) to listen for chat messages.
When a client sends a message:
The message is already encrypted.
The server just stores the ciphertext in Prisma (if you want persistence) and broadcasts to the recipient’s WebSocket.
For initial key exchange, the server simply serves the identity and pre-keys. If you implement one-time pre-keys, mark them as used when delivered to a client.
Pseudo-code for a simple WebSocket route handler:
ts
// Pseudocode for Next.js route or custom server
const connections = new Map(); // userId -> ws
function broadcastToUser(userId, data) {
const ws = connections.get(userId);
if (ws && ws.readyState === ws.OPEN) {
ws.send(JSON.stringify(data));
}
}
wsServer.on('connection', (ws, request) => {
const userId = authenticateUser(request); // e.g. via cookies/JWT
connections.set(userId, ws);
ws.on('message', async (message) => {
const payload = JSON.parse(message.toString());
// payload might be { recipientId, ciphertext, ... }
const { recipientId, ciphertext } = payload;
// Save to DB if desired
await prisma.message.create({
data: {
senderId: userId,
recipientId,
ciphertext
}
});
// Relay
broadcastToUser(recipientId, { senderId: userId, ciphertext });
});
ws.on('close', () => {
connections.delete(userId);
});
});
Recommended Crypto Libraries
libsignal-protocol-javascript: A reference implementation of Signal Protocol in JavaScript.
If you want to implement Double Ratchet yourself, you’ll need to manage key derivation (HKDF), chain keys, root keys, message keys, etc. It’s more secure to use a battle-tested library if possible.
Summary
The server only stores public identity + pre-keys and relays ciphertext.
All encryption/decryption happens on the client.
Use X3DH for initial key exchange and Double Ratchet for forward secrecy in subsequent messages.
Prisma stores only public keys and encrypted messages. No private keys or plaintext are sent to or stored on the server.
This approach ensures the server never sees the plaintext, and clients manage ratcheting keys locally.