Introduction to Express - Express Router
In this course, you will learn about Express Router and how to create modular routes to create organized and maintainable code.
- Understand how express.Router() is used to create a router instance
- Learn how to refactor and organize resource-specific route paths into router instances
- Learn how to configure a router instance as middleware
- Learn how the route path is configured when using router instances as middleware
- This course is intended for anyone who wants to learn about Express
Introduction to Express - Express Router. Express Router is a way to create modular, mountable route handlers. The router instance is a complete Express middleware and routing system that is often referred to as a mini app. Going over to the lab environment, I have the server.js file on the screen. Inside of this file, I have three routes; two routes for customer resources and one route for user resources. On the right side of the screen, I will demonstrate that these routes work using Insomnia. The first route will be for the user resources. And this route will respond back with all the users. The second route is for the customer resources. And this route will respond back with all the customers. The third route will be for the customer resources. And when give it a customer ID, this route will respond back with the customer that has the matching ID.
Now, these routes work, but there is one point I want to make before continuing further. The number of routes using this video is on a much smaller scale for teaching purposes. In real-world scenarios, the amount of API resources offered by an application would be on a larger scale. For example, if there was five different resources and create routes for each specific resource, that would lead to the creation of 20 different routes, overloading the server.js file with code. A modular approach using Express Router would lead to better organization and cleaner code for each resource by using the router instance for this specific application on the screen. This would mean delegating each classic resource, customer, and user to a router instance.
To begin, I'm going to create a routes folder. Inside of the folder, I will create three files; a customers.js file, a users.js file, and an index.js file. Next, I'm going to cut the existing customer routes from the server.js file, opening up the customers.js file. To set up express router, you need to require it. const router = require ("express").Router (). This router execution method attached to the end of Express is what creates the special router instance, which is also referred to as the router object. Now, for the data, I'm using two JSON files to act as a database, one for customers and another one for users. I'm going to import the customer's data. const customers = require, and inside of the required statement, the relative path to the customers.json file.
Next, I'm going to paste in the two routes that I had cut from the server.js file. Now, both routes begin with app.get. Earlier in the video, I mentioned that Express Router is a complete middleware and routing system. Because of this, I can replace app with router for both of these routes and the route handlers with both get methods will work as before. Next, both these routes refer to customers, one with api/customers, the other with api/customers/route parameter, customer id. Once I complete the use of Express Router, any route in this file by default will refer to /customers. Because of this upcoming change, I need to refactor the route paths to reflect this. For the first route, I will remove api/customers and just leave a forward (/), as this will be the root route, the /customers. For the second route, I will just leave the /customer id route parameter. Later on, this will be referring to as /customers: customer id.
And that's it for the route refactoring. The last thing I need to do is make this router object available throughout the application. So, I need to export it. module.exports = router. Now, that the customers' resource is done, I need to go over to that index.js file that I created inside of the routes folder. I will use this as the main entry point for all the router instances created within this folder. Once again, I need to import the Express Router object. In order to do this, const router = require ("express").Router. Next, I need to require the customer routes that I created inside of the customers.js file. const customerRoutes = require and the relative path of the customers.js file. Now, this router and these routes are middleware. And I want to use this middleware in conjunction with these customer routes whenever the endpoint /customers is requested.
The key word being "use," I will type router.use, and the first argument is the route path, /customers. The second argument is the customer routes. Now, with this code, this use of the middleware, I'm stating that any requests that refers to /customers will refer to the routes inside of the customers.js file. Now, you may be wondering, wasn't there supposed to be a /api as part of this route as showed earlier in the video? That will be handled towards the end of the video. As part of this file, I also need to export the router. module.exports = router. Now, I need to repeat the process for the users route. Going to the server.js file, I'm going to cut the remaining users route. Inside of the users.js file, I will once again require the router. const router = require ("express").Router. This is repetitive, but each file needs to represent its own instance of the router. Next, I will require the users' data from the users.json file. const users = require and the relative path to the users.json file. Next, I'm going to paste in the users route that I copied from the server.js file. And just like with the customer routes, I'm going to replace app with router for the users route. I will also change the route path from api/users to just forward slash (/). This route will represent the /users route after requiring the route inside of the index.js file.
Lastly, I need to export the router instance. module.exports = router. Going back to that index.js file, I need to import the user route. const userRoutes = require, the relative path of the users.js file. Once again, I need to use the user routes. router.use, and the first argument will be /users, which will be the base route path for any routes inside of this users.js file, followed by user routes. Now, this completes the users route. And I've already exported the router earlier when I set the customer routes. So, there's no point in doing that again. I have two router instances, one for each resource, ready to be used. The last step is now to bring these routes into the server.js file. Going to the file, I'm going to import the routes created with the router. const routes = require and the relative path of the routes folder. I do not need to include the index.js file as part of this path as that is the default file. Now that I've imported the routes, I need to use the routes, app.use, not router, because I'm not using the router instance in the server.js file. And this will have two arguments, /api and routes.
Remember earlier in the video, these routes were listed as /api/customers or /api/users. Because /api is the first argument in this app.use statement, it will now attach itself to any route listed inside of the routes folder as the base route path, as in recreating the same routes shown earlier in the video. With this, I've completed the refactoring of the routes using Express Router. I'm going to transition to a split screen with Insomnia to demonstrate that these routes work the same as before. Earlier in the video, the last test I performed was accessing a single customer using the ID of 50. That route is still here. So, I'm going to hit "Send" and there is the response with that single customer that has the corresponding ID of 50. Now, I'm going to remove the ID from the route path in order to request all the customers. Hitting "Send" again, there is the response with all the customers. Now, I'm going to change customers to users in the route path in order to access the users resource. Hitting "Send" again, there is the response with all the users. And that's it. Thanks for watching at Cloud Academy.
Farish has worked in the EdTech industry for over six years. He is passionate about teaching valuable coding skills to help individuals and enterprises succeed.
Previously, Farish worked at 2U Inc in two concurrent roles. Farish worked as an adjunct instructor for 2U’s full-stack boot camps at UCLA and UCR. Farish also worked as a curriculum engineer for multiple full-stack boot camp programs. As a curriculum engineer, Farish’s role was to create activities, projects, and lesson plans taught in the boot camps used by over 50 University partners. Along with these duties, Farish also created nearly 80 videos for the full-stack blended online program.
Before 2U, Farish worked at Codecademy for over four years, both as a content creator and part of the curriculum experience team.
Farish is an avid powerlifter, sushi lover, and occasional Funko collector.