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.

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay