The above comments didn't mention the core of this post. OP is coming from the templating world (PUG, etc). This is essentially, technically, traditionally server-side rendering. The server handles the request, determines what to render, then sends out a bunch of HTML to the browser. Since 2010s, client side frameworks (like AngluarJS, React, Vue) emerged. In simple words they use pure Javascript to generate the DOM (more or less equivalent to HTML in JS world). The HTML (index.html) is just a blank shell pointing to a script to render UI. This is called Client Side Rendering (CSR). JS can also handle client side routing by mimicking URL changes but under the hood it's just showing and hiding stuff with JS. This is Single Page App (SPA). These files can be served statically with any server/service (like nginx, caddy, S3), and probably not ExpressJS most of the time. So, the first answer to this post is: No you don't need to use Express if you just want a simple SPA, follow the Vite Tutorial till "Deploying" ( https://vitejs.dev/guide/static-deploy.html ). Then, your app probably needs data. The browser has a function called fetch() to fetch data from URL. If you fetch https://www.google.com you will get some HTML strings because it is serving a website directly. If you fetch https://reqres.in/api/users you will get a JSON containing some JSON data. When you build an SPA, all dynamic data will be coming from some API. Express usually works with any SPA as a REST api server, rather than serving the HTML directly. But, SPA is not Search engine friendly because the index.html does not contain any data at all (IDK, thats what people said 5 years ago :/). People started to want SSR again, but still wanted to use React. We then have https://react.dev/reference/react-dom/server . It is used by frameworks like Next.js to render complete HTML with the react rendering, on the server, send it to browser, then "hydrating" the website to be a complete react app. OK, I have gone too far. Anyway, it's still react and your data can still come from a separate Express server no matter what framework you're using. Someone said "Fetching from server A to server B then render HTML to browser is too slow". Then Next.JS and the react team now advocates "React Server Components" (RSC), (not to be confused as SSR) (not to be discussed here). They encourage putting backend logic directly in your Next.js app without an extra API server. So the Express server is not necessary too. As long as you chose react, the express server will never be a templating engine anymore. It's a REST API server that provides data for your react app. Answer from hinsxd on reddit.com
🌐
React Express
react.express
React Express
Additionally, this guide covers important tools and projects in the React ecosystem which are outside the scope of the React docs. This guide is intended for people who already know JavaScript. If you're new to JavaScript, or could use a refresher, consider first going through JavaScript Express. We'll assume a little knowledge of HTML and CSS, but even if you're not familiar with those, you should still be able to follow this guide. The interactive examples in this guide work better on desktop than mobile.
4.6useRef
In this example, we pass our ref to a canvas component. React will then assign the canvas's underlying DOM node to our ref's current property.
4.1useState
The useState hook lets us "remember" a value within a component function. Since our component function may be called many times throughout the lifecycle of the component, any variable we declare normally (i.e. with let myVar = ...) will get reset. With useState, React can remember a state variable ...
4.2useReducer
The useReducer hook is similar to useState, but gives us a more structured approach for updating complex values Β· We typically use useReducer when our state has multiple sub-values, e.g. an object containing keys that we want to update independently
5.6Data Model Props
Sometimes our components represent entities in our data schema, such as people, articles, posts, multimedia, etc. In these cases, we have to decide how we want to pass our data into our components, e.g. our post data model into our Post component Β· This is especially common if we're using ...
🌐
GitHub
github.com β€Ί nburgess β€Ί react-express-example
GitHub - nburgess/react-express-example: Quick example for creating a React application with an Express backend.
Quick example for creating a React application with an Express backend. - nburgess/react-express-example
Starred by 58 users
Forked by 40 users
Languages Β  JavaScript 78.8% | HTML 16.6% | CSS 4.6%
🌐
Reddit
reddit.com β€Ί r/reactjs β€Ί how do i use react with an express application?
r/reactjs on Reddit: how do I use react with an express application?
September 6, 2023 -

hi so basically I have been using express generator to make new express apps. I can make servers and then endpoint routes and then I then render html files for each of the routes visited and i use PUG as the view engine.

app.set("views", path.join(__dirname, "../views"));app.set("view engine", "pug");

Pug is nice but I am trying to figure out how to use react instead of making views for every route. Also as far as styling, using express generator I seem to only be able to edit styles.css to write vanilla css and then I have to serve the static path.

