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
- First, create a new directory for your project and navigate to it in your terminal.
mkdir react-server-deployment
cd react-server-deployment
- Next, initialize a new Node.js project by running:
npm init -y
- Install the necessary dependencies:
npm install express react react-dom
- Create a new
server.js
file in the project root:
touch server.js
- Open
server.js
and add the following code:
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
First, sign up for a free account on Heroku if you haven't already.
Install the Heroku CLI on your local machine.
Log in to your Heroku account using the CLI:
heroku login
- In your project folder, create a new Heroku application:
heroku create
- Add a new file named
Procfile
to your project root:
touch Procfile
- Open the
Procfile
and add the following content:
web: node server.js
This tells Heroku to run your server.js
file with Node.js.
- Commit your changes to a new Git repository:
git init
git add .
git commit -m "Initial commit"
- Push your changes to Heroku:
git push heroku master
- 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.