Web DevelopmentWordPress VIP or Self Hosted Enterprise WordPress in the UAEWordPress VIP or self hosted enterprise WordPress in the UAE: compare data residency, hosting SLA, cost drivers and code review rules, plus key setup notes.Node.js Middleware Explained With Real Business Use Cases
Node JS middleware explained through real business cases: authentication, logging, rate limiting, Arabic locale detection and error handling in Express apps.

Node JS middleware is a function that sits between an incoming request and your route handler, where it can read or change the request, end the response, or pass control on. In Express, that is how production apps handle authentication, logging, rate limiting, language detection and errors without repeating the same code in every route. The patterns below show how each one maps to a real business need.
How Node JS middleware works in Express
The Express guide describes middleware as functions that can execute code, modify the request and response, end the cycle or call next. If a function neither ends the response nor calls next, the request hangs. That single rule explains most middleware bugs seen in maintenance work.
The five kinds you will meet
- Application level: attached with app.use, runs for every matching request.
- Router level: attached to an Express router, useful for grouping rules for an admin area or an API version.
- Error handling: takes four arguments (err, req, res, next) instead of three.
- Built in: such as express.json for parsing request bodies and express.static for files.
- Third party: packages from npm for security headers, cookies, sessions and similar tasks.
Order is behaviour
Express runs middleware in the order it is registered. A typical production order is: request ID and logging, security headers, body parsing, rate limiting, locale detection, authentication, routes, then a 404 handler and finally the error handler. Moving authentication below a route that should be protected is enough to expose it.
Express middleware for business use cases
Each pattern below starts with the business problem, then describes the middleware that solves it.
Request logging with a correlation ID
Problem: a customer in Sharjah reports that checkout failed, and support cannot find the matching server error among thousands of log lines.
Solution: a small piece of custom middleware at the top of the stack generates a unique ID for each request, attaches it to the request object, adds it to a response header and includes it in every log line. When the customer shares the reference shown on the error page, support can trace the full request across services. Log the method, path, status and duration, but never passwords, card details or full identity numbers.
Authentication middleware
Problem: an internal dashboard and a customer portal share one API, and each route checks tokens slightly differently.
Solution: one authentication middleware reads the session cookie or bearer token, verifies it, loads the user and attaches it to the request. If verification fails, it ends the response with a 401 status. A second, smaller middleware checks roles, so a route can require "finance" or "admin" without repeating the token logic. Mount these at router level so the public marketing API stays open while the admin router is protected as a whole.
Rate limiting
Problem: a contact form or OTP endpoint is being hit by bots, raising SMS costs and filling the CRM with junk leads.
Solution: rate limiting middleware counts requests per client over a time window and returns a 429 status when the limit is exceeded. Apply strict limits to login, OTP and form endpoints and looser ones to general browsing. Use a shared store such as Redis when the app runs on more than one server, otherwise each instance counts separately.
One trap catches many teams. Behind a load balancer or CDN, every request appears to come from the proxy's address. The Express documentation explains that enabling the trust proxy setting makes req.ip use the X-Forwarded-For header instead, but warns to enable it only when your proxy overwrites that header. Otherwise clients can spoof their address and bypass the limit.

Arabic and English locale detection
Problem: a bilingual app serves English and Arabic, and users land in the wrong language or lose their choice between pages.
Solution: locale middleware decides the language once per request and attaches it to the request, so routes, templates and error messages all read the same value. A sensible order of precedence is:
- An explicit choice in the URL, such as an /ar/ path prefix.
- A saved preference in a cookie or the user's profile.
- The browser's Accept-Language header.
- A default, usually English.
MDN describes Accept-Language as a hint that should never override an explicit user choice, which is why it sits third in the list. The middleware should also set a direction value (right to left for Arabic) so templates apply the correct layout, and add a Vary header for Accept-Language if responses differ by language and are cached.
Error handling middleware that protects customers and data
Error handling middleware is the last line of defence. Express identifies it by its four arguments and expects it to be registered after all routes. Its job is to log the full error internally, return a safe and consistent response to the client, and never leak stack traces or database details.
What a good error handler does
- Maps known errors (validation, not found, forbidden) to the right status code and a clear message in the user's language.
- Returns a generic message and the request ID for unexpected errors.
- Sends serious errors to your monitoring tool with the request ID attached.
- Checks whether headers have already been sent, and if so hands over to the default handler.
Express 5 simplifies this. According to the Express error handling guide, async handlers and middleware that throw or return a rejected promise pass the error to next automatically. In older Express 4 apps, developers had to wrap async code in try and catch blocks or a helper, and missing one could crash the process. If you maintain an Express 4 app, auditing async routes for unhandled rejections is a worthwhile task before any upgrade.
Writing custom middleware that stays maintainable
Custom middleware is easy to write and easy to overuse. A few habits keep it manageable:
- One job per function. Separate authentication from role checks, and logging from metrics.
- Configure through factories. A function that returns middleware, for example a role checker that takes the allowed roles, avoids copies with small differences.
- Keep it fast. Middleware on every request should avoid slow database calls; cache what you can.
- Document the order. A short comment block listing the stack in order saves the next developer real time.
Hypothetical example: a Dubai logistics company has an Express API serving a customer tracking page and a driver app. Logging, rate limiting and locale run for all traffic. The driver router adds token authentication and a role check, while the public tracking route uses only a strict rate limit. One error handler at the end returns bilingual messages with a request ID that support staff can search.
A quick audit checklist for an existing app
- List the middleware stack in order and confirm protected routes sit after authentication.
- Check that trust proxy matches your actual hosting setup.
- Confirm rate limits on login, OTP, password reset and form endpoints.
- Search logs for personal data that should not be there.
- Verify the error handler hides internal details in production.
- Test both languages, including right to left layout and error messages.
For background on how applications differ from simpler sites, see our guide to static or dynamic websites, and for the build decision itself, template or custom design. Budgeting for the work is covered in website design cost in Dubai.
Get help with your Node.js application
Codeeo has delivered 200+ projects across the UAE and the US. Our web development team builds and maintains Node.js and Express applications, and our custom software practice handles the business systems behind them. If you need ongoing capacity for audits, upgrades or new features, dedicated developers can work inside your process. Contact us with a short description of your app, or meet the team at our Dubai office.
Frequently asked questions
No.
The idea of a chain of functions that process a request appears in many frameworks, including Koa, Fastify and Next.js, though each implements it differently. Fastify uses hooks and plugins, and Next.js runs a single request interceptor before routes. The business patterns in this article (authentication, logging, rate limiting, locale and errors) carry across; only the syntax and registration change.
Tell us what the business needs. We will tell you what to build first.
Schedule a free consultation and get a written recommendation, with costs, before you commit to anything.
Get in touchPROVEN RESULTS

