Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serve ReactJS static files with expressJS?

The Problem

I have successfully served the index.html file of my React app, but the index.js that replaces <root> in the html file with my first React component is not triggering on ReactDOM.render. How do I get the index.js file to start? If my understanding of serving a React app is skewed in certain ways, I would greatly appreciate clarification.

Folder Structure

  • / - contains all server-side files, including server.js
  • /client/ - contains all React files
  • /client/build/ - contains all production-ready client files
    • /client/build/index.html
    • /client/build/static/js/main.[hash].js - seems to be a minified version of index.js that contains the ReactDOM.render for my React app

Current Deployment

  • I am using Facebook's create-react-app for the /client/ directory, including npm run build to automatically populate /client/build/

File Snippets

// server.js
let app = express();
app.use(express.static(path.join(__dirname, '../client/public')));

This successfully loads the default index.html provided by create-react-app

// index.html
<body>
  <noscript>
    You need to enable JavaScript to run this app.
  </noscript>
  <div id="root"></div>
</body>

The above section of code may/may not be useful, but it is the default html file that comes with create-react-app. Do I need to replace the noscript tag with a script tag that references the minified index.js file? I have attempted that, and nothing changed, but perhaps it is because of incorrect relative path-making.

like image 435
gpsugy Avatar asked Jun 21 '17 19:06

gpsugy


People also ask

How do I serve a static file in node?

In your node application, you can use node-static module to serve static resources. The node-static module is an HTTP static-file server module with built-in caching. First of all, install node-static module using NPM as below. After installing node-static module, you can create static file server in Node.


1 Answers

After trying many different things through trial/error, the solution is quite simple:

Serve the /client/build folder in the static call, like so:

app.use(express.static(path.join(__dirname, '../client/build')));
like image 92
gpsugy Avatar answered Sep 18 '22 23:09

gpsugy