A real-time chat application built with Next.js and native WebSocket that allows multiple clients to chat with each other in real-time.
- Real-time messaging using native WebSocket API
- User join/leave notifications
- Clean and modern UI with Tailwind CSS
- Responsive design
- Connection status indicator
- Message timestamps
- Node.js (version 14 or higher)
- npm or yarn
- Clone the repository or navigate to the project directory
- Install dependencies:
npm install
-
Start the development server:
npm run dev
-
Open your browser and navigate to
http://localhost:3000 -
Enter a username to join the chat
-
Start chatting! You can open multiple browser tabs/windows to simulate multiple users
- Join the Chat: Enter your username on the login screen and click "Join Chat"
- Send Messages: Type your message in the input field and press Enter or click "Send"
- Real-time Updates: Messages from other users will appear in real-time
- User Notifications: You'll see when other users join or leave the chat
- Connection Status: The connection indicator shows if you're connected to the server
- Frontend: Next.js 15 with React 19
- Styling: Tailwind CSS
- WebSocket: Native WebSocket API with
wslibrary on server - Server: Custom Node.js server with separate WebSocket server
challenge-web-sockets/
├── server.js # Custom server with WebSocket support
├── src/
│ ├── app/
│ │ ├── page.tsx # Main application page
│ │ └── layout.tsx # App layout
│ └── components/
│ ├── Chat.tsx # Chat component with WebSocket logic
│ └── Login.tsx # Login component
└── package.json
The Chat.tsx component contains a WebSocket implementation challenge. The component needs to be completed to handle real-time communication with the server.
In the useEffect hook in src/components/Chat.tsx, you need to implement the following WebSocket functionality:
-
Create WebSocket Connection:
-
Handle WebSocket Events:
onopen: Set connection status and send join messageonclose: Update connection statusonerror: Handle connection errorsonmessage: Parse incoming messages and update chat
-
Incoming Message Types to Handle:
message: Regular chat messages from usersuserJoined: System announcement when user joinsuserLeft: System announcement when user leaves
-
Send Messages:
- Join message when connecting
- Chat messages when user sends
The WebSocket server runs on ws://localhost:3001, implementation can be found in server.js
The application uses a custom server (server.js) with two separate servers:
- Port 3000: Next.js server for HTTP requests
- Port 3001: WebSocket server for real-time communication
This separation prevents conflicts with Next.js's own WebSocket connections for Hot Module Replacement.
To run in production:
npm run build
npm start