0

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?

  • No, `react-router-dom` is client side routing. You'll need something like Nextjs to do any server-side routing/rendering. Is there an issue with having the `"/post"` route's component make an API call? – Drew Reese Aug 04 '22 at 16:07

2 Answers2

0

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

Shah
  • 2,126
  • 1
  • 16
  • 21
0

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");
});
Abi Ji
  • 184
  • 1
  • 4