paint-brush
3 Most Common Ways to Connect your Node and React Applications by@itsrakesh
611 reads
611 reads

3 Most Common Ways to Connect your Node and React Applications

by Rakesh PotnuruJanuary 2nd, 2022
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

There are different ways to connect react frontend and NodeJS backend. In this blog, I am going to tell you three ways how you can connect backend and frontend. These are the ways most developers prefer.

Companies Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - 3 Most Common Ways to Connect your Node and React Applications
Rakesh Potnuru HackerNoon profile picture


There are different ways to connect react frontend and NodeJS backend. In this blog, I am going to tell you three ways how you can connect backend and frontend. These are the ways most developers prefer.

Prerequisites

Basic knowledge of React and NodeJS

Let's Get Started

1. Single server

Single server

The first way is having a single server that serves both Node API and React SPA under the same domain. Here data is still exchanged through JSON. As you can see in the above picture, all the routes which do not start with /api will be handled by React SPA.

This is a simple way and you don't need to worry about those errors🥶. Here's how you can do it:


  • Copy build folder files from react app and paste them in public folder of NodeJS server.
  • Now serve the static index.html which is in the public folder
app.use(express.static(path.join('public')));
app.use((req,res) => {
   res.sendFile(path.resolve(__dirname, 'public', 'index.html'));
});

Pros

  • Single server.
  • No more CORS errors 😅
  • Ideal for small applications.

Cons

  • As both frontend and backend will be handled by the same server, you may face performance issues.

2. Two Separate Servers

Two separated servers Here we need two separate servers. One server serve static React SPA and another server serve Node API. Data will be exchanged through JSON.

Pros

  • As we use two different servers for backend and frontend, we get better performance.
  • Ideal for bigger applications.

Cons

  • Having to maintain two different servers.

3. Template engines

The third way and the least preferred way is server-side rendering with template engines like , , etc... Here we don't create any REST API. We render different HTML pages for different HTTP requests and use react to pre-render some parts of the page. This is not the preferred way to connect React and Node because we don't get the power of reactive user experience.



Hope this helps you! Save for reference. You can follow me on where I share random useful stuff.


First published


바카라사이트 바카라사이트 온라인바카라