🔌 Part 7: Connecting Frontend and Backend

With both frontend and backend components ready, it's time to connect them and ensure the chat interface communicates seamlessly with the backend API. This part focuses on API integration, routing, and testing the flow.


✅ What We'll Cover

  • Setting up proxy for development
  • Creating backend API endpoints
  • Sending chat messages from frontend
  • Handling CORS and testing full flow

🌐 1. Proxy Setup for Development

In your frontend/package.json, add a proxy to redirect API calls to the backend:

"proxy": "http://localhost:5000"

This tells React to forward /api requests to your backend during development.


🧪 2. Backend API Endpoint

Create a basic API in your backend:

// backend/routes/chat.js
const express = require('express');
const router = express.Router();
const { createQAChain } = require('../langchain/qaChain');

router.post('/', async (req, res) => {
  const { question } = req.body;

  try {
    const qaChain = await createQAChain();
    const response = await qaChain.call({ question });
    res.json({ answer: response.text });
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: 'Failed to process question' });
  }
});

module.exports = router;

And update your main server file to use this route:

// backend/server.js
const express = require('express');
const cors = require('cors');
const chatRoute = require('./routes/chat');
require('dotenv').config();

const app = express();
const PORT = process.env.PORT || 5000;

app.use(cors());
app.use(express.json());
app.use('/api/chat', chatRoute);

app.listen(PORT, () => {
  console.log(\`Server running on port \${PORT}\`);
});

🔁 3. Frontend Axios Integration

Already implemented in Part 6, your React component should be sending messages to /api/chat using Axios.

Make sure both frontend and backend are running:

# In one terminal
cd backend
node server.js

# In another terminal
cd frontend
npm start

✅ Next Steps (Part 8)

In the final part of this series, we’ll:

  • Deploy the chatbot to production
  • Optimize performance and cost
  • Set up monitoring and logging

🚀 You’re almost there—just one step to go!