External Routes with Node.js
Tags: beginners, node, routes, express
Published: 2017-10-03 03:14:56

---
title: External Routes with Node.js
published: true
description: A detailed instruction on how to structure your Node.js external routes. 
tags: beginners, node.js, routes, express
---

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](https://expressjs.com/)’ 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](https://dev.to/ryhenness/nodejs--express-server-setup-6ch) 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](https://www.youtube.com/watch?v=ctUH5Hj6WLM&t=11s), and the code on [GitHub](https://github.com/henness17/SweetCode/tree/master/002-Node-External-Routes).

---
# 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`:

```javascript
    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 called`externalRoutes.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: 
```javascript
// Our external route
var externalRoutes = require('./routes/externalRoutes');
app.use('/externalRoutes', externalRoutes);
```
The entire `index.js` file will look like this:
```javascript
// 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:
```javascript
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`:
```javascript
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:
```javascript
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](https://dev.to/ryhenness/auto-deploy-a-nodejs-server-heroku--github-em).

---
{% youtube ctUH5Hj6WLM %}