app.use(express.static(path.join(__dirname, "../public")));

In a nutshell, I am just trying to figure out how to use react with nodejs and express. I read a couple of guides so I think I have the directory structure correct (client and server, each with their own node modules), but not sure on how to proceed. any advice? I've attached my repo. thanks.

https://github.com/ForkEyeee/blog-api

Top answer
1 of 6
43
The above comments didn't mention the core of this post. OP is coming from the templating world (PUG, etc). This is essentially, technically, traditionally server-side rendering. The server handles the request, determines what to render, then sends out a bunch of HTML to the browser. Since 2010s, client side frameworks (like AngluarJS, React, Vue) emerged. In simple words they use pure Javascript to generate the DOM (more or less equivalent to HTML in JS world). The HTML (index.html) is just a blank shell pointing to a script to render UI. This is called Client Side Rendering (CSR). JS can also handle client side routing by mimicking URL changes but under the hood it's just showing and hiding stuff with JS. This is Single Page App (SPA). These files can be served statically with any server/service (like nginx, caddy, S3), and probably not ExpressJS most of the time. So, the first answer to this post is: No you don't need to use Express if you just want a simple SPA, follow the Vite Tutorial till "Deploying" ( https://vitejs.dev/guide/static-deploy.html ). Then, your app probably needs data. The browser has a function called fetch() to fetch data from URL. If you fetch https://www.google.com you will get some HTML strings because it is serving a website directly. If you fetch https://reqres.in/api/users you will get a JSON containing some JSON data. When you build an SPA, all dynamic data will be coming from some API. Express usually works with any SPA as a REST api server, rather than serving the HTML directly. But, SPA is not Search engine friendly because the index.html does not contain any data at all (IDK, thats what people said 5 years ago :/). People started to want SSR again, but still wanted to use React. We then have https://react.dev/reference/react-dom/server . It is used by frameworks like Next.js to render complete HTML with the react rendering, on the server, send it to browser, then "hydrating" the website to be a complete react app. OK, I have gone too far. Anyway, it's still react and your data can still come from a separate Express server no matter what framework you're using. Someone said "Fetching from server A to server B then render HTML to browser is too slow". Then Next.JS and the react team now advocates "React Server Components" (RSC), (not to be confused as SSR) (not to be discussed here). They encourage putting backend logic directly in your Next.js app without an extra API server. So the Express server is not necessary too. As long as you chose react, the express server will never be a templating engine anymore. It's a REST API server that provides data for your react app.
2 of 6
6
Your express is an API, it’s sole purpose would be to serve and ingest content Your client (react app) should make calls to the API then render the data appropriately
🌐
DEV Community
dev.to β€Ί techcheck β€Ί creating-a-react-node-and-express-app-1ieg
Creating a React, Node, and Express App - DEV Community
February 14, 2024 - In this article, I'll show you how to create a project with React, Node, and Express. We'll get the...
🌐
freeCodeCamp
freecodecamp.org β€Ί news β€Ί create-a-react-frontend-a-node-express-backend-and-connect-them-together-c5798926047c
How to create a React frontend and a Node/Express backend and connect them
September 7, 2018 - By JoΓ£o Henrique In this article, I’ll walk you through the process of creating a simple React app and connecting it to a simple Node/Express API that we will also be creating. I won't go into much detail about how to work with any of the technologie...
🌐
Simplilearn
simplilearn.com β€Ί home β€Ί resources β€Ί software development β€Ί learn react tutorial with real-world projects β€Ί the best guide to understanding react and express
Understanding React And Express: (A Comprehensive Guide) | Simplilearn
June 9, 2025 - React is a front-end JavaScript library, and Express is a back-end framework for web applications. This tutorial on React Express will walk you through all the topics. Click here to learn more.
Address Β  5851 Legacy Circle, 6th Floor, Plano, TX 75024 United States
🌐
Medium
medium.com β€Ί @eslmzadpc13 β€Ί how-to-use-react-with-express-5f832dc74104
How to use React with Express. Are you a React developer looking to… | by Eslam zaid | Medium
June 22, 2023 - To connect your React front end with the Express backend, you’ll need to make API calls from your React components. To achieve this, you can use popular libraries like Axios or the built-in fetch function. Here’s an example of creating an API call to retrieve data from your Express server:
🌐
GitHub
github.com β€Ί alexdevero β€Ί react-express-app
GitHub - alexdevero/react-express-app: Awesome and super-simple app with React front-end and Express back-end.
. β”œβ”€β”€ server/ - Express server that provides API routes and serves front-end β”‚ β”œβ”€β”€ routes/ - Handles API calls for routes β”‚ β”œβ”€β”€ app.js - Adds middleware to the express server β”‚ β”œβ”€β”€ sampleData.js - Contains all sample text data for generate pages β”‚ β”œβ”€β”€ constants.js - Defines the constants for the endpoints and port β”‚ └── server.js - Configures Port and HTTP Server β”œβ”€β”€ src - React front-end β”‚ β”œβ”€β”€ components - React components for each page β”‚ β”œβ”€β”€ App.jsx - React routing β”‚ └── index.jsx - React root component └── README.md
Starred by 9 users
Forked by 5 users
Languages Β  JavaScript 88.9% | HTML 5.9% | CSS 5.2%
Find elsewhere
🌐
Medium
medium.com β€Ί @maison.moa β€Ί setting-up-an-express-backend-server-for-create-react-app-bc7620b20a61
Setting up a Node.js Express server for React | by Maison Moa | Medium
May 12, 2018 - So far at this point, you should have created express_react_example folder, and then a server.js file inside of it.
🌐
Scaler
scaler.com β€Ί topics β€Ί expressjs-tutorial β€Ί express-react
Integrate React with NodeJS Express - Scaler Topics
July 10, 2023 - When the server starts, a callback function is invoked, and in our example, it just logs the server's running message. This is how the finished server.js file will appear: Open a terminal and enter the following command to launch the backend server: This command will start the server on port 8000. ... Open your browser and navigate to http://localhost:8000/message to view the JSON object the server returned to verify that it is functioning. ... In our express react amalgamation, replace the existing code by opening the App.js file in the src folder and adding the following.
🌐
GitHub
github.com β€Ί philnash β€Ί react-express-starter
GitHub - philnash/react-express-starter: A starter kit for React applications with a back end server all in the same project
This project was bootstrapped with Create React App. Then an Express server was added in the server directory.
Starred by 192 users
Forked by 89 users
Languages Β  JavaScript 75.5% | HTML 15.9% | CSS 8.6%
🌐
PropelAuth
propelauth.com β€Ί post β€Ί react-express-starter-app
React/Express Starter App | PropelAuth
July 13, 2023 - In this guide, we’ll build an example application in React/Express where users can sign up, login, and manage their acco...
🌐
React Native Express
reactnative.express
React Native Express
If you run into topics that aren't covered thoroughly in the React Native docs, play with the examples in this guide to quickly get up to speed. If you're already knowledgeable about a topic in this guide (e.g.
🌐
DEV Community
dev.to β€Ί juhanakristian β€Ί basics-of-react-server-side-rendering-with-expressjs-phd
Basics of React server-side rendering with Express.js - DEV Community
December 13, 2022 - Our main code in the client side is in App.jsx. import * as React from "react"; export default function App() { const [times, setTimes] = React.useState(0); return ( <div> <h1>Hello {times}</h1> <button onClick={() => setTimes((times) => times ...
🌐
GitHub
github.com β€Ί esausilva β€Ί example-create-react-app-express
GitHub - esausilva/example-create-react-app-express: Example on using create-react-app with a Node Express Backend
Example on using create-react-app with a Node Express Backend - esausilva/example-create-react-app-express
Starred by 370 users
Forked by 140 users
Languages Β  JavaScript 76.9% | HTML 16.9% | CSS 5.9% | Shell 0.3%
🌐
LinkedIn
linkedin.com β€Ί pulse β€Ί how-connect-express-react-comprehensive-guide-eslam-zaid
How to Connect Express with React: A Comprehensive Guide
July 15, 2023 - Open your browser and navigate to http://localhost:5000, and you should see the "Hello from Express!" message displayed. 5. Create a React Application Now that your Express server is up and running, it’s time to create a React application.
Top answer
1 of 3
20

There were a few errors. Here is some updated code and a description of what was going on:

React App.js:

import React, { Component } from 'react';
import axios from 'axios';

class Create extends Component {
  constructor(props) {
    super(props);

    this.state = {
      bookID: '',
      bookTitle: '',
      bookAuthor: '',
    };
  }

  handleInputChange = e => {
    this.setState({
      [e.target.name]: e.target.value,
    });
  };

  handleSubmit = e => {
    e.preventDefault();

    const { bookID, bookTitle, bookAuthor } = this.state;

    const book = {
      bookID,
      bookTitle,
      bookAuthor,
    };

    axios
      .post('http://localhost:3001/create', book)
      .then(() => console.log('Book Created'))
      .catch(err => {
        console.error(err);
      });
  };

  render() {
    return (
      <div>
        <br />
        <div className="container">
          <form onSubmit={this.handleSubmit}>
            <div style={{ width: '30%' }} className="form-group">
              <input
                type="text"
                className="form-control"
                name="bookID"
                placeholder="Book ID"
                onChange={this.handleInputChange}
              />
            </div>
            <br />
            <div style={{ width: '30%' }} className="form-group">
              <input
                type="text"
                className="form-control"
                name="bookTitle"
                placeholder="Book Title"
                onChange={this.handleInputChange}
              />
            </div>
            <br />
            <div style={{ width: '30%' }} className="form-group">
              <input
                type="text"
                className="form-control"
                name="bookAuthor"
                placeholder="Book Author"
                onChange={this.handleInputChange}
              />
            </div>
            <br />
            <div style={{ width: '30%' }}>
              <button className="btn btn-success" type="submit">
                Create
              </button>
            </div>
          </form>
        </div>
      </div>
    );
  }
}

export default Create;
  1. You were getting errors for using class and not className. class is a reserved word in react.js and should not be used.
  2. You were using the default post method which I would not recommend. I split the post out into it's own action and used the common library axios to make the CORS post call. I also created a function to handle the input changing on every key press with react.js.
  3. I added state to your component. This is common when there are form inputs to store them in state. I also changed the name of your variables to be title case which is the common way to write code variables.

Node.js index.js:

const express = require('express');
const logger = require('morgan');
const cors = require('cors');

const app = express();

//use cors to allow cross origin resource sharing
app.use(
  cors({
    origin: 'http://localhost:3000',
    credentials: true,
  })
);

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

let books = [];

app.get('/home', function(req, res) {
  console.log('Inside Home Login');
  res.writeHead(200, {
    'Content-Type': 'application/json',
  });
  console.log('Books : ', JSON.stringify(books));
  res.end(JSON.stringify(books));
});

app.post('/create', function(req, res) {
  const newBook = {
    BookID: req.body.bookID,
    Title: req.body.bookTitle,
    Author: req.body.bookAuthor,
  };

  books.push(newBook);
  console.log(books);
});

//start your server on port 3001
app.listen(3001, () => {
  console.log('Server Listening on port 3001');
});

  1. You weren't parsing the body of the req, so it was coming back as undefined. I added app.use(express.json()); and app.use(express.urlencoded({ extended: false })); which should take care of most of the issues.
  2. I updated the req.body variables to match those coming over from React.
  3. I added the module morgen which you see here app.use(logger('dev')); this is helpful by showing all your requests and statuses for dev purposes. In this case, it was showing that you were getting a 500 (internal server error) because express couldn't read bookID of undefined (because the body wasn't being parsed).

This should be working now, let me know if you have any problems.

2 of 3
0

I don't use express some so the details may not apply.

In essence you will have to send a network request to your server. How you do this is up to you, The most common ways are with axios(a library) or with vanilla js with the fetch api.

I would just use the fetch api. it takes two parameters an url and the options. so it should be called like this fetch(url,options)

so in your case it would be fetch('localhost:3001/create, options)

What should be in the options. I just suggest you look at the fecth MDN docs here https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

but your case you will need to pass an object with the method property set to post and the new book you want to data property set to a JSON serialized object of the book you want to create.

for example

let book ={
    BookId:1,
    Title: "coolBook",
    Author: "Me"
}

fetch("localhost:3001/create",
{
     method: "post",
     data: JSON.stringify(book)
}

When passing the books a string instead of an object you will likely have to take that string and parse it as an object on the server so that you express /create handler looks more like:

app.post('/create', function (req, res) {
    var newBook = JSON.parse(req.body.data)
    books.push(newBook)
    console.log(books);
})

On the react side you need to create an event handler that calls the above fetch function. I recommend you watch a react/express tutorial though as I can;t really cover all the thing required here in a stack overflow question such as: using and validating forms in react, error handling, async/await and so on.

All the Best! hope that was slightly helpful