How express() Works Internally in Node.js

Express is a popular backend web framework built on top of Node.js that simplifies routing, middleware, and server creation. To understand Express better, let’s see a simplified internal version of how express() might work.

🧠 What is express()?

The express() function returns an application object (usually named app) that gives access to important methods like:

So when we use:
const app = express();
We are actually creating an object that stores routes and can run a server.

πŸ“¦ Why do we use express()?

βš™ How Does It Work Internally?

// pretend this is inside express.js

function express() {

  const app = {};

  // storing all routes here
  app.routes = [];

  // add GET route creator
  app.get = function(path, handler) {
    app.routes.push({ method: "GET", path, handler });
  };

  // add POST route creator
  app.post = function(path, handler) {
    app.routes.push({ method: "POST", path, handler });
  };

  // method to start the server
  app.listen = function(port, callback) {

    // internally uses Node http server
    const http = require("http");

    const server = http.createServer((req, res) => {

      const matchedRoute = app.routes.find(
        r => r.method === req.method && r.path === req.url
      );

      if (matchedRoute) {
        matchedRoute.handler(req, res);
      } else {
        res.end("Route Not Found");
      }
    });

    server.listen(port, callback);
  };

  return app;  // <--- this is what express() returns
}

module.exports = express;

πŸ“ Summary