How to server-side render a specific route in ReactJS?

766 Views Asked by At

I would like to server-side render only a specific route in React. For example, /home should be client-side rendered, but /post should be server-side rendered.

The /post route receives a post ID as a parameter(using react-router) and fetches the content from a database server.

Is their any way I can server-side render only a specific page/route using react-dom server?

2

There are 2 best solutions below

0
Shah On

Your data should be handled by the middleware and stored there to minimize api calls. The Front end should render based on that data.

0
Abi Ji On

One good approach is to use built version of your react within express.js server. So let's say you have your built version of your react inside build directory :

var express = require('express');
var app = express();

app.use("/post",function(req,res) { 
   console.log(req); // Do your stuff for post route
});

app.use("/",express.static(path.join(__dirname,"/build")));
app.use("/*",express.static(path.join(__dirname,"/build"))); // Handle react-router

const httpServer = require("http").createServer(app);
httpServer.listen(8080, function(){
    console.log("Server is running on 8080");
});