Is there a way to host a React app without a NodeJS Server?

So you built your first React app and now it’s time to get it out in the world. But where do you host a React app?

Until now, you probably ran your app with npm start which spins up a development server for you to debug and test your app. But that won’t work in production.

After some research you will find out, that there are several services like Now or Heroku, that allow you to just push your React app to a public server to be accessed by the public without much configuration. You could also spin up a Droplet on Digital Ocean or buy a small VServer.

But can’t I just use my existing web hosting service? Is there a way to host my app without a NodeJS Server?`

The answer is Yes!

Serve your app like a static web site

If you’re only doing client-side stuff (no server-side rendering), you can drop a bundled version of your app on your web space and host your app from there.

To get a bundled version of your app, you can use build tools like Webpack or Parcel. If you created your app with create-react-app, you’re lucky! Everything is already set up for you to get your bundle by executing npm run build. This will build your app and put the bundled files fo your app into the /build folder:

Now there is only one thing left for you to do: Copy the contents of your /build folder to your web space.

Attention: If you’re using a router that is using the pushState history API like React Router with browserHistory, then you might need to configure your web server accordingly. That’s necessary because if you do a reload on a link like http://yourdomain.com/posts/123, your web server will look for the file /posts/123 – which results in a 404 Error.

The solution is, to configure the web server in a way, that all requests are always routed to your index.html file. If you’re using Apache, this could look like the following example:

    Options -MultiViews
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.html [QSA,L]

Congratulations! You’re serving your React app without using a NodeJS Server.

But why does this work?

Wrapping up

By building and bundling your app, the build tool bundles and minifies all your dependencies, javascript code and even CSS to a bunch of separate files. Those files contain all the necessary code for your app. After that, your index.html refers to those Javascript and CSS files like any other static . Since you’ve already bundled everything together, there is no need to import any npm modules anymore – that’s one reason why you can just serve your app as a static web site.

Don't miss my next post!

Did you like this article?
Sign up below and get my future blog posts delivered right into your inbox.

Photo by fabio on Unsplash

Leave a Reply