Is there an order for how to write a router and use it in app?


#1

Question

Is there an order for how to write a router and use it in app?

Answer

Most pieces for an express server are interchangeable in order, that is one of the wonderful advantages of that library, but we do want to keep a few things in mind.

  • We do want to make sure the router has been declared before we set up any requests and before we implement app.use(), ie:
const routesRouter = express.Router();

routesRouter.get('/', (req,res,next) => {...});
... //other methods

app.use('routes', routesRouter);

or

const routesRouter = express.Router();

app.use('routes', routesRouter);

routesRouter.get('/', (req,res,next) => {...});
... //other methods

even if in a different file:

//in routesRouter.js
const express = require('express');

const routesRouter = express.Router();

routesRouter.get('/', (req,res,next) => {...});
... //other methods
module.exports = routesRouter;

Now in app:

...
const routesRouter = require('./routesRouter');

app.use(routesRouter);
...
  • We also want to make sure we declare it before any request handler, now the handlers can be written before or after app.use() if they are in the same file, but because we need to have the router declared to use it, we cannot start writing our request handlers before we declared the router we will use for them.

Besides that, it is common to also see the router and its handlers to be after all the general set up of the server in app, and just commonly before app.listen() this way we have everything we need to have our server working, the router is created to handle routes, and at last, we open the server to requests with the listen method.


FAQ: Code Challenges - Code Challenge