Back to Snippets
Node.jsTypeScript

Node.js Express Middleware

A set of reusable Express middleware functions for logging, error handling, and CORS.

nodejsexpressmiddlewareapi
import express, { Request, Response, NextFunction } from class=class="text-emerald-400">"text-emerald-400">'express'

class=class="text-emerald-400">"text-gray">// Request logger
function logger(req: Request, _res: Response, next: NextFunction) {
  console.log(class="text-emerald-400">`${new Date().toISOString()} ${req.method} ${req.path}`)
  next()
}

class=class="text-emerald-400">"text-gray">// Async handler wrapper — catches errors automatically
function asyncHandler(fn: (req: Request, res: Response, next: NextFunction) => Promise<void>) {
  return (req: Request, res: Response, next: NextFunction) => {
    fn(req, res, next).catch(next)
  }
}

class=class="text-emerald-400">"text-gray">// Global error handler
function errorHandler(err: Error, _req: Request, res: Response, _next: NextFunction) {
  console.error(err.stack)
  res.status(500).json({ error: err.message || class=class="text-emerald-400">"text-emerald-400">'Internal Server Error' })
}

const app = express()
app.use(logger)
app.get(class=class="text-emerald-400">"text-emerald-400">'/api/data', asyncHandler(async (_req, res) => {
  const data = await fetchData()
  res.json(data)
}))
app.use(errorHandler)

How to Use

Use the logger middleware globally with app.use(). Wrap async route handlers with asyncHandler() to avoid try-catch blocks. Place errorHandler last — Express calls it when next(error) is invoked.

Related Technology

Node.js

Have a Project in Mind?

Let's discuss how we can bring your idea to life. From initial concept to production-ready product — we've got you covered.

or book a free call