Suresh Kumar
Suresh Kumar

Reputation: 227

React CRA with SSR configuration throws 404 when using the resulting html

I have a react application built using CRA with the default configurations. I wanted to make SSR, so I followed an article something similar to this https://www.vairix.com/tech-blog/server-side-rendering-ssr-of-create-react-app-cra-app-in-2020

Next, I wanted to inline the JS and CSS so that I could hit the URL and copy the resultant HTML page and then use it where ever I want.

For that, I used react-app-rewired plugin which works now I can see the HTML with inline CSS and JS.

The issue is when I copy the generated HTML and save it as .html, and when I open the page, it returns 404 error.

I am trying to copy the HTML that is produced and then use them as individual components in a completely different application.

Am I missing something?

config-overrides.js for react app rewired

const HtmlWebpackPlugin = require("html-webpack-plugin");
const InlineChunkHtmlPlugin = require("react-dev-utils/InlineChunkHtmlPlugin");
const HTMLInlineCSSWebpackPlugin = require("html-inline-css-webpack-plugin").default;

module.exports = {
  webpack: function(config, env) {
    if (env === "production") {
      config.plugins.push(new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [/.*/]));
      config.plugins.push(new HTMLInlineCSSWebpackPlugin());
    }
    return config;
  }
};

server.js for SSR

import express from "express";
import path from "path";
import renderer from "./react-renderer";

const app = express();
const PORT = 8000;

const routes = ["/custom1/:id","/custom2/:id","/custom3/:id"];

app.get("/*", renderer(routes));

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

app.listen(PORT, () => {
  console.log(`App running in the port ${PORT}`);
});

Upvotes: 2

Views: 591

Answers (1)

Daniele Ricci
Daniele Ricci

Reputation: 15837

404 is the HTTP code for not found: I don't think the problem is in opening the page but in finding it.

It seems the first route you added in your server is catching all the requests:

app.get("/*", renderer(routes));

you could try moving it as last route

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

app.get("/*", renderer(routes));

More than this you didn't said where you copied the resulting page, I hope in ../build or in ../public directories, otherwise I'm not surprised you can't GET it.

Upvotes: 1

Related Questions