How to Build AI Chat Interfaces in React with a .NET Backend

Meta Description: Learn how to build an AI chat interface in React with a .NET backend. Step-by-step guide with code examples, best practices, and real-time integration tips....

By · · Updated · 7 min read · intermediate


Meta Description: Learn how to build an AI chat interface in React with a .NET backend. Step-by-step guide with code examples, best practices, and real-time integration tips.


Introduction

AI-powered chat interfaces are transforming how users interact with applications. Whether you're building a customer support chatbot, a virtual assistant, or a real-time messaging app, combining React for the frontend and .NET for the backend provides a robust and scalable solution.

In this guide, you'll learn how to:

  • Set up a .NET backend with AI integration.
  • Build a React frontend for a seamless chat experience.
  • Connect the two using REST APIs or SignalR for real-time communication.
  • Deploy your application for production use.

Let’s dive in!


Prerequisites

Before you start, ensure you have the following tools and knowledge:

Tools and Technologies

  • Node.js and npm: For managing React dependencies.
  • .NET SDK: For building the backend (version 6.0 or later recommended).
  • Visual Studio or VS Code: For writing and debugging code.
  • Postman or Insomnia: For testing API endpoints.
  • Azure AI or OpenAI API Key: For AI capabilities (optional but recommended).

Knowledge Requirements

  • Basic understanding of C# and .NET Web API.
  • Familiarity with React and JavaScript/TypeScript.
  • Experience with REST APIs and SignalR (optional but helpful).

Setting Up the .NET Backend

Step 1: Create a .NET Web API Project

  1. Open a terminal and run the following command to create a new .NET Web API project:

    dotnet new webapi -n AIChatBackend
    cd AIChatBackend
    
  2. Open the project in Visual Studio or VS Code.

  3. Remove the default WeatherForecast controller and model, as they won’t be needed.


Step 2: Integrate AI Services

To add AI capabilities, you can use Azure AI or OpenAI. For this guide, we'll use OpenAI.

  1. Install the OpenAI NuGet package:

    dotnet add package OpenAI
    
  2. Add your OpenAI API key to appsettings.json:

    {
      "OpenAI": {
        "ApiKey": "your-api-key-here"
      }
    }
    
  3. Create a service to interact with OpenAI:

    // Services/OpenAIService.cs
    using OpenAI_API;
    
    public class OpenAIService
    {
        private readonly OpenAIAPI _openAI;
    
        public OpenAIService(IConfiguration configuration)
        {
            _openAI = new OpenAIAPI(configuration["OpenAI:ApiKey"]);
        }
    
        public async Task<string> GetAIResponse(string prompt)
        {
            var result = await _openAI.Completions.GetCompletion(prompt);
            return result;
        }
    }
    
  4. Register the service in Program.cs:

    builder.Services.AddSingleton<OpenAIService>();
    

Step 3: Set Up SignalR for Real-Time Communication

SignalR enables real-time communication between the frontend and backend.

  1. Install the SignalR package:

    dotnet add package Microsoft.AspNetCore.SignalR
    
  2. Create a Hub for chat messages:

    // Hubs/ChatHub.cs
    using Microsoft.AspNetCore.SignalR;
    
    public class ChatHub : Hub
    {
        public async Task SendMessage(string user, string message)
        {
            await Clients.All.SendAsync("ReceiveMessage", user, message);
        }
    }
    
  3. Register SignalR in Program.cs:

    builder.Services.AddSignalR();
    app.MapHub<ChatHub>("/chatHub");
    
  4. Create a controller to handle chat messages:

    // Controllers/ChatController.cs
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.SignalR;
    
    [ApiController]
    [Route("api/[controller]")]
    public class ChatController : ControllerBase
    {
        private readonly OpenAIService _openAIService;
        private readonly IHubContext<ChatHub> _hubContext;
    
        public ChatController(OpenAIService openAIService, IHubContext<ChatHub> hubContext)
        {
            _openAIService = openAIService;
            _hubContext = hubContext;
        }
    
        [HttpPost("send")]
        public async Task<IActionResult> SendMessage([FromBody] ChatMessage message)
        {
            var aiResponse = await _openAIService.GetAIResponse(message.Text);
            await _hubContext.Clients.All.SendAsync("ReceiveMessage", "AI", aiResponse);
            return Ok();
        }
    }
    
    public class ChatMessage
    {
        public string Text { get; set; }
    }
    

Building the React Frontend

Step 1: Set Up a React Project

  1. Create a new React project using Create React App:

    npx create-react-app ai-chat-frontend --template typescript
    cd ai-chat-frontend
    
  2. Install required dependencies:

    npm install @microsoft/signalr axios
    

