How to deploy react app with express js(SSR)

Deploy your reactjs application with expressjs backend. SSR server side rendering with expressjs and reactjs.

How to deploy react app with express js(SSR)
​​There are 2 ways you can deploy react app in production server.
we focus on server-side rendering with expressjs backend

1. Using static server
Create a build of react app and serve it statically using serve command. 

2. Serve page from expressjs
You don’t necessarily need a static server in order to run a Create React App project in production. It also works well when integrated into an existing server-side app.

First, you need to build your react code using:
npm run build
const express =require('express'); 
const path =require('path');
const app =express();
app.use(express.static(path.join(__dirname,'build')));
//setting static path
app.get('/',function(req, res){
res.sendFile(path.join(__dirname,'build','index.html'));
});​
app.listen(4000);


After getting build of your react code 
app.use(express.static(path.join(__dirname,'build')));
serve the build folder as static files, and target the index.html inside it

app.get('/',function(req, res){
res.sendFile(path.join(__dirname,'build','index.html'));
});

This will redirect all the incoming requests to index.html inside build directories. This is how react app can be deployed using SSR.


Related tags