DEV Community

Ryan
Ryan

Posted on • Updated 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 using Express’ 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 give this tutorial a look, it goes into detailed instruction on how to set up a Node.js server with Express.
You can find the video tutorial here, and the code on GitHub.


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:

    var express = require('express');
    var app = express();

    // Our first route
    app.get('/', function (req, res) {
        res.send('Hello Index!');
    });

    // Our A route
    app.get('/A', function (req, res) {
        res.send('Hello A!');
    });

    // Our B route
    app.get('/B', function (req, res) {
        res.send('Hello B!');
    });

    // Our C route
    app.get('/C', function (req, res) {
        res.send('Hello C!');
    });

    // Listen to port 5000
    app.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 called index.js and a folder called routes 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 the Can 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 called routes for a file called externalRoutes.js which contains the external routing implementation (well, not yet... but it will). Inside of index.js, let's add:

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

The entire index.js file will look like this:

// index.js
var express = require('express');
var app = express();

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

// Listen to port 5000
app.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 our externalRoutes.js. We will create a module export, which will export the definition of our externalRoutes variable. First, create a module.exports function inside of externalRoutes.js, like so:

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

Now add the variable to the module.exports body that we want to be exported, let's call it externalRoutes:

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

    var externalRoutes = require('express').Router();

    return externalRoutes;
})();

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

module.exports = (function() {
    'use strict';
    var externalRoutes = require('express').Router();

    externalRoutes.get('/', function (req, res) {
        res.send('Hello ExternalRoutes!');
    });
    externalRoutes.get('/someRoute', function (req, res) {
        res.send('Hello SomeRoute!');
    });

    return externalRoutes;
})();

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 command node index.js from the top-level directory). Head on over to address http://localhost:5000/externalRoutes, and http://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 out Auto-Deploy a Node.js Server: Heroku + GitHub.


Top comments (6)

Collapse
 
hm04 profile image
Matthew Marion

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.

Collapse
 
ryhenness profile image
Ryan

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.

Collapse
 
hm04 profile image
Matthew Marion

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

Collapse
 
anirudhrahul profile image
AnirudhRahul

Thanks this is just what I was looking for

Collapse
 
shivam20 profile image
Shivam

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

Collapse
 
ryhenness profile image
Ryan

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...