How To Use create-react-app with a Node Express Backend API

This is a very common question among newer React developers, and one question I had when I was starting out with React and Node. In this short example I will show you how to use create-react-app with a Node Express Backend.

GitHub Repo

Get the full code on the GitHub Repo for this example.

The How To

create-react-app

Create a project using create-react-app

$ create-react-app example-create-react-app-express

Create a example-create-react-app-express/client directory and move all of the React boilerplate created by create-react-app to this new client directory

$ cd example-create-react-app-express
$ mkdir client

The Express Server

Create a package.json inside the root directory and copy the following contents.

{
  "name": "example-create-react-app-express",
  "version": "1.0.0",
  "scripts": {
    "client": "cd client && yarn start",
    "server": "nodemon server.js",
    "dev": "concurrently --kill-others-on-fail \"yarn server\" \"yarn client\""
  },
  "dependencies": {
    "express": "^4.16.2"
  },
  "devDependencies": {
    "concurrently": "^3.5.0"
  }
}

Notice I am using concurrently to run the React app and Server at the same time. The –kill-others-on-fail flag will kill other processes if one exits with non zero status code.

Install nodemon globally and the server dependencies.

$ npm i nodemon -g
$ yarn

Create a server.js file and copy the following contents

const express = require('express');

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

app.get('/api/hello', (req, res) => {
  res.send({ express: 'Hello From Express' });
});

app.listen(port, () => console.log(`Listening on port ${port}`));

This is a simple Express server that will run on port 5000 and have a single API route /api/hello.

The React App

Now switch over to the client directory where our React app lives.

Add the following line to package.json.

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

The key to use an Express backend with a project created with create-react-app is on using a proxy. This tells Webpack development server to proxy our API requests to our API server, given that our Express server is running on localhost:5000.

Now modify /client/src/App.js to call our Express API Backend.

import React, { Component } from 'react';
import 'whatwg-fetch';

import logo from './logo.svg';

import './App.css';

class App extends Component {
  state = {
    response: ''
  };

  componentDidMount() {
    this.callApi()
      .then(res => this.setState({ response: res.express }))
      .catch(err => console.log(err));
  }

  callApi = async () => {
    const response = await fetch('/api/hello');
    const body = await response.json();

    if (response.status !== 200) throw Error(body.message);

    return body;
  };

  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <p className="App-intro">{this.state.response}</p>
      </div>
    );
  }
}

export default App;

We import whatwg-fetch to make API calls and create callApi method to interact with our Express API Backend, then call this method in componentDidMount and finally set the state to the API response, which will be Hello From Express.

Project Structure

This will be the final project structure.

Running the App

Run the following in the root of the project

$ yarn dev

Will launch the React app and run the server at the same time.

If you navigate to http://localhost:5000/api/hello, you will get the following

Now navigate to http://localhost:3000

 

That is it folks! If you have any questions let me know in the comment section.

 



Esau Silva
Software Engineer at Region One ESC
Full Stack Software Engineer working with Microsoft technologies, ReactJS is awesome and avid Brazilian Jiu-Jitsu practitioner
If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed.
Share