41
Different ways to connect react frontend and node backend
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.

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 CORS errors🥶.
Here's how you can do it-
This is a simple way and you don't need to worry about those CORS errors🥶.
Here's how you can do it-
build
folder files from react app and paste them in public
folder of NodeJS server.index.html
which in the public
folder
app.use(express.static(path.join('public')));
app.use((req,res) => {
res.sendFile(path.resolve(__dirname, 'public', 'index.html'));
});

The third way and the least preferred way is server-side rendering with template engines like ejs, handlebars, pugjs 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.
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.
So, what other ways do you know and what is your preferred way? Comment below 👇
Web maker is a offline web playground which you can use in your browser. Simply open web maker once and bookmark it.
41