Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Ryan
Ryan

Posted on • Edited on

     

External Routes with Node.js

What's up, I'm glad you're here! We'll be discussing how to set up and structure external routes for our Node.js server by usingExpress’ routers. External routes can be a great way to keep your code organized, maintainable, and easy to understand; they help create a structure that is easy to examine in order to locate a particular piece related to your work. If you haven't set up a Node.js server before, make sure to givethis tutorial a look, it goes into detailed instruction on how to set up a Node.js server with Express.
You can find the video tutorialhere, and the code onGitHub.


What Do You Mean?

Okay, so what do I mean by external routes? Well, as you get more and more routes set up inside of your server, things can get a bit clunky and confusing. External routing is a way of structuring your code so that it stays nice and organized by taking the route implementations outside of the main server file and moving them into a separate router file.


Can I Get An Example?

Of course. Let's say that we have a simple server file with a bunch of routes,index.js:

varexpress=require('express');varapp=express();// Our first routeapp.get('/',function(req,res){res.send('Hello Index!');});// Our A routeapp.get('/A',function(req,res){res.send('Hello A!');});// Our B routeapp.get('/B',function(req,res){res.send('Hello B!');});// Our C routeapp.get('/C',function(req,res){res.send('Hello C!');});// Listen to port 5000app.listen(5000,function(){console.log('Dev app listening on port 5000!');});

We can see that adding more routes and functionality would easily make this file very confusing and hard to maintain. It may not be doing a whole lot right now, but imagine developing with it for weeks... months... years. We could start to add routes that handle things such as social media verification, APIs, and even just static pages. So, we want to start separating and structuring our code as our routes can become more niche, and before the index file starts gaining more functionality - it may need to handle more than just routing in the future (and it would if this was a probable application).


The Goal

Our goal is to keep our index clean and our code organized. This is the overview of our file/folder structure, and how we want to separate these route definitions from the main index file. So go ahead and recreate this structure by creating a file calledindex.js and a folder calledroutes with a file calledexternalRoutes.js inside of it:

.├── index.js              └── routes                └── externalRoutes.js

Defining the Router

Now it's time to clean up our index file (the file used in theCan I Get An Example? section). Let's replace all of those routes with a router definition. This router definition will tell the index file where to look for routes to be defined. In this case, we are telling the index (which is at the top-level directory) to search inside of a folder calledroutes for a file calledexternalRoutes.js which contains the external routing implementation (well, not yet... but it will). Inside ofindex.js, let's add:

// Our external routevarexternalRoutes=require('./routes/externalRoutes');app.use('/externalRoutes',externalRoutes);

The entireindex.js file will look like this:

// index.jsvarexpress=require('express');varapp=express();// Our external routevarexternalRoutes=require('./routes/externalRoutes');app.use('/externalRoutes',externalRoutes);// Listen to port 5000app.listen(5000,function(){console.log('Dev app listening on port 5000!');});

Now that's a whole lot cleaner already, isn't it? :)


Implementing the Router

But where did those routes go?! Don't worry! We're going to store them inside of ourexternalRoutes.js. We will create a module export, which will export the definition of our externalRoutes variable. First, create amodule.exports function inside ofexternalRoutes.js, like so:

module.exports=(function(){'use strict';})();

Now add the variable to themodule.exports body that we want to be exported, let's call itexternalRoutes:

module.exports=(function(){'use strict';varexternalRoutes=require('express').Router();returnexternalRoutes;})();

Finally, add the routes to themodule.exports that we've all been waiting for, and you've got yourself some external routes! The entire body ofexternalRoutes.js looks like this:

module.exports=(function(){'use strict';varexternalRoutes=require('express').Router();externalRoutes.get('/',function(req,res){res.send('Hello ExternalRoutes!');});externalRoutes.get('/someRoute',function(req,res){res.send('Hello SomeRoute!');});returnexternalRoutes;})();

External Routes on the Browser

Now that we've got your external routes set up, fire up that server and web browser (for those that aren't sure how, run the commandnode index.js from the top-level directory). Head on over to addresshttp://localhost:5000/externalRoutes, andhttp://localhost:5000/externalRoutes/someRoute to see your routes in action with responses!


Review

Congratulations! You've now successfully set up external routes on your Node.js server. You did this by removing the routes from your index file and structuring your architecture in a way that allows the routes to be a part of an external file. This made your code more maintainable as you start to build your server and add its functionality. If you'd like to learn about deployment, check outAuto-Deploy a Node.js Server: Heroku + GitHub.


Top comments(6)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
hm04 profile image
Matthew Marion
Georgia Tech '22 Computer Science student, soccer player
  • Email
  • Location
    United States
  • Work
    Software Developer at Moojm, NCR
  • Joined

Good explanation of how to move routes to an external file; however, you still aren't making your code cleaner, easier to understand, or even maintainable. By the looks of it you are simply "cleaning your room" by stuffing everything in the closet. Anyways, good explanation of external routes, I just do not think it solves all the problems you claimed in the introduction.

CollapseExpand
 
ryhenness profile image
Ryan
Excited to learn new technologies while growing as a developer. Studied at University of Portland.
  • Location
    Portland, OR
  • Education
    University of Portland
  • Work
    Software Developer at Viewpoint, a Trimble company
  • Joined

Thanks for the feedback! I've updated the intro with something I believe to be a bit more fitting, along with an explanation. I agree with your argument that the code does not become cleaner, it is just being moved somewhere else. I would argue that external routes do make the code easier to understand, and maintainable by putting things into their drawers, rather than stuffing everything in the closet.

CollapseExpand
 
hm04 profile image
Matthew Marion
Georgia Tech '22 Computer Science student, soccer player
  • Email
  • Location
    United States
  • Work
    Software Developer at Moojm, NCR
  • Joined

No problem! I do also agree that it can make it easier to understand to an extent.

CollapseExpand
 
anirudhrahul profile image
AnirudhRahul
  • Joined

Thanks this is just what I was looking for

CollapseExpand
 
shivam20 profile image
Shivam
  • Joined

how can i pass data from externalrouter to app.js in nodejs

CollapseExpand
 
ryhenness profile image
Ryan
Excited to learn new technologies while growing as a developer. Studied at University of Portland.
  • Location
    Portland, OR
  • Education
    University of Portland
  • Work
    Software Developer at Viewpoint, a Trimble company
  • Joined

Hey Shivam, I would need more context to fully help you. But if you'd like to pass data from the front-end of the application (like what the user has typed in a textbox) to the server, check out POST requests:codeforgeek.com/handle-get-post-re...

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Excited to learn new technologies while growing as a developer. Studied at University of Portland.
  • Location
    Portland, OR
  • Education
    University of Portland
  • Work
    Software Developer at Viewpoint, a Trimble company
  • Joined

More fromRyan

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp