How to Deploy Node.js Application: Simple Steps and Example
To deploy a
Node.js application, you first prepare your app with a package.json and entry file, then upload it to a server or cloud platform like Heroku or Vercel. Finally, you start the app using node or a process manager like PM2 to keep it running.Syntax
Deploying a Node.js app involves these key steps:
- Prepare app files: Your main file (e.g.,
app.js) andpackage.jsonlisting dependencies. - Upload to server: Copy files to a hosting service or cloud platform.
- Install dependencies: Run
npm installon the server to get needed packages. - Start app: Use
node app.jsor a process manager likepm2 start app.jsto run your app continuously.
bash
node app.js # or using PM2 pm2 start app.js
Example
This example shows a simple Node.js app deployed locally and started with node. It listens on port 3000 and responds with 'Hello World'.
javascript
const http = require('http'); const port = 3000; const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello World'); }); server.listen(port, () => { console.log(`Server running at http://localhost:${port}/`); });
Output
Server running at http://localhost:3000/
Common Pitfalls
Common mistakes when deploying Node.js apps include:
- Not running
npm installon the server, causing missing modules. - Starting the app with
nodewithout a process manager, so the app stops if the terminal closes. - Not setting environment variables like
PORT, causing the app to fail on some hosts. - Forgetting to add a
startscript inpackage.json, which some platforms require.
json
/* Wrong: No start script in package.json */ { "name": "myapp", "version": "1.0.0", "dependencies": {} } /* Right: Add start script */ { "name": "myapp", "version": "1.0.0", "scripts": { "start": "node app.js" }, "dependencies": {} }
Quick Reference
Tips for smooth Node.js deployment:
- Always include a
startscript inpackage.json. - Use
PM2or similar to keep your app running. - Set environment variables like
PORTproperly. - Test your app locally before deploying.
- Choose a hosting platform that fits your needs (Heroku, Vercel, DigitalOcean, etc.).
Key Takeaways
Prepare your Node.js app with a main file and package.json before deployment.
Upload your app to a server and run npm install to get dependencies.
Use a process manager like PM2 to keep your app running continuously.
Set environment variables like PORT to ensure your app listens correctly.
Include a start script in package.json for easier deployment on platforms.