skip to Main Content

The Setup

I’m building a React app that is statically served using Express.

  • The React app is built with npm run build and the static files live in the build/ directory.

  • Express statically serves these files with the following code (reference):

const path = require("path");
const express = require("express");
const app = express();
const port = 80;
const host = "::";

let root = path.join(__dirname, "build"); // Output of `npm run build`
app.use(express.static(root));  // Tell Express to serve static files from here

// The wildcard (*) lets all paths bypass Express 
// in favor of React handling client-side routing.
app.get("/*", (req, res) => {
  res.sendFile(path.join(root, "index.html"));
});

app.listen(port, host, () => {
  console.log(`Serving from root=${root}`);
  console.log(`Example app listening on host ${host} & port ${port}`);
});

I’m also containerizing the app and deploying it to EKS behind an Ingress (aka, an entrypoint).

  • The Ingress URL is ingress.company.com
  • My app has an address reserved at ingress.company.com/my-app. All users must be able to go here, so every URL should use this /my-app slug.

The Problem

When I point my browser to ingress.company.com/my-app, Express successfully returns build/index.html. However, the accompanying static JavaScript files aren’t being found resulting in a bare HTML file without life.

I’ve discovered the reason why:

  • The static JavaScript file lives at ingress.company.com/my-app/js/main.hash.js
  • Express is trying to reach files at ingress.company.com/js/main.hash.js (missing my-app/) and a 404 is returned.

How can I get my Static Express Server to include the URL slug my-app/ when serving for build files? Is there a way to set a Base URL?

2

Answers


  1. Chosen as BEST ANSWER

    According to the official Create React App docs:

    By default, Create React App produces a build assuming your app is hosted at the server root. To override this, specify the homepage in your package.json, for example:

      "homepage": "http://mywebsite.com/relativepath",
    

    This will let Create React App correctly infer the root path to use in the generated HTML file.


  2. The problem is perhaps with your index.html file.
    Have you included your Javascript files inside a script tag in your index html file?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search