Node.jsExpressError Fix2026 Updated

Node.js Server Crashing Automatically— Fixed [Complete Guide 2026]

January 20267 min readNode.js · All OS

⚡ First Step — Find the Crash Cause

Add these two lines at the very top of your entry file to log exactly what is crashing:

server.js — add as line 1 and 2
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 typeWhat you seeFix
Unhandled promise rejectionUnhandledPromiseRejectionWarningJump →
Uncaught exceptionError message then process exitsJump →
Express route errorServer crashes on specific requestsJump →
Async route without try/catchCrash when route throwsJump →
Memory overflowFATAL ERROR: CALL_AND_RETRY_LAST Allocation failedJump →
Database connection dropMongoNetworkError or similar then crashJump →
1

Handle Unhandled Promise Rejections

Most common crash cause in modern Node.js
3 min

In 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.

Terminal Error
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.js

Add a global unhandledRejection handler

server.js — top of file
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

routes/data.js
// 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.

2

Catch Uncaught Exceptions

Synchronous errors outside try/catch
2 min

Uncaught exceptions are synchronous errors that were not caught by any try/catch block. They crash the process immediately.

server.js — top of file
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.

3

Add Express Error Middleware

Express route errors crashing the server
2 min

Without 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.

server.js — add LAST, after all routes
// ✅ 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.

4

Fix Async Route Handlers

Every async route needs try/catch
3 min

Every 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

routes/users.js
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)

utils/asyncHandler.js
// Utility that wraps async handlers automatically
const asyncHandler = (fn) => (req, res, next) =>
  Promise.resolve(fn(req, res, next)).catch(next)

module.exports = asyncHandler
routes/users.js
const 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)
}))
5

Use PM2 for Auto-Restart in Production

Production — keep server alive after crashes
5 min

PM2 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.

terminal
# 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 save

PM2 ecosystem file (recommended)

ecosystem.config.js
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.js

max_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.

6

Fix Memory-Related Crashes

FATAL ERROR: Allocation failed — JavaScript heap
5 min
Terminal Error
FATAL 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

terminal / package.json
# 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

server.js — monitor memory
// 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
7

Fix Database Connection Crashes

Server crashes when DB disconnects
3 min

If 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

server.js
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

server.js
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:

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?+
The most common causes are unhandled promise rejections, uncaught exceptions, or out-of-memory errors. Add process.on('uncaughtException') and process.on('unhandledRejection') handlers at the top of your entry file to log the exact crash cause.
How do I keep Node.js running after a crash?+
Use PM2: npm install -g pm2, then pm2 start server.js. PM2 automatically restarts your app when it crashes and logs the crash reason. It also starts your app on system reboot.
Node.js server exits without any error message — why?+
Add these handlers to see the hidden error: process.on('uncaughtException', console.error) and process.on('unhandledRejection', console.error). The crash reason will now be logged before the process exits.
How do I handle errors in Express so the server does not crash?+
Add error middleware as the LAST middleware: app.use((err, req, res, next) => { console.error(err); res.status(500).json({ error: err.message }) }). This catches all Express route errors.
Node.js crashes on production but not locally — why?+
Common production-only causes: different environment variables, less available memory, more concurrent requests revealing race conditions, different Node.js version, or a missing .env configuration. Check production logs with pm2 logs.
How do I monitor Node.js crashes in production?+
Use PM2 (pm2 logs, pm2 monit) for basic monitoring. For production-grade monitoring, use tools like Sentry (error tracking), Datadog, or New Relic to capture crash data with full context.

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