Step 2: Create Chat UI Components

  1. Create a Chat component:

    // src/components/Chat.tsx
    import React, { useState, useEffect } from "react";
    import { HubConnectionBuilder } from "@microsoft/signalr";
    
    const Chat = () => {
        const [messages, setMessages] = useState<{ user: string; text: string }[]>([]);
        const [input, setInput] = useState("");
        const [connection, setConnection] = useState<any>(null);
    
        useEffect(() => {
            const newConnection = new HubConnectionBuilder()
                .withUrl("https://localhost:5001/chatHub")
                .withAutomaticReconnect()
                .build();
    
            setConnection(newConnection);
        }, []);
    
        useEffect(() => {
            if (connection) {
                connection.start()
                    .then(() => {
                        connection.on("ReceiveMessage", (user: string, text: string) => {
                            setMessages((prev) => [...prev, { user, text }]);
                        });
                    })
                    .catch((err: any) => console.error(err));
            }
        }, [connection]);
    
        const sendMessage = async () => {
            if (input.trim() === "") return;
            await connection.invoke("SendMessage", "User", input);
            setInput("");
        };
    
        return (
            <div>
                <div className="chat-messages">
                    {messages.map((msg, index) => (
                        <div key={index}>
                            <strong>{msg.user}:</strong> {msg.text}
                        </div>
                    ))}
                </div>
                <input
                    type="text"
                    value={input}
                    onChange={(e) => setInput(e.target.value)}
                    onKeyPress={(e) => e.key === "Enter" && sendMessage()}
                />
                <button onClick={sendMessage}>Send</button>
            </div>
        );
    };
    
    export default Chat;
    
  2. Add the Chat component to your App.tsx:

    // src/App.tsx
    import React from "react";
    import Chat from "./components/Chat";
    
    function App() {
        return (
            <div className="App">
                <h1>AI Chat Interface</h1>
                <Chat />
            </div>
        );
    }
    
    export default App;
    

Step 3: Connect to the .NET Backend

  1. Use Axios to send messages to the backend:

    // src/components/Chat.tsx
    import axios from "axios";
    
    const sendMessage = async () => {
        if (input.trim() === "") return;
        await axios.post("https://localhost:5001/api/chat/send", { text: input });
        setInput("");
    };
    
  2. Run the React app:

    npm start
    

Integrating AI into the Chat Interface

Step 1: Send User Messages to the AI Service

The .NET backend already handles sending user messages to the AI service via the ChatController. The AI response is then broadcasted to all clients using SignalR.

Step 2: Display AI Responses in the Chat

The Chat component in React listens for messages from the ChatHub and displays them in real-time. The AI responses are automatically appended to the chat interface.


Testing and Debugging

Testing the Backend

  1. Use Postman or Insomnia to test the /api/chat/send endpoint.
  2. Send a POST request with a JSON body:
    {
        "text": "Hello, AI!"
    }
    
  3. Verify that the AI response is returned.

Testing the Frontend

  1. Open the React app in a browser.
  2. Type a message and press Enter or click Send.
  3. Verify that the AI response appears in the chat.

Debugging Tips

  • Backend: Check the console for errors in the .NET application.
  • Frontend: Use the React Developer Tools and browser console to debug issues.
  • SignalR: Ensure the connection is established by checking the network tab in the browser's developer tools.

Deployment

Deploying the .NET Backend

  1. Publish the .NET application to Azure App Service or AWS Elastic Beanstalk:
    dotnet publish -c Release -o ./publish
    
  2. Deploy the published files to your hosting provider.

Deploying the React Frontend

  1. Build the React app for production:
    npm run build
    
  2. Deploy the build folder to Netlify, Vercel, or Azure Static Web Apps.

Configuring CORS

Ensure your .NET backend allows requests from the React frontend:

// Program.cs
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowReactApp",
        policy => policy.WithOrigins("https://your-react-app-url.com")
                        .AllowAnyHeader()
                        .AllowAnyMethod());
});

app.UseCors("AllowReactApp");

Conclusion

In this guide, you learned how to build an AI-powered chat interface using React and .NET. Here’s a quick recap of what you accomplished:

  • Set up a .NET backend with AI integration using OpenAI.
  • Built a React frontend for a seamless chat experience.
  • Connected the two using SignalR for real-time communication.
  • Tested and deployed the application.

Key Takeaways

  • React is ideal for building dynamic and responsive UIs.
  • .NET provides a robust backend for handling AI logic and real-time communication.
  • SignalR enables real-time updates without polling.
  • AI integration adds intelligence to your chat interface.

Call to Action

Now that you’ve built an AI chat interface, it’s time to experiment further! Here are some ideas:

  • Add authentication to secure your chat application.
  • Integrate Azure AI for advanced natural language processing.
  • Deploy your app to Azure or AWS for global accessibility.

Share your progress in the comments or reach out if you have questions. Happy coding! 🚀