Overview:
Heroku is a cloud platform that enables developers to build, run, and operate applications entirely in the cloud. It’s especially popular for deploying full-stack applications quickly and easily, without worrying about infrastructure management. In this tutorial, we’ll walk through deploying a full-stack application (with a Node.js backend and a React frontend) to Heroku.
By the end of this guide, you’ll have a fully functional full-stack application hosted on Heroku, accessible via a live URL.
Prerequisites:
- Heroku CLI installed.
- A Heroku account (you can sign up here).
- Basic knowledge of React and Node.js.
Step 1: Create a Simple Full-Stack Application
Let’s build a simple full-stack app that uses a React frontend and a Node.js/Express backend. We’ll start by setting up both the backend and frontend locally before deploying to Heroku.
1.1 Create a Project Directory
Create a directory to store your project files:
mkdir heroku-fullstack-app
cd heroku-fullstack-app
1.2 Set Up the Backend (Node.js/Express)
- Initialize a Node.js project:
npm init -y
- Install the necessary dependencies:
npm install express
- Create a
server.js
file:
touch server.js
Add the following code to server.js
:
const express = require('express');
const path = require('path');
const app = express();
const PORT = process.env.PORT || 5000;
// Serve static files from the React app
app.use(express.static(path.join(__dirname, 'client/build')));
// API route
app.get('/api/hello', (req, res) => {
res.json({ message: 'Hello from the server!' });
});
// The "catchall" handler: for any request that doesn't match one above, send back React's index.html file.
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname + '/client/build/index.html'));
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
This Node.js backend will serve the static files from the React frontend and provide a simple API route.
Step 2: Set Up the Frontend (React)
- Inside the
heroku-fullstack-app
directory, create the React app:
npx create-react-app client
- Navigate to the
client
directory:
cd client
- Add a simple API call to
App.js
:
Edit src/App.js
and replace its content with the following:
import React, { useState, useEffect } from 'react';
import './App.css';
function App() {
const [message, setMessage] = useState('');
useEffect(() => {
fetch('/api/hello')
.then((response) => response.json())
.then((data) => setMessage(data.message));
}, []);
return (
<div className="App">
<header className="App-header">
<h1>{message}</h1>
</header>
</div>
);
}
export default App;
This React frontend makes a call to the /api/hello
route served by the Node.js backend and displays the response.
- Build the React app for production:
npm run build
This command generates the optimized production build in the client/build
directory.
Step 3: Prepare for Deployment
3.1 Update the package.json
File
To deploy on Heroku, the root package.json
should also include the scripts to install both the backend and frontend dependencies and build the frontend.
Edit the root package.json
(in the heroku-fullstack-app
directory) to look like this:
{
"name": "heroku-fullstack-app",
"version": "1.0.0",
"description": "A full-stack app deployed to Heroku",
"main": "server.js",
"scripts": {
"start": "node server.js",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
},
"dependencies": {
"express": "^4.17.1"
},
"engines": {
"node": "14.x"
}
}
Explanation:
- The
"start"
script is what Heroku uses to start your app. - The
"heroku-postbuild"
script is crucial because it tells Heroku to build the React app when deploying. - The
"engines"
field specifies the Node.js version Heroku should use.
Step 4: Deploy to Heroku
4.1 Log in to Heroku
Log in to Heroku using the CLI:
heroku login
This will open a browser window asking you to authenticate.
4.2 Create a New Heroku App
In the root directory of your project, run the following command to create a new Heroku app:
heroku create
This will create a new app on Heroku and give you the URL where your app will be accessible once deployed.
4.3 Initialize a Git Repository
If you haven’t initialized a git repository yet, do so now:
git init
git add .
git commit -m "Initial commit"
4.4 Deploy the App
Now, deploy your app to Heroku by pushing your code to the Heroku remote repository:
git push heroku master
Heroku will detect your app type (Node.js) and automatically build and deploy it. After the deployment is complete, you’ll see a message with the URL where your app is live.
Example:
https://your-app-name.herokuapp.com/
4.5 Open the App
Open your deployed app in the browser using:
heroku open
Your full-stack application should be live, and the React frontend should display the message from the API route!
Step 5: Managing the App
Heroku provides several tools to manage your deployed application:
5.1 View Logs
To see logs from your application:
heroku logs --tail
This will show real-time logs from both the frontend and backend, which can be useful for debugging issues.
5.2 Scaling the App
By default, Heroku apps use a single dyno (a lightweight Linux container). You can scale your app using the following command:
heroku ps:scale web=1
5.3 Adding a Database (Optional)
You can easily add a PostgreSQL database to your app using Heroku’s free PostgreSQL add-on:
heroku addons:create heroku-postgresql:hobby-dev
This will provision a free PostgreSQL database for your app, and you can retrieve the database credentials from the Heroku dashboard.
Conclusion
In this tutorial, we deployed a full-stack application with a React frontend and a Node.js/Express backend on Heroku. We learned how to build and serve the React app from the backend, configure the app for deployment, and push it to Heroku using Git.
Heroku’s simplicity and ease of use make it an excellent platform for deploying small to medium-sized applications, especially during development and prototyping phases.
You can extend this setup by adding a database, user authentication, or even additional microservices. Heroku also offers integrations with CI/CD tools, making it a great platform for continuous deployment.
Feel free to copy and paste the code snippets and modify them for your own applications.