Combining Node and React in backend

Photo by Tekton on Unsplash

Far not every web app built with React needs a backend. And those that do, can have different programming languages server-side. What backend to use with React? Python, PHP, Ruby, or Java – you can add any of them to your project tech stack. But there is an option of going fullstack JavaScript by using Node.js and Express.js.

So, should you use JavaScript on the backend of your React app? Let’s see whether combining Node and React would be a good idea.

Scroll down to read about an example app that is perfect to build with React and Node.

Who uses Node as a React backend?

Walmart was among the first large companies that benefited from using React.js with Node.js. In 2015, the company migrated about 25 apps that powered their eCommerce website from Java to the React and Node technology bundle.

“Migrating two dozen apps that process 10000 requests per second in less than a year to a completely different tech stack is a big deal. It's the best and the fastest tech transformation that I've seen in my career”, said Alex Grigoryan, Director of Software Engineering at Walmart at Nodevember Conference

The conversion to React using Node.js was the key enabler of transforming Walmart’s retail platform into a marketplace. In 2016, the custom technology solution they built was open-sourced as the Electrode platform for building highly-scalable universal React/Node apps.

With Node.js and React, Walmart's eCommerce website speed increased significantly. The company gained 60% performance improvement for the server-side rendered home page and 30% for client-side rendered checkout pages.

Since that time Node.js and React.js became a go-to solution for performance-critical and SEO-friendly web apps. Let’s check what benefits it gives web developers.

Find your next developer

Aan de slag

Benefits of using Node.js with React.js

Fullstack JavaScript developers creating dynamic websites and single-page apps (SPAs) may name Node.js the best backend for React.js for several reasons. This combination of tech allows them to:

  • Build universal (isomorphic) apps running JS code on the client and server.
  • Create SEO-friendly SPAs that leverage server-side rendering of app views.
  • Use the same V8 JavaScript engine for the client- and server-side rendering.
  • Employ React DOM components specifically designed to work with Node.js.
  • Leverage npm code packages to speed up the web app development cycle.
  • Use Node.js modules to bundle the React app into a single file.
  • Leverage event-driven, non-blocking architecture for I/O-intensive real-time apps.
  • Use JSON and MongoDB database to avoid data transformation.

However, in many cases, React.js and Node.js do not represent the complete stack of technologies used in building SPAs. MongoDB and Express are the tools that often work on the backend of such apps.

MERN stack for end-to-end web app development

MERN stands for MongoDB, Express.js, React.js, and Node.js. Those are four key technologies that are commonly used together in web development.

MERN stack for a web app

MERN stack allows building fullstack JavaScript web apps that use the JSON format for storing and transporting data:

  • MongoDB or its cloud version MongoDB Atlas stores JSON data using a binary version of JSON called BSON.
  • Express.js web app framework wraps HTTP requests and responses and makes it easy to map URLs to server-side functions.
  • React.js library runs JavaScript code in the browser to make the user interface interactive and communicate JSON data to the server.
  • Node.js runtime environment runs JavaScript code on the server and handles concurrent requests effectively.

On the backend, a MERN web app has an Express.js framework that interacts with the React frontend of the app. How well do they work together?

Why use Express with React in web development

Express.js is distributed as an open-source third-party module for Node.js. It’s way smaller than Django or Ruby on Rails. By adding only a thin abstraction layer on top of the Node.js server, it smooths web development without imposing a certain app structure. As React library is meant for architectural freedom, using it together with Express.js allows building highly-customized apps.

Express.js framework is lightweight and modular. Its core contains only basic functionality, like a routing system, session and cookie support, MIME helpers, RESTful interface, HAML-based views, etc., that can be extended by adding optional modules or middlewares if needed.

For even better flexibility, Express.js supports 24 JS templating engines, with EJS used as a default option. Among them, there are express-react-views, which allows rendering React components on the server to produce static HTML markup for React apps leveraging SSR.

Another advantage of this framework is a high speed and the ability to handle thousands of concurrent connections per second. Its performance can be additionally improved through caching or scaling to multiple processes. Being this productive, Express.js can hardly become a bottleneck for a high-load React app.

Example: how to build an app with MERN stack

We asked Peter, Fullstack Developer on Proxify, about his experience of using the MERN stack. For the last three years, Peter has completed several projects that had to use Node on the backend of React. He explained for what projects he uses this combo and gave us an example.

“I often use the MERN stack to build data-oriented applications with a microservice architecture. It works great because I can get a service up and running quickly with minimum effort and create a very scalable pipeline for data processing and data visualization.” – Peter, Fullstack developer

Let’s imagine you want to build an app that measures foot traffic in shopping malls. Your app can do it by processing anonymized facial recognition data collected from the devices within the buildings. It can count the number of unique visitors for every shop inside a mall and display the stats on a dashboard.

In terms of workflow, your future service will accept pre-processed sensor data in POST requests, do some additional server-side processing, and display statistics via a React interface. Such functionality might take a few months to build.

Peter suggests that MERN is the most efficient stack for such types of apps. If he worked on the project, he would use:

  • Node.js, to leverage a reliable enterprise-grade solution for scalable apps.
  • TypeScript, to ease maintainability, refactoring, and reduce the number of bugs.
  • Express.js, to build Restful APIs that serve as an interface for the service.
  • MongoDB, to store sensor data as a collection of documents that mimic the format of the incoming requests and require minimal processing.
  • React, to work with Restful APIs and fetch data from MongoDB.

Express.js serves well to create the routes and controllers that handle responses. An Express request handler is a simple function that uses requests and responses as arguments. It does some arbitrary processing and returns the response. It can be as simple as this little anonymous function: (req,res) => {}

