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).
Customized Cloud Solutions to Drive your Business Success
- Cloud Migration
- Devops
- AIML & IoT
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.
Get your new hires billable within 1-60 days. Experience our Capability Development Framework today.
- Cloud Training
- Customized Training
- Experiential Learning
About CloudThat
CloudThat is a leading provider of Cloud Training and Consulting services with a global presence in India, the USA, Asia, Europe, and Africa. Specializing in AWS, Microsoft Azure, GCP, VMware, Databricks, and more, the company serves mid-market and enterprise clients, offering comprehensive expertise in Cloud Migration, Data Platforms, DevOps, IoT, AI/ML, and more.
CloudThat is the first Indian Company to win the prestigious Microsoft Partner 2024 Award and is recognized as a top-tier partner with AWS and Microsoft, including the prestigious ‘Think Big’ partner award from AWS and the Microsoft Superstars FY 2023 award in Asia & India. Having trained 850k+ professionals in 600+ cloud certifications and completed 500+ consulting projects globally, CloudThat is an official AWS Advanced Consulting Partner, Microsoft Gold Partner, AWS Training Partner, AWS Migration Partner, AWS Data and Analytics Partner, AWS DevOps Competency Partner, AWS GenAI Competency Partner, Amazon QuickSight Service Delivery Partner, Amazon EKS Service Delivery Partner, AWS Microsoft Workload Partners, Amazon EC2 Service Delivery Partner, Amazon ECS Service Delivery Partner, AWS Glue Service Delivery Partner, Amazon Redshift Service Delivery Partner, AWS Control Tower Service Delivery Partner, AWS WAF Service Delivery Partner, Amazon CloudFront Service Delivery Partner, Amazon OpenSearch Service Delivery Partner, AWS DMS Service Delivery Partner, AWS Systems Manager Service Delivery Partner, Amazon RDS Service Delivery Partner, AWS CloudFormation Service Delivery Partner, AWS Config, Amazon EMR and many more.
WRITTEN BY Shreya Shah
Comments