To implement real-time progress updates for roadmap creation using WebSockets in your Express backend, you can leverage Socket.io, which simplifies WebSocket integration with Express and provides robust features for handling connections, authentication, and real-time communication.
Below are the steps to achieve this:
- Install Required Dependencies
- Set Up Socket.io with Express
- Create JWT Authentication Middleware for WebSocket Connections
- Modify
createRoadmapFunction to Emit Progress Updates
- Update the Backend Code Accordingly
1. Install Required Dependencies
First, ensure you have the necessary packages installed. You need socket.io for WebSocket communication and express if not already installed.
npm install socket.io
npm install --save-dev @types/socket.io
2. Set Up Socket.io with Express
Integrate Socket.io with your existing Express server.
// server.ts or app.ts
import express from 'express';
import http from 'http';
import { Server } from 'socket.io';
import { jwtAuthMiddlewareSocket } from './middlewares/jwtAuthSocket'; // We'll create this next
import { createRoadmapHandler } from './handlers/createRoadmapHandler'; // We'll create this handler
const app = express();
const server = http.createServer(app);
// Initialize Socket.io server
const io = new Server(server, {
cors: {
origin: "*", // Update this with your frontend URL
methods: ["GET", "POST"],
},
});
// Use JWT middleware for Socket.io
io.use(jwtAuthMiddlewareSocket);
// Handle Socket.io connections
io.on('connection', (socket) => {
console.log(`User connected: ${socket.id}, User ID: ${socket.data.userId}`);
// Listen for 'createRoadmap' event from the client
socket.on('createRoadmap', async (data) => {
try {
await createRoadmapHandler(data.prompt, socket);
} catch (error) {
console.error('Error in createRoadmapHandler:', error);
socket.emit('roadmapError', { message: 'Failed to create roadmap' });
}
});
socket.on('disconnect', () => {
console.log(`User disconnected: ${socket.id}`);
});
});
// Start the server
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
});
3. Create JWT Authentication Middleware for WebSocket Connections
Create a middleware to authenticate and extract userId from JWT tokens for Socket.io connections.
// middlewares/jwtAuthSocket.ts
import { Socket } from 'socket.io';
import jwt from 'jsonwebtoken';
interface JwtPayload {
user: {
id: number;
// other user properties
};
}
export const jwtAuthMiddlewareSocket = (socket: Socket, next: (err?: any) => void) => {
const token = socket.handshake.auth.token || socket.handshake.headers.authorization;
if (!token) {
return next(new Error('Authorization token is missing'));
}
let jwtToken = token;
if (token.startsWith('Bearer ')) {
jwtToken = token.substring(7);
}
try {
const decoded = jwt.verify(jwtToken, process.env.JWT_SECRET || '') as JwtPayload;
socket.data.userId = decoded.user.id;
console.log('Authenticated user ID:', socket.data.userId);
next();
} catch (err) {
console.error('JWT Authentication error:', err);
next(new Error('Authentication error'));
}
};
4. Modify createRoadmapFunction to Emit Progress Updates
Refactor your createRoadmapFunction to accept a socket parameter and emit progress updates at each key step.
// handlers/createRoadmapHandler.ts
import { Socket } from 'socket.io';
import { createRoadmapSchema } from '../schemas/roadmapSchema'; // Assuming you have a Zod schema
import { availaleRoadmapInDB, insertJsonToPrisma, populateFirstRoadmapTopic } from '../services/roadmapService'; // Update with actual paths
import { createRoadmapFunction } from '../services/createRoadmapFunction'; // We'll refactor this next
export const createRoadmapHandler = async (prompt: string, socket: Socket) => {
const userId = socket.data.userId;
// Emit 0%: Starting
socket.emit('roadmapProgress', { progress: 0, message: 'Starting roadmap creation...' });
// Validate input - assuming prompt is the only input
const validationResult = createRoadmapSchema.safeParse({ prompt });
if (!validationResult.success) {
socket.emit('roadmapError', { errors: validationResult.error.errors });
return;
}
try {
const response = await createRoadmapFunction(prompt, userId, socket);
socket.emit('roadmapComplete', response);
socket.disconnect(); // Disconnect after completion
} catch (error) {
console.error('Error creating roadmap:', error);
socket.emit('roadmapError', { message: 'Failed to create roadmap' });
socket.disconnect();
}
};
5. Refactor createRoadmapFunction to Use WebSocket for Progress Updates
Modify createRoadmapFunction to accept the socket and emit progress updates.
// services/createRoadmapFunction.ts
import { Socket } from 'socket.io';
import { PromptTemplate, ChatPromptTemplate, RunnableSequence, StringOutputParser } from 'your-prompt-library'; // Replace with actual imports
import { availaleRoadmapInDB, insertJsonToPrisma, populateFirstRoadmapTopic } from './roadmapService'; // Update with actual paths
import { jsonToMarkdown } from './utils'; // Replace with your actual markdown converter
export const createRoadmapFunction = async (
userQuery: string,
userId: number,
socket: Socket
): Promise<{} | Error> => {
try {
// Emit 10%: Checking existing roadmaps
socket.emit('roadmapProgress', { progress: 10, message: 'Checking existing roadmaps...' });
const isRoadmapAvailable = await availaleRoadmapInDB(userQuery, userId);
if (Object.keys(isRoadmapAvailable).length !== 0) {
// Emit 100%: Complete
socket.emit('roadmapProgress', {
progress: 100,
message: 'Roadmap already exists.',
roadmap: isRoadmapAvailable,
});
return {
message: `Roadmap for ${userQuery} already exists in the database.`,
roadmap: isRoadmapAvailable,
};
}
// Emit 20%: Generating structure
socket.emit('roadmapProgress', { progress: 20, message: 'Generating roadmap structure...' });
const roadmapPrompt = PromptTemplate.fromTemplate(`
Create a comprehensive learning roadmap for mastering {userQuery}. Your task includes topics and subtopics. Respond with a JSON object only, using the following structure:
{{
"topics": [
{{
"name": "Topic Name",
"description": "Brief description of the topic",
"order": 1,
"subtopics": [
{{
"name": "Subtopic Name",
"description": "Brief description of the subtopic",
"order": 1
}}
]
}}
]
}}
// ...rest of the prompt
`);
const chain = roadmapPrompt.pipe(groqModel).pipe(new StringOutputParser());
const response = await chain.invoke({
userQuery: userQuery,
});
// Emit 40%: Converting to markdown
socket.emit('roadmapProgress', { progress: 40, message: 'Converting roadmap to Markdown...' });
const markdown = jsonToMarkdown(JSON.parse(response));
const markdownInfoPrompt = ChatPromptTemplate.fromTemplate(`
Your task is to create a JSON object with two keys: "markdownRoadmap" and "courseInfo". Follow these instructions carefully:
// ...rest of the prompt
`);
const RoadmapInfoPrompt = ChatPromptTemplate.fromTemplate(`
You are an expert course curator. Using the following {markdown} content as a reference, create a clear, descriptive overview of what the course roadmap entails.
// ...rest of the prompt
`);
const RoadmapNamePrompt = ChatPromptTemplate.fromTemplate(`
You are an expert course curator. Based on {userQuery}, generate a compelling and concise name for the roadmap that captures the essence of the course or learning journey.
// ...rest of the prompt
`);
// Emit 60%: Generating course info
socket.emit('roadmapProgress', { progress: 60, message: 'Generating course information...' });
const courseInfoChain = RoadmapInfoPrompt.pipe(groqModel).pipe(new StringOutputParser());
const courseInfoResponse = await courseInfoChain.invoke({
markdown: markdown,
});
// Emit 70%: Generating course name
socket.emit('roadmapProgress', { progress: 70, message: 'Generating course name...' });
const courseNameChain = RoadmapNamePrompt.pipe(groqModel).pipe(new StringOutputParser());
const courseNameResponse = await courseNameChain.invoke({
userQuery: userQuery,
});
// Emit 80%: Saving to database
socket.emit('roadmapProgress', { progress: 80, message: 'Saving roadmap to database...' });
const combinedResponse = {
markdownRoadmap: markdown,
courseInfo: courseInfoResponse,
};
const roadmapId = await insertJsonToPrisma(
JSON.parse(response),
combinedResponse,
userId,
courseNameResponse
);
// Emit 90%: Populating initial content
socket.emit('roadmapProgress', { progress: 90, message: 'Populating initial content...' });
await populateFirstRoadmapTopic(roadmapId);
// Emit 100%: Complete
socket.emit('roadmapProgress', { progress: 100, message: 'Roadmap creation complete!' });
return { message: 'Roadmap Created Successfully' };
} catch (error) {
console.error('An error occurred in roadmapLangChain:', error);
socket.emit('roadmapError', { message: 'An error occurred while creating the roadmap' });
throw new Error('An error occurred while creating the roadmap');
}
};
6. Update Your Existing JWT Middleware if Necessary
Ensure your existing jwtAuth middleware is compatible or redundant with the new WebSocket authentication. Since WebSocket connections are handled separately, you might not need to modify the existing REST API routes unless you want to support both REST and WebSocket for roadmap creation.
7. Frontend Implementation (Overview)
While you didn't request frontend code, here's a brief overview of how you can handle this on the client side using Socket.io:
// frontend.js
import { io } from "socket.io-client";
const socket = io("http://localhost:3000", {
auth: {
token: "Bearer YOUR_JWT_TOKEN",
},
});
// Listen for progress updates
socket.on("roadmapProgress", (data) => {
console.log(`Progress: ${data.progress}% - ${data.message}`);
// Update your UI accordingly
});
// Listen for completion
socket.on("roadmapComplete", (data) => {
console.log("Roadmap creation complete:", data);
// Handle the completed roadmap data
socket.disconnect();
});
// Listen for errors
socket.on("roadmapError", (error) => {
console.error("Roadmap creation error:", error.message);
// Show error message to the user
socket.disconnect();
});
// Trigger roadmap creation
const createRoadmap = (prompt) => {
socket.emit("createRoadmap", { prompt });
};
// Example usage
createRoadmap("Learn TypeScript");
8. Summary
By following the steps above, you have successfully:
- Integrated Socket.io with your Express server.
- Implemented JWT authentication for WebSocket connections, ensuring only authenticated users can initiate roadmap creation.
- Modified the roadmap creation workflow to emit real-time progress updates to the frontend.
- Handled completion and error states by emitting appropriate events and disconnecting the socket when necessary.
This setup will provide a responsive and interactive experience for users, allowing them to see the roadmap creation progress in real-time.
Additional Recommendations
- Error Handling: Ensure all potential errors are caught and appropriately emitted to the client to maintain a robust connection.
- Scalability: For larger applications, consider namespacing or rooms in Socket.io to handle multiple simultaneous roadmap creation processes.
- Security: Always validate and sanitize inputs to prevent injection attacks or other security vulnerabilities.
- Optimization: Depending on the complexity of
createRoadmapFunction, you might want to offload intensive tasks to background workers or use queues (e.g., with Redis and Bull).
Feel free to reach out if you need further assistance or specific code implementations!