Upgrading to Express.js 5: What’s New and How to Migrate

What’s New in Express.js 5?

Express.js 5 introduces several significant changes and improvements, including:

  • Path Route Matching Syntax: The way path strings are matched to incoming requests has been updated.
  • Rejected Promises and Middleware Handlers: Any rejected promise or error thrown from middleware or handlers is forwarded as an error to the error handling middleware.
  • Return of the app.router Object: The app.router object has been brought back in Express 5.
  • Port Maintained in req.host Object: The port number is now maintained in the req.host object.
  • req.query Object Changed to Getter: The req.query property has been changed from a writable property to a getter.

Migrating an Express 4 App to Express 5

Migrating an existing Express 4 app to Express 5 is relatively straightforward. To get started, update your project dependencies by running the following command:

npm install express@5

Next, rebuild your project or rerun your tests to determine if anything failed. Use the updates covered in this article to fix any issues that may have occurred.

Step-by-Step Demo: Creating a Web App in Express 5

In this demo, we’ll create a simple web app using Express 5.

    1. Create a new project directory and initialize a new Node.js project:
mkdir my-express-app
cd my-express-app
npm init -y
    1. Install Express 5:
npm install express@5
    1. Create a new file called `app.js` and add the following code:
const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(3000, () => {
  console.log('Server started on port 3000');
});
    1. Start the server:
node app.js
  1. Open a web browser and navigate to `http://localhost:3000/` to see the “Hello World!” message.

Leave a Reply

Your email address will not be published. Required fields are marked *