title: How to setup api calls in MERN Stack app (Server Side Rendering)
body: <p>I have created a react app that's a server side rendered, the problem am facing is setting up API calls. basically i want to get data from the database but i couldn't figure out how to do it properly.</p>
  
  <p>As you may know in the static MERN App / REST API the server sends data according to the requested routes through the data property, then we get it in the client using res.data but in the server side rendered app i can't do that because the server always sends HTML tag of the page that we request to the client through res.data property which makes sense, but what are the correct approach of setting up routes in a way that we can get and post data to the database in server rendered app</p>
  
  <p>Any help would really be appreciated, Thanks in advance</p>
  
  <p>server/server.js</p>
  
  <pre><code>import React from "react";
  import express from "express";
  import compression from "compression";
  import { Provider } from "react-redux";
  import ReactDOMServer from "react-dom/server";
  import { StaticRouter } from "react-router";
  import store from "../client/store/store";
  import App from "../client/App";
  import mongoose from "mongoose";
  import path from "path";
  import fs from "fs";
  import cors from "cors";
  import User from "./model/users";
  
  const app = express();
  const PORT = process.env.PORT || 3000;
  
  app.use(cors());
  app.use(compression());
  app.use(express.json());
  app.use(express.static("./build/public"));
  
  mongoose
    .connect(
      process.env.MONGODB_URI,
      {
        useNewUrlParser: true,
        useCreateIndex: true,
        useUnifiedTopology: true
      }
    )
    .then(() =&gt; {
      console.log("Connected to the Database...");
    })
    .catch(err =&gt; console.log("ERROR: " + err));
  
  app.get("*", (req, res) =&gt; {
    const content = ReactDOMServer.renderToString(
      &lt;Provider store={store}&gt;
        &lt;StaticRouter location={req.url} context={{}}&gt;
          &lt;App /&gt;
        &lt;/StaticRouter&gt;
      &lt;/Provider&gt;
    );
  
    const indexFile = path.resolve("./build/public/index.html");
    fs.readFile(indexFile, "utf8", (err, data) =&gt; {
      if (err) {
        console.log(err);
        return res.status(500).send("Oops, Something went wrong!");
      }
  
      return res.send(
        data.replace(
          '&lt;div id="root"&gt;&lt;/div&gt;',
          `&lt;!DOCTYPE html&gt;
          &lt;html lang="en"&gt;
            &lt;head&gt;
              &lt;meta charset="UTF-8" /&gt;
              &lt;meta name="viewport" content="width=device-width, initial-scale=1.0" /&gt;
              &lt;meta http-equiv="X-UA-Compatible" content="ie=edge" /&gt;
              &lt;title&gt;My App&lt;/title&gt;
            &lt;/head&gt;
            &lt;body&gt;
              &lt;div id="root"&gt;${content}&lt;/div&gt;
            &lt;/body&gt;
          &lt;/html&gt;`
        )
      );
    });
  });
  
  // app.get("/api/getData", (req, res) =&gt; {
  //   User.find({}, (err, users) =&gt; {
  //     if (err) throw err;
  //     res.json({ newUser: users });
  //   });
  // });
  
  app.listen(PORT, () =&gt; {
    console.log("server is listening to port:", PORT);
  });
  
  </code></pre>
  
  <p>client/client.js</p>
  
  <pre><code>import "./assets/scss/styles.scss";
  import React from "react";
  import ReactDOM from "react-dom";
  import { Provider } from "react-redux";
  import { BrowserRouter } from "react-router-dom";
  import App from "./App";
  import store from "./store/store";
  
  function importAll(r) {
    let images = {};
    r.keys().map(item =&gt; {
      images[item.replace("./", "")] = r(item);
    });
    return images;
  }
  importAll(require.context("./assets/images", false, /\.(png|jpe?g|svg)$/));
  
  ReactDOM.hydrate(
    &lt;Provider store={store}&gt;
      &lt;BrowserRouter&gt;
        &lt;App /&gt;
      &lt;/BrowserRouter&gt;
    &lt;/Provider&gt;,
    document.querySelector("#root")
  );
  </code></pre>
  
  <p>client/App.js</p>
  
  <pre><code>import React, { Component } from "react";
  import { connect } from "react-redux";
  import { Route, Switch } from "react-router-dom";
  import Home from "./pages/Home";
  import About from "./pages/About";
  import Themes from "./pages/themes";
  import Contact from "./pages/Contact";
  import ErrorBoundary from "./pages/ErrorBoundary";
  
  class App extends Component {
    render() {
      return (
        &lt;ErrorBoundary&gt;
          &lt;Switch&gt;
            &lt;Route exact path="/" component={Home} /&gt;
            &lt;Route exact path="/about" component={About} /&gt;
            &lt;Route exact path="/themes" component={Themes} /&gt;
            &lt;Route exact path="/contact" component={Contact} /&gt;
          &lt;/Switch&gt;
        &lt;/ErrorBoundary&gt;
      );
    }
  }
  
  export default connect()(App);
  </code></pre>
  
  <p>client/pages/Home.js</p>
  
  <pre><code>import React, { Component } from "react";
  import { connect } from "react-redux";
  import axios from "axios";
  
  class Home extends Component {
    componentDidMount() {
      axios
        .get("api/getData")
        .then(res =&gt; {
          if (res) {
            console.log(res.data);
          }
        })
        .catch(err =&gt; console.log(err));
    }
  
    render() {
      return (
        &lt;div&gt;&lt;h1&gt;Welcome Home&lt;/h1&gt;&lt;/div&gt;
      );
    }
  }
  
  export default connect()(Home);
  </code></pre>