> ## Documentation Index
> Fetch the complete documentation index at: https://docs.loremstock.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Connecting Node.js to an ES5 or ES6 Express Server

> Understand the difference between ES5 CommonJS and ES6 ESModules syntax and build an Express server with both approaches side by side.

Two module systems exist in Node.js: the original CommonJS (ES5 style) and the modern ES Modules (ES6 style). You will encounter both in real projects. This page builds the same Express server in each style, highlights every syntax difference, and covers the ES6 features you use daily in backend development.

## ES5 vs ES6: Syntax Comparison Table

| Feature           | ES5 (CommonJS)              | ES6 (ES Modules)                       |
| ----------------- | --------------------------- | -------------------------------------- |
| Import            | `const x = require('x')`    | `import x from 'x'`                    |
| Export (default)  | `module.exports = fn`       | `export default fn`                    |
| Export (named)    | `module.exports = { fn }`   | `export { fn }`                        |
| Variables         | `var` (function-scoped)     | `let` / `const` (block-scoped)         |
| Functions         | `function(x) { return x; }` | `(x) => x`                             |
| Strings           | `'Hello ' + name`           | `Hello ${name}`                        |
| Async code        | Callbacks / Promises        | `async/await`                          |
| Destructuring     | `var id = req.params.id`    | `const { id } = req.params`            |
| Enable in Node.js | Default (no config)         | Add `"type": "module"` to package.json |

<Note>
  CommonJS is the default in Node.js. ES Modules need `"type": "module"` in `package.json`. You cannot mix them in the same file.
</Note>

## Install Express

```bash theme={null}
npm install express
```

## Express Server: ES5 (CommonJS)

```javascript theme={null}
// server-es5.js
const express = require('express');
const app = express();
const PORT = 3000;

app.use(express.json());

app.get('/', function(req, res) {
  res.status(200).json({
    message: 'Hello from ES5 server!',
    timestamp: new Date().toISOString()
  });
});

app.get('/users/:id', function(req, res) {
  var userId = req.params.id;
  res.status(200).json({ userId: userId });
});

app.post('/users', function(req, res) {
  var userData = req.body;
  res.status(201).json({ message: 'User created', data: userData });
});

// Error handler (4 params = error middleware)
app.use(function(err, req, res, next) {
  console.error(err.stack);
  res.status(500).json({ error: 'Something went wrong!' });
});

app.listen(PORT, function() {
  console.log('ES5 server running on http://localhost:' + PORT);
});
```

## Express Server: ES6 (ES Modules)

First add to `package.json`:

```json theme={null}
{ "type": "module" }
```

```javascript theme={null}
// server-es6.js
import express from 'express';

const app = express();
const PORT = 3000;

app.use(express.json());

app.get('/', (req, res) => {
  res.status(200).json({
    message: `Hello from ES6 server!`,
    timestamp: new Date().toISOString()
  });
});

app.get('/users/:id', (req, res) => {
  const { id } = req.params;          // Destructuring
  res.status(200).json({ userId: id });
});

app.post('/users', (req, res) => {
  const { body } = req;               // Destructuring
  res.status(201).json({ message: 'User created', data: body });
});

// Error handler
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ error: 'Something went wrong!' });
});

app.listen(PORT, () => {
  console.log(`ES6 server running on http://localhost:${PORT}`);
});
```

## Side-by-Side Comparison

<CodeGroup>
  ```javascript ES5 theme={null}
  const express = require('express');
  const app = express();

  app.use(express.json());

  app.get('/', function(req, res) {
    res.json({ message: 'Hello ES5' });
  });

  app.listen(3000, function() {
    console.log('Running on port 3000');
  });
  ```

  ```javascript ES6 theme={null}
  import express from 'express';

  const app = express();

  app.use(express.json());

  app.get('/', (req, res) => {
    res.json({ message: 'Hello ES6' });
  });

  app.listen(3000, () => {
    console.log(`Running on port 3000`);
  });
  ```
</CodeGroup>

## Core Express Concepts

### The Request-Response Cycle

<Steps>
  <Step title="Client sends request">
    Browser or mobile app sends HTTP request to a URL with a method (GET, POST...).
  </Step>

  <Step title="Express matches route">
    Express checks registered routes for a matching path and method.
  </Step>

  <Step title="Middleware runs">
    Each registered `app.use()` function runs in order before the route handler.
  </Step>

  <Step title="Route handler executes">
    The matched handler runs business logic and queries the database.
  </Step>

  <Step title="Response sent">
    Handler calls `res.json()`, `res.send()`, or `res.status().json()` to respond.
  </Step>
</Steps>

### Essential Express Methods

| Method                      | What it does                          |
| --------------------------- | ------------------------------------- |
| `app.listen(port, cb)`      | Starts the server on the given port   |
| `app.get(path, handler)`    | Handles GET requests to `path`        |
| `app.post(path, handler)`   | Handles POST requests                 |
| `app.put(path, handler)`    | Handles PUT requests                  |
| `app.delete(path, handler)` | Handles DELETE requests               |
| `app.use(middleware)`       | Registers middleware for ALL requests |

### req and res Objects

```javascript theme={null}
app.post('/users', (req, res) => {
  // --- Reading the request ---
  req.body         // Parsed JSON body (needs express.json())
  req.params.id    // URL path parameter (:id in the route)
  req.query.page   // Query string ?page=2
  req.headers      // Request headers

  // --- Sending the response ---
  res.status(201).json({ id: 1, name: 'Alice' });
  res.status(404).json({ message: 'Not found' });
  res.status(204).send();
});
```

## ES6 Features Used Daily in Node.js

### Arrow Functions

```javascript theme={null}
// Traditional function
const add = function(a, b) { return a + b; };