“Express works great for such things. It’s easy-to-use and supported by many cloud providers. For example, Firebase functions are express response handlers. They are fully compatible. A little anonymous function, such as (req,res) => {}, can be exported as a cloud function given necessary dependencies.” – Peter, Fullstack developer

For this type of apps you can use Typescript to create a simple interface for displaying the data received via APIs:

interface shopperdata {
    fingerprint : string;
    timestamp : Date;
    location : GeoJson
} `
interface GeoJson {
    type : string,
    coordinates : [number]
}

The app will deal with anonymized data. The sensors can create it by running a SHA512 hash and a seed on the facial recognition data they capture, then send encrypted unique fingerprints into the app. This requires you to follow several rules:

Keep the seed a secret and never match this with any personal data. The timestamp should be the date when the face was scanned. The location should define where the sensor was placed (e.g. a store door frame).

GeoJson and MongoDb can work with such data out of the box. MongoDB allows saving it right away with only a tiny little thing added. You’ll need to define a schema to validate the values that you save into the database:

const storedDataSchema  = new Schema({
    _id : ObjectId,
    fingerprint : {type : String,required : true},
    timestamp : {type : Date, required : true},
    location : {
        type : {
            type : String, 
            enum: ['Point'],
            required : true
            },
        coordinates : {
            type : [Number],
            required : true
         }
    }
})

After this you can create a MongoDB model that you’ll use to access this data:

export const dataModel = model(
  'shopperdata',
  storedDataSchema
)

With this model, you’ll be able to save data into a collection called ‘shopperdata’ and make any query supported by MongoDB.

“When working with large amounts of data, object-oriented programming can bring unwanted overhead. I recommend that you stick to the functional approach when designing such services.” – Peter, Fullstack developer

MongoDB offers a very powerful way to query data. You’ll be able to run queries using the model. For example, the dataModel.distinct("fingerprint",{location : storeLocation}) query will return the number of unique customers that have visited a certain shop inside the mall using the storeLocation variable. Moreover, by stating the ‘from’ and ‘till’ dates, you’ll easily get the number of unique visitors for a certain period.

dataModel.distinct("fingerprint",{
            location : storeLocation,
            timestamp : {
                "$gte" : dateFrom,
                "$lte" : datetill} 
            })

Apart from that, you can calculate how many times people pass by a particular location to track the foot traffic inside the mall using the dataModel.where('location').near({center: storeLocation}) query. This query takes advantage of using GeoJSON format and MongoDB’s built-in location data support.

“As you see, the backend built with MERN allows running simple queries that give endless possibilities. Creating a slick frontend with React will be the final touch. React library has great tools for displaying stats in the form of beautiful charts. Those tools will help you present the value your app creates to businesses.” – Peter, Fullstack developer

As a bonus, most payment gateways, like Stripe, have out-of-the-box solutions for integration with React apps. This makes adding features for monthly subscription payments collection an easy task. Apart from that, Node.js can also compete for the title of the best backend for React Native mobile apps.

Ready to build a React and Express app?

For this task, you should hire React developers experienced in using Express with React for fullstack JS web apps. At Proxify you’ll find senior programmers that have built similar projects before. We can recommend specialists who know how to architect React/Node apps that scale well and are easy to maintain.

Send us a talent request and we’ll match you with the right Node developer within two weeks. And remember, when hiring on Proxify, you benefit from reasonable rates starting from 29€ / h.

Quick React backend Q&A

You ask, we answer.

What backend to use with react?

React.js web apps can have various technologies on the backend. You can ask your developers to use Django (Python), Laravel (PHP), RoR (Ruby), or make a fullstack JavaScript app with Express (Node.js) on the backend. Moreover, if you follow a decoupled architecture and your frontend communicates with the backend via API, you can rewrite your server-side app in another framework if needed. As long as the API remains the same your React app would continue working as intended.

What is the best backend for React.js?

Many fullstack JavaScript developers creating SPAs would vote for Node.js, Express, and Mongo DB as the best backend for React. Those technologies are commonly used together in web development and form the so-called MERN stack. MERN works exceptionally well for rapid prototyping and building MVPs.

What database to use with React.js?

Your React.js application can have any type of database on its backend: relational (SQL) or non-relational (NoSQL). Your choice would depend on the type of data you’re going to collect and store. If the data is structured, such as name, email, user ID, choose MySQL. For unstructured data, such as social media posts or text and media files, use Firebase or MongoDB. If you need to manage both types of data, Postgre would be a good choice.

How to use Node and React together?

Node.js is a runtime environment for server-side JavaScript. You’ll need to use the Express.js framework to write a server app that will run on Node and connect it to your React frontend app via API.

Kseniia Kyslova

Kseniia Kyslova

Content marketing specialist

Kseniia is a content writer at Proxify. She collaborates with tech folks to assist them in sharing knowledge and expertise on the web.

Verified author

We work exclusively with top-tier professionals.
Our writers and reviewers are carefully vetted industry experts from the Proxify network who ensure every piece of content is precise, relevant, and rooted in deep expertise.

Vind jouw volgende ontwikkelaar binnen enkele dagen, niet maanden

In een kort gesprek van 25 minuten:

  • gaan we in op wat je nodig hebt om je product te ontwikkelen;
  • Ons proces uitleggen om u te matchen met gekwalificeerde, doorgelichte ontwikkelaars uit ons netwerk
  • delen we de stappen met je om de juiste match te vinden, vaak al binnen een week.

Maak een afspraak