DEV Community

Avinash Maurya
Avinash Maurya

Posted on

microservices in React App

Another approach involves using a proxy server to route requests from the React app to the respective microservices. This can be achieved using a package like http-proxy-middleware.

Proxy Server

  1. Create a new directory for the proxy server.
  2. Inside the directory, create a package.json file:
{
  "name": "proxy-server",
  "version": "1.0.0",
  "main": "index.js",
  "dependencies": {
    "express": "^4.17.1",
    "http-proxy-middleware": "^1.0.6"
  }
}
Enter fullscreen mode Exit fullscreen mode
  1. Run npm install to install the dependencies.
  2. Create an index.js file:
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const app = express();
const PORT = 3000;

app.use('/serviceA', createProxyMiddleware({ target: 'http://localhost:3001', changeOrigin: true }));
app.use('/serviceB', createProxyMiddleware({ target: 'http://localhost:3002', changeOrigin: true }));

app.listen(PORT, () => {
  console.log(`Proxy server is running on port ${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode
  1. Run the proxy server with node index.js.

Microservice 1: Service A

Follow the steps mentioned in the first example to set up Service A.

Microservice 2: Service B

Follow the steps mentioned in the first example to set up Service B.

React Frontend

  1. Update the React frontend package.json to include a proxy configuration:
{
  "name": "frontend",
  "version": "1.0.0",
  "main": "index.js",
  "dependencies": {
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "axios": "^0.24.0"
  },
  "proxy": "http://localhost:3000"
}
Enter fullscreen mode Exit fullscreen mode
  1. Update the index.js file:
import React, { useState, useEffect } from 'react';
import axios from 'axios';

function App() {
  const [dataA, setDataA] = useState({});
  const [dataB, setDataB] = useState({});

  useEffect(() => {
    // Fetch data from Service A
    axios.get('/serviceA/api/data')
      .then(response => setDataA(response.data))
      .catch(error => console.error(error));

    // Fetch data from Service B
    axios.get('/serviceB/api/data')
      .then(response => setDataB(response.data))
      .catch(error => console.error(error));
  }, []);

  return (
    <div>
      <h1>Microservices Example</h1>
      <p>Value from Service A: {dataA.value}</p>
      <p>Value from Service B: {dataB.value}</p>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode
  1. Run the React frontend with npm start.

This approach uses a proxy server to forward requests from the React app to the microservices. It allows you to centralize routing and manage CORS issues effectively. Adjust the code as needed based on your specific requirements and use case.

Top comments (0)