Featured resource
2025 Tech Upskilling Playbook
Tech Upskilling Playbook

Build future-ready tech teams and hit key business milestones with seven proven plays from industry leaders.

Check it out
  • Lab
    • Libraries: If you want this lab, consider one of these libraries.
Labs

Guided: Real-Time Chat with WebSockets in Full-stack Java with Play Framework and React

In this Code Lab, you'll build a real-time chat application using the Play Framework for the backend and React for the frontend. You'll learn how to handle WebSocket connections, manage state with actors, and create a dynamic user interface that updates instantly.

Lab platform
Lab Info
Level
Beginner
Last updated
Sep 25, 2025
Duration
45m

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.
Table of Contents
  1. Challenge

    Step 1: Introduction and Setup

    Welcome to the React + Play Framework Chat Application lab! In this comprehensive lab, you'll build a real-time chat application using modern full-stack technologies.

    The Application

    You will implement:

    • Backend: Actor-based chat rooms using Play Framework and Pekko Actors
    • Authentication: JWT token-based security system
    • REST API: Endpoints for rooms and message history
    • Real-time Communication: WebSocket connections with automatic reconnection
    • Frontend: React application with modern hooks and state management
    • UI Components: Interactive chat interface with room management

    Technology Stack

    • Backend: Java 21, Play Framework v3.0.9, Pekko Actors, JWT
    • Frontend: TypeScript, React 19, Zustand, Emotion (CSS-in-JS)
    • Communication: WebSocket, REST API, JSON
    • Testing: JUnit (backend), Vitest (frontend)

    File Structure

    The project is organized into:

    • backend/: Play Framework application with actors, controllers, and services
    • frontend/: React application with components, services, and state management
    • solutions/: Reference implementations for each task
  2. Challenge

    Step 2: Actor-Based Chat Room Management

    The foundation of our chat application is the Actor model, which provides excellent concurrency and fault tolerance for handling multiple users and chat rooms simultaneously.

    Pekko Actors (formerly Akka) use message passing to handle concurrent operations safely. Each ChatRoomActor manages:

    • User connections per room
    • Message broadcasting
    • Join/leave notifications
    • State isolation between rooms

    The Actor model eliminates traditional concurrency issues like race conditions and deadlocks by processing messages sequentially within each actor instance.

    You'll start by implementing the core functionality for users joining chat rooms. Next, implement the complementary functionality for users leaving chat rooms. Proper cleanup is crucial in actor systems to prevent memory leaks and ensure accurate state management.

    The leave functionality must:

    • Remove disconnected clients
    • Clean up user mappings
    • Notify remaining participants
    • Handle edge cases gracefully
  3. Challenge

    Step 3: JWT Authentication System

    Modern web applications require secure, stateless authentication. JSON Web Tokens (JWT) provide an ideal solution for our chat application.

    JWT Benefits:

    • Stateless: No server-side session storage required
    • Scalable: Works across multiple server instances
    • Secure: Cryptographically signed tokens
    • Flexible: Can include custom claims (like userId)

    Our authentication system will generate tokens upon login and verify them for protected endpoints and WebSocket connections.

    First, implement token generation for successful logins. Token verification is equally important - it ensures only authenticated users can access protected resources. The verification process must:

    • Validate the token signature
    • Check expiration times
    • Extract user information
    • Handle invalid tokens gracefully

    This creates a complete authentication cycle for secure access control.

  4. Challenge

    Step 4: REST API Endpoints

    The REST API provides the bridge between our frontend and backend, providing structured access to chat rooms and message history.

    RESTful Design Principles:

    • Clear, predictable URLs
    • Appropriate HTTP methods
    • Consistent JSON responses
    • Proper status codes
    • Authentication protection

    Our API will serve two main purposes:

    1. Provide available chat rooms
    2. Retrieve message history for rooms

    Start by implementing the rooms listing endpoint. Message history is essential for users joining existing conversations. When users enter a room, they should see recent messages to understand the context.

    The messages endpoint must:

    • Handle room-specific queries
    • Return properly formatted message data
    • Include all message metadata (timestamps, user info, etc.)
    • Handle non-existent rooms gracefully
  5. Challenge

    Step 5: WebSocket Real-time Communication

    Real-time communication is the heart of any chat application. WebSockets provide full-duplex communication between the browser and server, enabling instant message delivery.

    WebSocket Features:

    • Bidirectional: Both client and server can initiate communication
    • Low Latency: No HTTP request/response overhead
    • Persistent: Connection stays open for the session
    • Efficient: Minimal protocol overhead

    Connection Management:

    • Heartbeat (ping/pong) to detect disconnections
    • Automatic reconnection with exponential backoff
    • Graceful error handling
    • Message queuing during disconnections

    Start by implementing message handling with ping/pong heartbeat functionality. Network connections can be unreliable, especially on mobile devices. Implementing smart reconnection logic ensures users stay connected to their conversations.

    Reconnection Strategy:

    • Exponential backoff prevents server overload
    • Maximum attempt limits avoid infinite loops
    • Connection state tracking
    • User feedback during reconnection

    This creates a robust communication layer that handles real-world network conditions.

  6. Challenge

    Step 6: Frontend State Management

    Modern React applications require efficient state management for complex user interactions. Zustand provides a lightweight, TypeScript-friendly solution.

    State Management Benefits:

    • Centralized: Single source of truth for authentication
    • Reactive: Components automatically update when state changes
    • Type-Safe: Full TypeScript support
    • Simple: Minimal boilerplate compared to Redux

    Authentication State:

    • Login status and user information
    • JWT token storage and management
    • Automatic persistence across sessions
    • Error handling and user feedback

    Implement the login functionality first.

    warning> Note: Follow the tasks in this step sequentially. Each task builds on the previous one, so be sure to complete Task 1 before moving on to Task 2. User registration should provide a seamless experience by automatically logging users in after successful account creation.

    Registration Flow:

    1. Validate user input
    2. Create account via API
    3. Automatically log in the new user
    4. Update application state
    5. Redirect to chat interface

    This eliminates the extra step of manual login after registration.

  7. Challenge

    Step 7: Interactive Chat Interface

    The chat interface is where users spend most of their time. It must be intuitive, responsive, and handle real-time interactions smoothly.

    Chat Component Features:

    • Message Input: Text input with validation and submission
    • Real-time Display: Live message updates via WebSocket
    • Room Management: Create and switch between chat rooms
    • User Experience: Keyboard shortcuts, auto-focus, visual feedback

    Input Handling:

    • Trim whitespace from messages
    • Validate non-empty content
    • Clear input after sending
    • Maintain focus for continuous typing

    Start with implementing the message sending functionality. Room creation allows users to start new conversations on different topics. This feature completes the core chat functionality.

    Room Creation Features:

    • Input validation for room names
    • API integration for persistence
    • Real-time UI updates
    • Error handling and user feedback
    • Automatic room list refresh

    With this final feature, users can create rooms, join conversations, and chat in real-time!

About the author

Real skill practice before real-world application

Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.

Learn by doing

Engage hands-on with the tools and technologies you’re learning. You pick the skill, we provide the credentials and environment.

Follow your guide

All labs have detailed instructions and objectives, guiding you through the learning process and ensuring you understand every step.

Turn time into mastery

On average, you retain 75% more of your learning if you take time to practice. Hands-on labs set you up for success to make those skills stick.

Get started with Pluralsight