Modularizing Routes in Express Using the Router Object
Learn how to modularize Express routes using the Router object for better code organization.
We'll cover the following
A large-scale web application would have many different paths for many different
web pages. We may have a /login
URL path to render a login page and a /products
URL path to show a list of products, for example. Each of these URLs may have to handle GET requests, POST requests, PUT requests, DELETE requests, or PATCH requests. If we had an application that had hundreds of endpoints, then having each handler of an Express application within the same file would quickly become a maintenance nightmare.
Express provides a Router
object that can be used to split these routes into separate files in such a way that all requests that use the /login
URL, for example, can be handled by code within a single file, and all requests for /products
can be handled by code within another file.
Let’s create a routes
directory within our application and create two route files named index.ts
and login.ts
to explore this technique.
The index.ts
route file
First, let’s look at the index.ts
file:
Get hands-on with 1400+ tech skills courses.