Build a WebSocket-based chat application with end-to-end encryption using Next.js and…
- User
Build a WebSocket-based chat application with end-to-end encryption using Next.js and Prisma.
Assistant
Build a WebSocket-based chat application with end-to-end encryption using Next.js and Prisma.
The user wants a WebSocket-based chat application with end-to-end encryption using Next.js and Prisma. This is a complex request that involves several technologies and security considerations.
1. Core Technologies:
ws library, but Next.js API routes are serverless by default on Vercel, which makes persistent WebSocket connections tricky. I need to address this. Custom server or a serverless-friendly WebSocket solution? For a "build an app" tutorial, a Custom Server is usually the standard way to handle WebSockets in Next.js, although for production on Vercel, one might use Pusher or Ably. I'll stick to a custom server setup or a separate socket server for clarity, but since the prompt asks for "Next.js", integrating it via a custom server or a separate Node process is necessary. Self-correction: Using server components and API routes isn't enough for WebSockets. I should probably set up a separate simple Node.js server for the WebSocket part to keep it compatible with standard Next.js hosting or explain the Custom Server route. Let's go with a Custom Server approach as it's a self-contained solution for a tutorial, or a separate socket server.2. Architecture & Data Flow:
{ encryptedMessage, encryptedKey }.3. Simplification for the Tutorial: Implementing full Signal Protocol style ratcheting is too complex for a single code block. I will implement a simpler version of E2EE:
4. Project Structure:
prisma/schema.prisma: User, Message models.server.js: Custom Next.js server with Socket.io.pages/index.js: Chat UI.lib/crypto.js: Utility functions for encryption/decryption.pages/api/auth/[...nextauth].js: Authentication.pages/api/chat/keys.js: Endpoint to exchange public keys.5. Drafting the Code (Mental or Scratchpad):
Prisma Schema:
WebSocket Logic:
connection: Join a room based on User ID.send_message: Save to DB -> Emit to recipient room.Crypto Logic:
generateKeyPair(): window.crypto.subtle.generateKeyexportPublicKey(): window.crypto.subtle.exportKey("spki")encryptMessage(message, receiverPublicKey): Generate AES key -> Encrypt msg -> Wrap AES key with RSA -> Return bundle.decryptMessage(bundle, privateKey): Unwrap AES key -> Decrypt msg.6. Refining the "Next.js + WebSocket" issue:
Deploying a WebSocket server alongside Next.js on Vercel is impossible without external services (like Pusher). For a standalone code example, using a server.js file is the correct approach. I will explicitly mention this limitation.
7. Step-by-Step Plan:
8. Code Constraints & Details:
Let's write the code.
Self-Correction during drafting: Should I store messages in the DB? Yes, but since they are E2EE, the DB stores gibberish. When the user loads the app, they fetch history and decrypt it client-side.
Code Structure:
package.json scripts need updating for server.js.prisma/schema.prismalib/crypto.js (Client-side mostly, maybe server-side util for nothing since server shouldn't touch crypto).pages/api/user/pubkey.js (GET/POST).server.js (Socket.io integration).pages/index.js (Main app).Let's refine the server.js part. It needs to merge with the Next.js request handler.
Let's refine the crypto.js part. It needs to be robust.
Function encrypt:
Function decrypt:
Okay, ready to generate the response. I will structure it clearly with file names and instructions. I will use SQLite for simplicity in the Prisma setup to make it runnable immediately. This is a sophisticated project that combines real-time communication (WebSockets), modern web framework architecture (Next.js), data persistence (Prisma), and advanced security (End-to-End Encryption).
You will need Node.js installed.
Create the Next.js app and install dependencies.
npx create-next-app@latest secure-chat --typescript --eslint
cd secure-chat
npm install prisma @prisma/client next-auth socket.io socket.io-client
npm install tailwindcss postcss autoprefixer (optional, for styling)
Initialize Prisma and define your schema.
npx prisma init
Open prisma/schema.prisma and add your models.
// prisma/schema.prisma
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "sqlite" // Use "postgresql" for production
url = env("DATABASE_URL")
}
model User {
id String @id @default(cuid())
name String?
email String? @unique
emailVerified DateTime?
image String?
publicKey String? // Stores the RSA Public Key (Spki format)
accounts Account[]
sessions Session[]
sentMessages Message[] @relation("SentMessages")
receivedMessages Message[] @relation("ReceivedMessages")
}
model Account {
id String @id @default(cuid())
userId String
type String
provider String
providerAccountId String
refresh_token String?
access_token String?
expires_at Int?
token_type String?
scope String?
id_token String?
session_state String?
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@unique([provider, providerAccountId])
}
model Session {
id String @id @default(cuid())
sessionToken String @unique
userId String
expires DateTime
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
}
model VerificationToken {
identifier String
token String @unique
expires DateTime
@@unique([identifier, token])
}
model Message {
id String @id @default(cuid())
content String // Encrypted Base64 string
iv String // Initialization Vector for AES
senderId String
receiverId String
createdAt DateTime @default(now())
sender User @relation("SentMessages", fields: [senderId], references: [id])
receiver User @relation("ReceivedMessages", fields: [receiverId], references: [id])
}
Run the migration:
npx prisma migrate dev --name init
npx prisma generate
Since Vercel (standard Next.js hosting) is serverless and doesn't support persistent WebSocket connections, we need a custom server.
Create server.js in the root:
// server.js
const { createServer } = require('http');
const { parse } = require('url');
const next = require('next');
const { Server } = require('socket.io');
const dev = process.env.NODE_ENV !== 'production';
const hostname = 'localhost';
const port = 3000;
const app = next({ dev, hostname, port });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const httpServer = createServer(async (req, res) => {
try {
const parsedUrl = parse(req.url, true);
await handle(req, res, parsedUrl);
} catch (err) {
console.error('Error occurred handling', req.url, err);
res.statusCode = 500;
res.end('internal server error');
}
});
const io = new Server(httpServer, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST"]
}
});
io.on('connection', (socket) => {
console.log('a user connected:', socket.id);
// Join a specific room named after the user's ID (passed from client)
socket.on('join', (userId) => {
socket.join(userId);
console.log(`User ${userId} joined their room`);
});
// Handle sending messages
socket.on('send_message', async (data) => {
// data contains: { receiverId, encryptedContent, iv, senderId }
// 1. Save to Database (Pseudo-code, better to use an API call inside the component,
// but here we illustrate server-side logic)
// In a real app, you might validate the session here.
console.log(`Message from ${data.senderId} to ${data.receiverId}`);
// 2. Emit to the specific receiver
io.to(data.receiverId).emit('receive_message', {
senderId: data.senderId,
content: data.encryptedContent,
iv: data.iv,
createdAt: new Date()
});
});
});
httpServer.listen(port, (err) => {
if (err) throw err;
console.log(`> Ready on http://${hostname}:${port}`);
});
});
Update package.json scripts:
"scripts": {
"dev": "node server.js",
"build": "next build",
"start": "NODE_ENV=production node server.js"
}
This is the core of the E2EE. We use the browser's window.crypto.subtle API.
Create utils/crypto.js:
// utils/crypto.js
// Helper to convert ArrayBuffer to Base64
const arrayBufferToBase64 = (buffer) => {
return btoa(String.fromCharCode(...new Uint8Array(buffer)));
};
// Helper to convert Base64 to ArrayBuffer
const base64ToArrayBuffer = (base64) => {
const binaryString = atob(base64);
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes.buffer;
};
export const generateKeyPair = async () => {
const keyPair = await window.crypto.subtle.generateKey(
{
name: "RSA-OAEP",
modulusLength: 2048,
publicExponent: new Uint8Array([1, 0, 1]),
hash: "SHA-256",
},
true,
["encrypt", "decrypt"]
);
// Export keys to store/share
const publicKey = await window.crypto.subtle.exportKey("spki", keyPair.publicKey);
const privateKey = await window.crypto.subtle.exportKey("pkcs8", keyPair.privateKey);
return {
publicKey: arrayBufferToBase64(publicKey),
privateKey: arrayBufferToBase64(privateKey),
};
};
export const importPublicKey = async (keyBase64) => {
return await window.crypto.subtle.importKey(
"spki",
base64ToArrayBuffer(keyBase64),
{ name: "RSA-OAEP", hash: "SHA-256" },
true,
["encrypt"]
);
};
export const importPrivateKey = async (keyBase64) => {
return await window.crypto.subtle.importKey(
"pkcs8",
base64ToArrayBuffer(keyBase64),
{ name: "RSA-OAEP", hash: "SHA-256" },
true,
["decrypt"]
);
};
// Generates a random AES key for the message session
const generateAesKey = async () => {
return await window.crypto.subtle.generateKey(
{ name: "AES-GCM", length: 256 },
true,
["encrypt", "decrypt"]
);
};
// Encrypts the message using AES, then encrypts the AES key with Receiver's RSA
export const encryptMessage = async (message, receiverPublicKeyBase64) => {
const encoder = new TextEncoder();
const data = encoder.encode(message);
// 1. Generate symmetric AES key for this specific message
const aesKey = await generateAesKey();
// 2. Encrypt the message with AES
const iv = window.crypto.getRandomValues(new Uint8Array(12));
const encryptedContent = await window.crypto.subtle.encrypt(
{ name: "AES-GCM", iv },
aesKey,
data
);
// 3. Encrypt the AES key with Receiver's RSA Public Key
const receiverPublicKey = await importPublicKey(receiverPublicKeyBase64);
const exportedAesKey = await window.crypto.subtle.exportKey("raw", aesKey);
const encryptedAesKey = await window.crypto.subtle.encrypt(
{ name: "RSA-OAEP" },
receiverPublicKey,
exportedAesKey
);
return {
content: arrayBufferToBase64(encryptedContent),
iv: arrayBufferToBase64(iv),
key: arrayBufferToBase64(encryptedAesKey), // Send this so receiver can read it
};
};
export const decryptMessage = async (encryptedPackage, privateKeyBase64) => {
const { content, iv, key } = encryptedPackage;
const privateKey = await importPrivateKey(privateKeyBase64);
// 1. Decrypt the AES key using our Private Key
const decryptedAesKeyBuffer = await window.crypto.subtle.decrypt(
{ name: "RSA-OAEP" },
privateKey,
base64ToArrayBuffer(key)
);
// Import the raw AES key
const aesKey = await window.crypto.subtle.importKey(
"raw",
decryptedAesKeyBuffer,
{ name: "AES-GCM" },
true,
["decrypt"]
);
// 2. Decrypt the message content using the AES key
const decryptedContent = await window.crypto.subtle.decrypt(
{ name: "AES-GCM", iv: base64ToArrayBuffer(iv) },
aesKey,
base64ToArrayBuffer(content)
);
const decoder = new TextDecoder();
return decoder.decode(decryptedContent);
};
We need an endpoint to upload our public key and get others' public keys.
Create pages/api/user/keys.js:
// pages/api/user/keys.js
import { getServerSession } from "next-auth/next"
import { authOptions } from "../auth/[...nextauth]" // Assuming standard NextAuth setup
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
export default async function handler(req, res) {
const session = await getServerSession(req, res, authOptions);
if (!session) {
return res.status(401).json({ error: "Unauthorized" });
}
const currentUserEmail = session.user.email;
if (req.method === 'POST') {
// Upload Public Key
const { publicKey } = req.body;
try {
await prisma.user.update({
where: { email: currentUserEmail },
data: { publicKey },
});
res.status(200).json({ message: "Key uploaded" });
} catch (error) {
res.status(500).json({ error: "Failed to save key" });
}
}
else if (req.method === 'GET') {
// Get Public Key of a user
const { email } = req.query;
try {
const user = await prisma.user.findUnique({
where: { email },
select: { publicKey: true },
});
if (user && user.publicKey) {
res.status(200).json({ publicKey: user.publicKey });
} else {
res.status(404).json({ error: "User or Key not found" });
}
} catch (error) {
res.status(500).json({ error: "Failed to fetch key" });
}
}
}
We will create a simple page that handles key generation, storage in LocalStorage (for demo purposes; in production use secure storage), and socket communication.
Create pages/chat.js (or modify pages/index.js):
// pages/chat.js
import React, { useEffect, useState, useRef } from 'react';
import io from 'socket.io-client';
import { generateKeyPair, encryptMessage, decryptMessage } from '../utils/crypto';
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/router';
let socket;
export default function Chat() {
const { data: session, status } = useSession();
const [messages, setMessages] = useState([]);
const [input, setInput] = useState('');
const [receiverEmail, setReceiverEmail] = useState(''); // In real app, select from list
const [myKeys, setMyKeys] = useState({ private: null, public: null });
const router = useRouter();
useEffect(() => {
if (status === 'unauthenticated') {
router.push('/api/auth/signin');
}
}, [status, router]);
useEffect(() => {
// 1. Initialize Keys
const initKeys = async () => {
const storedPriv = localStorage.getItem('privateKey');
const storedPub = localStorage.getItem('publicKey');
if (!storedPriv || !storedPub) {
const keys = await generateKeyPair();
localStorage.setItem('privateKey', keys.privateKey);
localStorage.setItem('publicKey', keys.publicKey);
setMyKeys({ private: keys.privateKey, public: keys.publicKey });
// Upload Public Key to Server
await fetch('/api/user/keys', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ publicKey: keys.publicKey }),
});
} else {
setMyKeys({ private: storedPriv, public: storedPub });
// Ensure server has key (optional update)
await fetch('/api/user/keys', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ publicKey: storedPub }),
});
}
};
if (session?.user) initKeys();
// 2. Initialize Socket
socket = io('http://localhost:3000');
socket.on('connect', () => {
console.log('Socket connected');
// Identify ourselves to the socket server so it can map socket.id to user.id
// In real app, use session.user.id
socket.emit('join', session?.user?.id || 'anonymous');
});
socket.on('receive_message', async (data) => {
// Decrypt incoming message
try {
// We need the private key to decrypt
const privKey = localStorage.getItem('privateKey');
if (!privKey) return;
// Note: data.encryptedKey needs to be sent by the sender.
// Simplification: In this UI logic, we are constructing the package manually in 'send'
const decryptedText = await decryptMessage({
content: data.content,
iv: data.iv,
key: data.key // The encrypted AES key
}, privKey);
setMessages((prev) => [...prev, { text: decryptedText, sender: 'them', id: data.senderId }]);
} catch (err) {
console.error("Decryption failed", err);
}
});
return () => {
socket?.disconnect();
};
}, [session]);
const sendMessage = async () => {
if (!input || !receiverEmail) return;
try {
// 1. Get Receiver's Public Key
const res = await fetch(`/api/user/keys?email=${receiverEmail}`);
const { publicKey } = await res.json();
if (!publicKey) {
alert("Receiver Public Key not found!");
return;
}
// 2. Encrypt Message
const encryptedPackage = await encryptMessage(input, publicKey);
// 3. Send via Socket
const payload = {
receiverId: receiverEmail, // Simplification: using email as ID
senderId: session.user.id,
content: encryptedPackage.content,
iv: encryptedPackage.iv,
key: encryptedPackage.key // The encrypted symmetric key
};
socket.emit('send_message', payload);
setMessages((prev) => [...prev, { text: input, sender: 'me' }]);
setInput('');
// Optional: Save to DB via API here
} catch (err) {
console.error(err);
}
};
if (status === "loading") return <div>Loading...</div>;
return (
<div className="flex flex-col h-screen p-4">
<div className="mb-4 p-4 border-b">
<input
type="text"
placeholder="Receiver Email (e.g., bob@test.com)"
value={receiverEmail}
onChange={(e) => setReceiverEmail(e.target.value)}
className="border p-2 mr-2 text-black"
/>
</div>
<div className="flex-1 overflow-y-auto border p-4 mb-4 bg-gray-50">
{messages.map((msg, idx) => (
<div key={idx} className={`my-2 p-2 rounded ${msg.sender === 'me' ? 'bg-blue-200 ml-auto w-1/2' : 'bg-gray-200 mr-auto w-1/2'}`}>
{msg.text}
</div>
))}
</div>
<div className="flex">
<input
type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
className="flex-1 border p-2 mr-2 text-black"
placeholder="Type a secure message..."
/>
<button onClick={sendMessage} className="bg-blue-500 text-white p-2 rounded">Send</button>
</div>
</div>
);
}
pages/api/auth/[...nextauth].js with a simple credential or email provider..env has DATABASE_URL.npx prisma migrate dev
npm run dev
localStorage. This is vulnerable to XSS attacks. In a production high-security app, consider:
{ content, iv, key } object to a REST API.socket.emit('join', userId) logic is secured. Typically, you send the JWT token in the auth object during socket initialization and verify it in the server middleware.