Voiced by Amazon Polly |
Overview
Real-time chat is essential for modern customer support. In this tutorial, we will build a live chatbot using React on the frontend and AWS WebSocket API, AWS Lambda, and Amazon DynamoDB on the backend. This solution allows instant messaging and smart auto-responses, escalating to human agents without managing servers when needed. It’s fully serverless, scalable, and production-ready.
We will build a real-time customer support chatbot with React as the frontend and AWS WebSocket API + AWS Lambda + Amazon DynamoDB as the backend.
Instead of a simple echo bot, our chatbot will:
- Respond to user questions using a simple AI engine.
- Escalate to a human support agent if the bot doesn’t understand.
- Show “agent typing” indicators (bonus feature).
Freedom Month Sale — Upgrade Your Skills, Save Big!
- Up to 80% OFF AWS Courses
- Up to 30% OFF Microsoft Certs
Amazon DynamoDB Table Design
Table Name: LiveChatSessions
Partition Key: connectionId (String)
Sort Key (optional): timestamp (for message ordering)
1 2 3 4 5 6 7 8 |
{ "connectionId": "abc123", "userType": "customer", "chat": [ { "sender": "customer", "text": "I need help with my order." }, { "sender": "bot", "text": "Can you please share your order ID?" } ] } |
AWS Lambda Functions
A. $connect Handler
Registers new users in Amazon DynamoDB.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
exports.handler = async (event) => { const connectionId = event.requestContext.connectionId; const userType = event.queryStringParameters?.type || 'customer'; await dynamo.put({ TableName: 'LiveChatSessions', Item: { connectionId, userType, chat: [], timestamp: Date.now() } }).promise(); return { statusCode: 200 }; }; |
B. $disconnect Handler
Removes disconnected users from Amazon DynamoDB.
1 2 3 4 5 6 7 8 9 |
exports.handler = async (event) => { const connectionId = event.requestContext.connectionId; await dynamo.delete({ TableName: 'LiveChatSessions', Key: { connectionId } }).promise(); return { statusCode: 200 }; }; |
C. sendMessage Handler
Handles incoming messages, responds via bot, and escalates if needed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
exports.handler = async (event) => { const { connectionId } = event.requestContext; const body = JSON.parse(event.body); const message = body.message; const botResponse = getBotResponse(message); await sendMessageToClient(connectionId, botResponse); await dynamo.update({ TableName: 'LiveChatSessions', Key: { connectionId }, UpdateExpression: 'SET chat = list_append(chat, :msg)', ExpressionAttributeValues: { ':msg': [{ sender: 'customer', text: message }, { sender: 'bot', text: botResponse }] } }).promise(); return { statusCode: 200 }; }; function getBotResponse(message) { const orderRegex = /order/i; if (orderRegex.test(message)) { return 'Can you please provide your order ID?'; } else { return 'Let me connect you to a human agent.'; } } |
React Frontend (Client)
Install a WebSocket client:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
npm install reconnecting-websocket import React, { useState, useEffect, useRef } from 'react'; import ReconnectingWebSocket from 'reconnecting-websocket'; const ChatBot = () => { const [messages, setMessages] = useState([]); const [input, setInput] = useState(''); const ws = useRef(null); useEffect(() => { ws.current = new ReconnectingWebSocket('wss://your-api-id.execute-api.region.amazonaws.com/production?type=customer'); ws.current.onmessage = (event) => { const { data } = event; setMessages(prev => [...prev, { sender: 'bot', text: data }]); }; return () => ws.current.close(); }, []); const sendMessage = () => { ws.current.send(JSON.stringify({ message: input })); setMessages(prev => [...prev, { sender: 'you', text: input }]); setInput(''); }; return ( <div> <h3>Live Support Chat</h3> <div style={{ border: '1px solid #ccc', padding: 10, height: 200, overflowY: 'scroll' }}> {messages.map((msg, idx) => ( <p key={idx}><strong>{msg.sender}:</strong> {msg.text}</p> ))} </div> <input value={input} onChange={e => setInput(e.target.value)} /> <button onClick={sendMessage}>Send</button> </div> ); }; export default ChatBot; |
Security Considerations
Authentication: Add Amazon Cognito or signed query strings to restrict access.
Rate Limiting: Use AWS WAF or Amazon API Gateway throttling.
Escalation Logic: Set up a secondary WebSocket or Amazon SNS topic for real agents.
Conclusion
Compared to REST APIs, WebSockets offer true two-way communication, making your support experience faster and more engaging. Combined with Amazon DynamoDB for persistent chat history, this architecture is both lightweight and production-ready.
Drop a query if you have any questions regarding AWS WebSockets and we will get back to you quickly.
Freedom Month Sale — Discounts That Set You Free!
- Up to 80% OFF AWS Courses
- Up to 30% OFF Microsoft Certs
About CloudThat
CloudThat is an award-winning company and the first in India to offer cloud training and consulting services worldwide. As a Microsoft Solutions Partner, AWS Advanced Tier Training Partner, and Google Cloud Platform Partner, CloudThat has empowered over 850,000 professionals through 600+ cloud certifications winning global recognition for its training excellence including 20 MCT Trainers in Microsoft’s Global Top 100 and an impressive 12 awards in the last 8 years. CloudThat specializes in Cloud Migration, Data Platforms, DevOps, IoT, and cutting-edge technologies like Gen AI & AI/ML. It has delivered over 500 consulting projects for 250+ organizations in 30+ countries as it continues to empower professionals and enterprises to thrive in the digital-first world.
WRITTEN BY Shreya Shah
Comments