title: Using Express Router with Next.js
body: <p>I'm trying to use the Express Router with Next.js using their <a href="https://github.com/zeit/next.js/blob/master/examples/custom-server-express/server.js" rel="noreferrer">custom-express-server example</a> as my boilerplate. The only difference is that I'm trying to define the routes externally on routes/router.js as follows:</p>
  
  <p>Code in server.js:</p>
  
  <pre><code>const express = require('express')
  const next = require('next')
  
  const port = parseInt(process.env.PORT, 10) || 3000
  const dev = process.env.NODE_ENV !== 'production'
  const app = next({ dev })
  const handle = app.getRequestHandler()
  const routes = require('./routes/router')
  
  app.prepare()
    .then(() =&gt; {
      const server = express()
  
      server.use('/', routes)
  
      server.get('*', (req, res) =&gt; {
        return handle(req, res)
      })
  
      server.listen(port, (err) =&gt; {
        if (err) throw err
        console.log(`&gt; Ready on http://localhost:${port}`)
      })
    })
  
  module.exports = app;
  </code></pre>
  
  <p>Code in routes/router.js:</p>
  
  <pre><code>const express = require('express'),
  app = require('../server.js'),
  router = express.Router();
  
  router.get('/a', (req, res) =&gt; {
    return app.render(req, res, '/b', req.query)
  })
  
  router.get('/b', (req, res) =&gt; {
    return app.render(req, res, '/a', req.query)
  })
  
  router.get('/posts/:id', (req, res) =&gt; {
    return app.render(req, res, '/posts', { id: req.params.id })
  })
  
  module.exports = router;
  </code></pre>
  
  <p>At this point, even when I'm importing "app" from server.js, app is not available within router.js.</p>
  
  <p>Is my logic incorrect?
  If it's not, then why is app not available within router.js?</p>