How to Deploy Express App to Heroku: Step-by-Step Guide
To deploy an
Express app to Heroku, first create a Procfile to tell Heroku how to run your app, then push your code to a Heroku Git remote using git push heroku main. Make sure your app listens on the port provided by process.env.PORT and has a start script in package.json.Syntax
Deploying Express to Heroku involves these key parts:
- Procfile: A file that tells Heroku how to start your app.
- package.json: Must include a
startscript to run your server. - Listening on the correct port: Your Express app must use
process.env.PORTto work on Heroku. - Git commands: Use
heroku createto make a Heroku app andgit push heroku mainto deploy.
bash
web: node index.js
Example
This example shows a simple Express app setup ready for Heroku deployment. It listens on the port Heroku assigns and includes a Procfile and package.json with a start script.
javascript
const express = require('express'); const app = express(); const PORT = process.env.PORT || 3000; app.get('/', (req, res) => { res.send('Hello from Express on Heroku!'); }); app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });
Output
Server running on port 3000 (or assigned Heroku port)
Common Pitfalls
Common mistakes when deploying Express to Heroku include:
- Not using
process.env.PORTfor the server port, causing the app to crash on Heroku. - Missing a
startscript inpackage.json, so Heroku doesn't know how to run the app. - Forgetting to commit the
Procfileor having wrong syntax in it. - Not pushing to the correct Heroku Git remote branch.
javascript
Wrong (hardcoded port): const PORT = 3000; Right (dynamic port): const PORT = process.env.PORT || 3000;
Quick Reference
- Create a Heroku app:
heroku create - Add a
Procfilewith:web: node index.js - Ensure
package.jsonhas:"start": "node index.js"script - Use
process.env.PORTin your Express app - Deploy with:
git push heroku main
Key Takeaways
Always use process.env.PORT to listen on the correct port for Heroku.
Include a start script in package.json to tell Heroku how to run your app.
Create a Procfile with 'web: node index.js' to define the web process.
Use git push heroku main to deploy your code to Heroku.
Check for common mistakes like missing Procfile or hardcoded ports.