Onjsdev

Share


Handling Unmatched Routes in Nodejs


By onjsdev

Jan 29th, 2024

In Node.js with a web framework like Express, you can implement a catch-all route by using a wildcard (*) in the route definition. This route will match any path that hasn't been matched by the previous routes.

Here's an example using Express:

const express = require('express');
const app = express();
const port = 3000;

// Your other routes go here

// Catch-all route
app.get('*', (req, res) => {
  res.status(404).send('Page not found');
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

In the above example, the app.get('*') route will match any GET request that hasn't been matched by the previous routes. It then sends a 404 response with the message "Page not found."

Keep in mind that the order of route declarations matters. The catch-all route should be defined after your specific routes so that they have a chance to match first. If the catch-all route is defined first, it will match all requests, and your specific routes won't be reached.

Conclusion

In conclusion ,using the wildcard (*) in your route definition, you can catch all routes. Depending on your application's needs, in the catch-all route, you can handle various scenarios like sending a custom 404 page or redirecting to a specific page.

Thank you for reading