DEV Community

Cover image for Build a Secure, Real-Time Chat App in Minutes with React, Clerk, and Stream
Naman Srivastava
Naman Srivastava

Posted on

Build a Secure, Real-Time Chat App in Minutes with React, Clerk, and Stream

πŸš€ Chat Application Setup Guide

A complete guide to set up and run your React chat application using Clerk authentication and Stream Chat.

πŸ“‹ Prerequisites

Before you start, make sure you have:

  • Node.js (version 14 or higher) installed on your computer
  • npm or yarn package manager
  • A code editor (VS Code recommended)
  • Basic knowledge of React

πŸ—οΈ Project Structure

Your project should have the following structure:

my-chat-app/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ App.jsx
β”‚   β”œβ”€β”€ appli.css
β”‚   └── main.jsx
β”œβ”€β”€ .env
β”œβ”€β”€ package.json
└── README.md
Enter fullscreen mode Exit fullscreen mode

πŸ”§ Step 1: Initialize Your React Project

  1. Create a new React project using Vite:
   npm create vite@latest my-chat-app -- --template react
   cd my-chat-app
Enter fullscreen mode Exit fullscreen mode
  1. Install required dependencies:
   npm install @clerk/clerk-react stream-chat stream-chat-react
Enter fullscreen mode Exit fullscreen mode

πŸ”‘ Step 2: Set Up Authentication (Clerk)

Create a Clerk Account

  1. Go to clerk.com and sign up for a free account
  2. Create a new application
  3. Copy your Publishable Key from the Clerk dashboard

Configure Clerk in Your App

  1. Wrap your main App component with ClerkProvider in src/main.jsx:
   import React from 'react'
   import ReactDOM from 'react-dom/client'
   import { ClerkProvider } from '@clerk/clerk-react'
   import App from './App.jsx'

   const CLERK_PUBLISHABLE_KEY = import.meta.env.VITE_CLERK_PUBLISHABLE_KEY

   ReactDOM.createRoot(document.getElementById('root')).render(
     <React.StrictMode>
       <ClerkProvider publishableKey={CLERK_PUBLISHABLE_KEY}>
         <App />
       </ClerkProvider>
     </React.StrictMode>,
   )
Enter fullscreen mode Exit fullscreen mode

πŸ’¬ Step 3: Set Up Chat (Stream)

Create a Stream Account

  1. Go to getstream.io and sign up for a free account
  2. Create a new Chat application
  3. Note down your API Key from the dashboard

Generate User Tokens Manually

Stream requires user tokens for authentication. Since your code already handles two specific users (alice and bob based on email), you'll need to generate tokens for these exact user IDs.

Using Stream's JWT Generator

You can generate a token manually using the JWT generator from Stream's documentation.

  1. Go to Stream's Token Generator:

  2. Generate token for "alice":

    • Enter your Stream Secret Key in the "Your Secret" field
    • Enter alice in the "User ID" field
    • Leave "Set Expiration?" unchecked for tokens that don't expire
    • Click generate to get Alice's token
  3. Generate token for "bob":

    • Keep the same Stream Secret Key
    • Change User ID to bob
    • Click generate to get Bob's token
  4. Copy both tokens - you'll use these in your environment variables

Why These Specific User IDs?

Your React code determines the user based on email:

const isAlice = user.primaryEmailAddress?.emailAddress === "alice@example.com";
const streamUserId = isAlice ? STREAM_USER_ID_ALICE : STREAM_USER_ID_BOB;
Enter fullscreen mode Exit fullscreen mode
  • If the logged-in user's email is alice@example.com, it uses the "alice" user ID
  • For any other email, it uses the "bob" user ID

So you need tokens specifically for:

  • User ID: alice
  • User ID: bob

πŸ” Step 4: Environment Variables

Create a .env file in your project root with the following variables:

VITE_CLERK_PUBLISHABLE_KEY=your_clerk_publishable_key_here
VITE_STREAM_API_KEY=your_stream_api_key_here
VITE_STREAM_USER_ID_ALICE=alice
VITE_STREAM_USER_TOKEN_ALICE=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiYWxpY2UifQ.generated_token_here
VITE_STREAM_USER_ID_BOB=bob
VITE_STREAM_USER_TOKEN_BOB=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiYm9iIn0.generated_token_here
Enter fullscreen mode Exit fullscreen mode

Replace the token values with the ones you generated using your Stream secret key.

⚠️ Important Security Notes:

  • Never commit your .env file to version control
  • Add .env to your .gitignore file
  • Keep your Stream Secret Key secure and never expose it in client-side code
  • The tokens shown above are examples - use your own generated tokens
  • Replace all example values with your actual credentials

πŸ“ Step 5: Add Your Application Files

1. Create src/App.jsx

Copy the React component code provided into this file.

2. Create src/appli.css

Copy the CSS styles provided into this file.

πŸš€ Step 6: Run Your Application

  1. Start the development server:
   npm run dev
Enter fullscreen mode Exit fullscreen mode
  1. Open your browser and navigate to:
   http://localhost:5173
Enter fullscreen mode Exit fullscreen mode

🎯 How It Works

Authentication Flow

  1. Signed Out State: Users see a welcome screen with a "Sign In" button
  2. Sign In Process: Clicking the button opens Clerk's authentication modal
  3. Signed In State: Authenticated users can access the chat interface

Chat System

  1. User Detection: The app determines if the signed-in user is Alice or Bob based on their email
  2. Stream Connection: Connects to Stream Chat using the appropriate user credentials
  3. Real-time Messaging: Users can send and receive messages in real-time

πŸ‘₯ Testing Your App

To test the chat functionality:

  1. Set up test users in Clerk:

    • Create two test accounts with emails: alice@example.com and any other email for Bob
  2. Test the chat:

    • Sign in as Alice in one browser/tab
    • Sign in as Bob in another browser/tab (incognito mode)
    • Start chatting between the two users

πŸ” Troubleshooting

Common Issues and Solutions

1. Environment Variables Not Loading

  • Make sure your .env file is in the project root
  • Restart your development server after adding environment variables
  • Check that variable names start with VITE_

2. Clerk Authentication Not Working

  • Verify your Clerk publishable key is correct
  • Check that ClerkProvider is properly wrapping your App component

3. Stream Chat Connection Issues

  • Ensure your Stream API key is valid
  • Verify user tokens are correctly generated for Alice and Bob
  • Check browser console for connection errors

πŸ” Security Notes

For Production:

  • Never expose user tokens in client-side code
  • Implement server-side token generation
  • Use environment variables for all sensitive data

Current Setup Limitations:

  • This is a development setup with hardcoded user tokens
  • Suitable for learning and testing purposes only
  • Not recommended for production use

πŸ“š Next Steps

Once your basic chat is working, consider:

  1. Improved Authentication:
    • Dynamic user creation
    • Server-side token generation
    • Role-based access control

Happy Chatting! πŸŽ‰

Top comments (0)