// Arrow function
const add = (a, b) => a + b;

// Arrow function with block body
const greet = (name) => {
  return `Hello, ${name}!`;
};
```

### Template Literals

```javascript theme={null}
const name = 'Alice';
const port = 3000;

// ES5
console.log('Server started on port ' + port + ' for ' + name);

// ES6
console.log(`Server started on port ${port} for ${name}`);
```

### Destructuring

```javascript theme={null}
// Object destructuring
const user = { id: 1, name: 'Bob', email: 'bob@test.com' };
const { id, name, email } = user;

// In route handler
app.get('/users/:id', (req, res) => {
  const { id } = req.params;
  const { page = 1, limit = 10 } = req.query;  // with defaults
});
```

### Spread Operator

```javascript theme={null}
const defaults = { port: 3000, host: 'localhost' };
const config = { ...defaults, port: 8080 };
// Result: { port: 8080, host: 'localhost' }
```

### async/await

```javascript theme={null}
// With Promises (older style)
app.get('/users', (req, res) => {
  User.find()
    .then(users => res.json(users))
    .catch(err => res.status(500).json({ error: err.message }));
});

// With async/await (cleaner)
app.get('/users', async (req, res) => {
  try {
    const users = await User.find();
    res.json(users);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});
```

<Note>
  `async/await` is syntactic sugar over Promises. An `async` function always returns a Promise. `await` pauses execution until the Promise resolves. Always wrap `await` in `try/catch`.
</Note>

## Error Handling in Express

### Centralized Error Handler (must be LAST)

```javascript theme={null}
// Place this after all routes
app.use((err, req, res, next) => {
  console.error('Error:', err.message);

  const statusCode = err.statusCode || 500;
  res.status(statusCode).json({
    success: false,
    error: err.message || 'Internal Server Error',
    // Show stack trace only in development
    ...(process.env.NODE_ENV === 'development' && { stack: err.stack })
  });
});
```

### Passing Errors from Async Routes

```javascript theme={null}
app.get('/users', async (req, res, next) => {
  try {
    const users = await User.find();
    res.json(users);
  } catch (err) {
    next(err); // Pass to Express error handler
  }
});
```

## Key Terms

| Term                       | Definition                                                                        |
| -------------------------- | --------------------------------------------------------------------------------- |
| **CommonJS**               | Node.js's original module system using `require()` and `module.exports`.          |
| **ESModules**              | Modern standard using `import` and `export`. Needs `"type":"module"`.             |
| **Middleware**             | A function that runs between request arrival and response sending.                |
| **Request-response cycle** | The complete HTTP flow from client request to server response.                    |
| **Port**                   | A number identifying which process should receive a network request (e.g., 3000). |
| **Route**                  | A URL path + HTTP method combination mapped to a handler function.                |
| **Handler**                | The callback function that runs when a route matches. Receives `req` and `res`.   |

## Common Mistakes

<Accordion title="Mixing require() and import">
  Once you add `"type": "module"`, all .js files must use `import`. If one file uses `require()`, rename it to `.cjs`.
</Accordion>

<Accordion title="Forgetting express.json()">
  Without `app.use(express.json())`, `req.body` is `undefined` for POST and PUT requests. This is the most common beginner error.
</Accordion>

<Accordion title="Not returning after res.send()">
  Always `return res.status(404).json(...)` to exit the function. Without `return`, Express tries to send two responses and crashes with "headers already sent."
</Accordion>

<Accordion title="Error handler with wrong number of params">
  Error handling middleware must have exactly 4 parameters: `(err, req, res, next)`. With 3 params, Express treats it as a normal middleware and errors bypass it.
</Accordion>
