Node.js Server Crashing Automatically— Fixed [Complete Guide 2026]
⚡ First Step — Find the Crash Cause
Add these two lines at the very top of your entry file to log exactly what is crashing:
process.on('uncaughtException', (err) => console.error('CRASH:', err))
process.on('unhandledRejection', (reason) => console.error('REJECTION:', reason))Restart your server — the crash message will now appear in your logs. Fix the underlying error, then implement proper error handling from the fixes below.
Find the Crash Cause First
A Node.js server crashes for a reason. Every crash. The process exits because it encountered an error it did not know how to handle — and without proper error handlers, that reason disappears silently. The first step is always making the crash visible.
| Crash type | What you see | Fix |
|---|---|---|
| Unhandled promise rejection | UnhandledPromiseRejectionWarning | Jump → |
| Uncaught exception | Error message then process exits | Jump → |
| Express route error | Server crashes on specific requests | Jump → |
| Async route without try/catch | Crash when route throws | Jump → |
| Memory overflow | FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed | Jump → |
| Database connection drop | MongoNetworkError or similar then crash | Jump → |
Handle Unhandled Promise Rejections
Most common crash cause in modern Node.jsIn Node.js 15+, unhandled promise rejections crash the process immediately. Before that they were just warnings. This is the most common reason modern Node.js apps crash after running fine for a while.
UnhandledPromiseRejectionWarning: MongoNetworkError: connect ECONNREFUSED
(Use `node --trace-warnings ...` to show where the warning was created)
node:internal/process/promises:279
triggerUncaughtException(err, true /* fromPromise */);
[1] + 1234 killed node server.jsAdd a global unhandledRejection handler
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise)
console.error('Reason:', reason)
// Log to error tracking service (Sentry etc.) here
// Do NOT crash the process — log and continue
})But also fix the underlying async code
// WRONG — unhandled rejection if fetchData() rejects
app.get('/data', async (req, res) => {
const data = await fetchData() // if this throws → crash!
res.json(data)
})
// CORRECT — catch the error
app.get('/data', async (req, res) => {
try {
const data = await fetchData()
res.json(data)
} catch (err) {
console.error('Route error:', err)
res.status(500).json({ error: 'Failed to fetch data' })
}
})The global handler is a safety net, not a substitute for try/catch in async functions. Always add try/catch to every async route handler.
Catch Uncaught Exceptions
Synchronous errors outside try/catchUncaught exceptions are synchronous errors that were not caught by any try/catch block. They crash the process immediately.
process.on('uncaughtException', (err) => {
console.error('Uncaught Exception:', err)
console.error(err.stack)
// Optionally: send alert, log to service, graceful shutdown
// process.exit(1) // uncomment if you want to force restart via PM2
})Common sources of uncaught exceptions
- JSON.parse() on invalid data — wrap in try/catch
- fs.readFileSync() on a file that does not exist
- Accessing a property of undefined or null
- Throwing inside a synchronous event handler
Do not use uncaughtException as a general error suppressor. It should log the error and ideally restart the process via PM2. A process that caught an uncaught exception is in an unknown state and should not be trusted to continue.
Add Express Error Middleware
Express route errors crashing the serverWithout error middleware, an error thrown in an Express route propagates to Node.js as an uncaught exception and crashes the whole server. Error middleware catches these before they escape.
// ✅ Add this AFTER all your route definitions
app.use((err, req, res, next) => {
console.error('Express error:', err.message)
console.error(err.stack)
// Send clean error response — no crash
res.status(err.status || 500).json({
error: process.env.NODE_ENV === 'production'
? 'Internal server error'
: err.message
})
})
// Catch 404 — add before error middleware
app.use((req, res) => {
res.status(404).json({ error: 'Route not found' })
})Express error middleware must have FOUR parameters: (err, req, res, next). If you write only three, Express will not recognize it as error middleware.
Fix Async Route Handlers
Every async route needs try/catchEvery async Express route handler needs a try/catch. Without it, any rejected promise inside the handler becomes an unhandled rejection and crashes the server.
Option A — try/catch in every handler
app.get('/users', async (req, res) => {
try {
const users = await User.find()
res.json(users)
} catch (err) {
next(err) // passes to Express error middleware
}
})
app.post('/users', async (req, res, next) => {
try {
const user = await User.create(req.body)
res.status(201).json(user)
} catch (err) {
next(err)
}
})Option B — async wrapper utility (cleaner)
// Utility that wraps async handlers automatically
const asyncHandler = (fn) => (req, res, next) =>
Promise.resolve(fn(req, res, next)).catch(next)
module.exports = asyncHandlerconst asyncHandler = require('../utils/asyncHandler')
// No try/catch needed — asyncHandler catches rejections
app.get('/users', asyncHandler(async (req, res) => {
const users = await User.find()
res.json(users)
}))
app.post('/users', asyncHandler(async (req, res) => {
const user = await User.create(req.body)
res.status(201).json(user)
}))Use PM2 for Auto-Restart in Production
Production — keep server alive after crashesPM2 is a production process manager for Node.js. Even after fixing crash causes, production apps will sometimes encounter unexpected errors. PM2 catches crashes, logs them, and automatically restarts the app.
# Install PM2 globally
npm install -g pm2
# Start your app
pm2 start server.js --name my-app
# Auto-restart on crash with delay
pm2 start server.js --name my-app --restart-delay=3000
# View running apps
pm2 list
# View logs including crash logs
pm2 logs my-app
pm2 logs my-app --lines 200
# Monitor in real-time
pm2 monit
# Restart / stop
pm2 restart my-app
pm2 stop my-app
# Start on system boot
pm2 startup
pm2 savePM2 ecosystem file (recommended)
module.exports = {
apps: [{
name: 'my-app',
script: 'server.js',
instances: 'max', // use all CPU cores
exec_mode: 'cluster',
watch: false,
max_memory_restart: '500M',
env: {
NODE_ENV: 'production',
PORT: 3000
},
error_file: 'logs/error.log',
out_file: 'logs/output.log',
log_file: 'logs/combined.log',
}]
}
// Start with: pm2 start ecosystem.config.jsmax_memory_restart: '500M' tells PM2 to automatically restart the app if it uses more than 500MB of memory — preventing memory leak crashes from taking down the server permanently.
Fix Memory-Related Crashes
FATAL ERROR: Allocation failed — JavaScript heapFATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory
1: 0xb7c9e0 node::Abort() [node]
2: 0xa93510 node::FatalError(char const*, char const*) [node]
Aborted (core dumped)Increase heap size
# Run with increased memory
node --max-old-space-size=2048 server.js # 2GB
# In package.json scripts
{
"scripts": {
"start": "node --max-old-space-size=2048 server.js"
}
}
# With PM2
pm2 start server.js --node-args="--max-old-space-size=2048"Find memory leaks
// Log memory usage every 30 seconds
setInterval(() => {
const mem = process.memoryUsage()
console.log({
heapUsed: Math.round(mem.heapUsed / 1024 / 1024) + ' MB',
heapTotal: Math.round(mem.heapTotal / 1024 / 1024) + ' MB',
rss: Math.round(mem.rss / 1024 / 1024) + ' MB',
})
}, 30000)- Close database connections when no longer needed
- Clear intervals and timeouts when they finish
- Avoid storing large arrays in memory — use streams for large files
- Remove event listeners when components unmount or are destroyed
Fix Database Connection Crashes
Server crashes when DB disconnectsIf your database goes down or the connection drops, unhandled errors from pending queries will crash the server. Implement reconnection logic and error handling.
Mongoose — handle connection drops
mongoose.connect(process.env.MONGODB_URI)
mongoose.connection.on('error', (err) => {
console.error('MongoDB connection error:', err)
// Don't crash — log and attempt reconnect
})
mongoose.connection.on('disconnected', () => {
console.log('MongoDB disconnected — attempting reconnect...')
setTimeout(() => {
mongoose.connect(process.env.MONGODB_URI)
}, 5000)
})Add connection timeout and retry
const connectWithRetry = async () => {
try {
await mongoose.connect(process.env.MONGODB_URI, {
serverSelectionTimeoutMS: 5000,
})
console.log('MongoDB connected')
} catch (err) {
console.error('MongoDB connection failed:', err.message)
console.log('Retrying in 5 seconds...')
setTimeout(connectWithRetry, 5000)
}
}
connectWithRetry()Prevention — The Definitive Checklist
A production Node.js app should never crash permanently. Here is the complete set of defensive patterns that protect against every crash type:
- Add process.on('uncaughtException') and process.on('unhandledRejection') handlers
- Wrap every async route handler in try/catch or use an asyncHandler utility
- Add Express error middleware as the last middleware (4 parameters)
- Use PM2 in production with max_memory_restart configured
- Implement database reconnection logic — never crash on DB disconnect
- Set NODE_ENV=production to disable stack traces in error responses
- Use a logging library (winston, pino) with file output for persistent crash logs
- Set up error tracking (Sentry, Datadog) to get alerts when crashes occur in production
- Add health check endpoints so load balancers can detect unhealthy instances
Complete crash-proof server template
// server.js — crash-proof boilerplate
process.on('uncaughtException', (err) => {
console.error('UNCAUGHT EXCEPTION:', err)
process.exit(1) // let PM2 restart
})
process.on('unhandledRejection', (reason) => {
console.error('UNHANDLED REJECTION:', reason)
})
require('dotenv').config()
const express = require('express')
const app = express()
app.use(express.json())
// Your routes here...
// Error middleware — LAST
app.use((err, req, res, next) => {
console.error(err)
res.status(500).json({ error: 'Internal server error' })
})
const server = app.listen(process.env.PORT || 3000, () => {
console.log('Server running')
})
// Graceful shutdown
process.on('SIGTERM', () => server.close(() => process.exit(0)))Frequently Asked Questions
Why does my Node.js server keep crashing?+−
How do I keep Node.js running after a crash?+−
Node.js server exits without any error message — why?+−
How do I handle errors in Express so the server does not crash?+−
Node.js crashes on production but not locally — why?+−
How do I monitor Node.js crashes in production?+−
Need Expert Help?
We Build Production-Grade Node.js Apps
Softplix builds stable, scalable Node.js backends for startups and enterprises. Dealing with production crashes? We can fix your error handling architecture.
Talk to an Engineer