React16 Server Side Rendering (SSR) CSS and Images Not Loading Issues

Before looking into React16 SSR css and images related issues first check go through a Step By Step guide for implementing React16 Server Side Rendering (SSR) with Material-ui library

React16 SSR css & public images not loading issue

Since in SSR applications we configure our own http server using expressjs or any other framework, we have to configure the path for public folder and css files folder path so that http server finds the file when request comes.

To fix css and public images not loading issue which is a very common issues in react ssr applications, we have to add following below lines in our server side script

//note the relative path of build folder  may change as per your project structure check those ../.. as per your project.
app.use(express.static(path.join(__dirname, '../../build'))); 
app.use(express.static(path.join(__dirname, 'public')));

if above two lines are not added in your server side script then you may face following common issues.

  1. Bootstrap/jquery css files are not getting included after running npm run build and running the app
  2. images referred from public folder will not be loaded

ComponentDidMount not getting called in React SSR application

Another very common problem in react ssr applications is once we enable server side rendering client side rendering will stop happening. Since client side rendering doesn’t happen componentDidMount will not be fired some times.

React run build generates lots of javascript files under build/static/js folder, if these files are not served by our server side script when browser requests those files then client side rendering fails. when we generate build using npm run build, react-scripts refers those static js files in index.html file. When page is loaded browser requests for those js files but our server side script fails to serve those files.

again to solve this issue the above two lines code is important especially,

//note the relative path of build folder  may change as per your project structure check those ../.. as per your project.
app.use(express.static(path.join(__dirname, '../../build')));