Skip to main content

Deploying to Server-Side Platforms

In this tutorial, we'll learn how to deploy your React applications to popular server-side platforms, such as Node.js with Express and Heroku. Deploying to server-side platforms allows you to utilize server-side rendering (SSR) and other server-side features in your applications.

Setting Up Node.js and Express

  1. First, create a new directory for your project and navigate to it in your terminal.
mkdir react-server-deployment
cd react-server-deployment
  1. Next, initialize a new Node.js project by running:
npm init -y
  1. Install the necessary dependencies:
npm install express react react-dom
  1. Create a new server.js file in the project root:
touch server.js
  1. Open server.js and add the following code:
JavaScript
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;

app.use(express.static('build'));

app.get('*', (req, res) => {
res.sendFile(__dirname + '/build/index.html');
});

app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});

This code sets up a simple Express server that serves the React application from the build folder. You can replace the build folder with the output folder of your React application.

Deploying to Heroku

  1. First, sign up for a free account on Heroku if you haven't already.

  2. Install the Heroku CLI on your local machine.

  3. Log in to your Heroku account using the CLI:

heroku login
  1. In your project folder, create a new Heroku application:
heroku create
  1. Add a new file named Procfile to your project root:
touch Procfile
  1. Open the Procfile and add the following content:
web: node server.js

This tells Heroku to run your server.js file with Node.js.

  1. Commit your changes to a new Git repository:
git init
git add .
git commit -m "Initial commit"
  1. Push your changes to Heroku:
git push heroku master
  1. Open the deployed application in your browser:
heroku open

Conclusion

Congratulations! You've successfully deployed your React application to a server-side platform. This allows you to take advantage of server-side features such as server-side rendering, APIs, and more.