I am trying to implement server side rendering(ssr) in my react website, but I faced an error while running the express server?

Viewed 126

I am trying to implement server side rendering(ssr) in my react website, but I faced an error

 C:\Users\RONAK ASNANI\Desktop\storeshop\src\images\bookappointment.webp:1
RIFF�,


SyntaxError: Invalid or unexpected token

So, do I need to configure a webpack for server side redering and if yes then how?

Currently I just have a server folder setup in the root directory having server.js and index.js file.

 require("ignore-styles");

require("@babel/register")({
  ignore: [/(node_modules)/],
  presets: ["@babel/preset-env", "@babel/preset-react"],
});

require("./server");

This is index.js

import express from "express";
import fs from "fs";
import path from "path";

import React from "react";
import ReactDOMServer from "react-dom/server";

import App from "../src/App";

const PORT = 8000;

const app = express();

app.use("^/$", (req, res, next) => {
  fs.readFile(path.resolve("./build/index.html"), "utf-8", (err, data) => {
    if (err) {
      console.log(err);
      return res.status(500).send("Some error happened");
    }
    return res.send(
      data.replace(
        '<div id="root"></div>',
        `<div id="root">${ReactDOMServer.renderToString(<App />)}</div>`
      )
    );
  });
});

app.use(express.static(path.resolve(__dirname, "..", "build")));

app.listen(PORT, () => {
  console.log(`App launched on ${PORT}`);
});

This is server.js

I am totally new to server side rendering so any suggestions or guidance is welcomed?

1 Answers

If you want to ssr React yourself you can config webpack for development and production and for each we have client and server name , you can find samples in gitub , my suggestion is read from github first and get good prespective and after that start that , for example : https://github.com/cullenjett/react-ssr-boilerplate

Related