All posts

Fix NotFoundError in Express When Deploying

Resolve 404 errors when deploying Express.js applications, covering route ordering, static file serving, and reverse proxy configuration.

Express.js 404 Errors After Deployment

Express routes that work locally but return 404 in production usually indicate route ordering issues, missing static file configuration, or reverse proxy mismatches.

Route Order Matters

Express matches routes in registration order. A catch-all before specific routes swallows everything:

// BAD — catch-all before API routes
app.get('*', (req, res) => res.sendFile('index.html'));
app.get('/api/users', getUsers); // Never reached!

// GOOD — specific routes first
app.get('/api/users', getUsers);
app.get('/api/posts', getPosts);
// Catch-all LAST
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

Static Files Not Found

// Make sure the path is absolute and correct
app.use(express.static(path.join(__dirname, 'public')));

// In Docker, __dirname might be different
// Verify: console.log('Static path:', path.join(__dirname, 'public'));

Reverse Proxy Prefix

If the app is behind a proxy at /api/:

// Nginx: proxy_pass http://localhost:3000/;
// Note the trailing slash — it strips the prefix

// Or handle it in Express:
app.use('/api', router);

Trust Proxy

app.set('trust proxy', 1);
// Needed for correct req.ip, req.protocol behind a proxy

404 Handler

// Must be after all other routes
app.use((req, res) => {
  res.status(404).json({ error: 'Route not found', path: req.path });
});

Bugsly captures Express 404 errors with the full request path, method, and headers, helping you identify which routes are missing in production.

Try Bugsly Free

AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.

Get Started Free