How to add wildcard routing to cover everything under and including a path with Express.js?

Sometimes, we want to add wildcard routing to cover everything under and including a path with Express.js.

In this article, we’ll look at how to add wildcard routing to cover everything under and including a path with Express.js.

How to add wildcard routing to cover everything under and including a path with Express.js?

To add wildcard routing to cover everything under and including a path with Express.js, we can use the * wildcard character in our route paths.

For instance, we write

const express = require("express")
const app = express.createServer();

const fooRoute = (req, res, next) => {
  res.end("foo route");
}

app.get("/foo*", fooRoute);
app.get("/foo", fooRoute);

app.listen(3000);

to call app.get with "/foo*" to add a route that matches any path that starts with /foo.

The 2nd route we add with app.get matches only the path /foo.

Conclusion

To add wildcard routing to cover everything under and including a path with Express.js, we can use the * wildcard character in our route paths.