Next.js: How should I configure NextJS if I want routes in a separate file?

Created on 9 Sep 2017  路  2Comments  路  Source: vercel/next.js

I see an example of NextJS with express on the backend. But how should I code all this, if I want routes in a separate file like routes.js, and functions to each route in separate file like controller.js?

This is your example, server.js:

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()

app.prepare()
.then(() => {
  const server = express()

  server.get('/a', (req, res) => {
    return app.render(req, res, '/b', req.query)
  })

  server.get('/b', (req, res) => {
    return app.render(req, res, '/a', req.query)
  })

  server.get('*', (req, res) => {
    return handle(req, res)
  })

  server.listen(port, (err) => {
    if (err) throw err
    console.log(`> Ready on http://localhost:${port}`)
  })
})

But what If I want structure like this:

controllers.js:

exports.somePage = (req, res) => {
    return app.render(req, res, '/a', req.query)
}

and routes.js

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

server.get('/b', controller.somePage)

I can't configure it this way. I googled this a lot, and didn't find it, hope not too dumb of a question.

Most helpful comment

It's actually fairly easy, you can just return a function inside a function which takes app 馃槃

exports.somePage = (app) => (req, res) => {
    return app.render(req, res, '/a', req.query)
}
const controller = require('./controller');

server.get('/b', controller.somePage(app))

The double arrow in this case is just a shorthand for this:

exports.somePage = (app) => {
     return (req, res) => {
          return app.render(req, res, '/a', req.query)
     }
}

All 2 comments

@askeroff You could probably use the next-routes package to help achieve this.

It's actually fairly easy, you can just return a function inside a function which takes app 馃槃

exports.somePage = (app) => (req, res) => {
    return app.render(req, res, '/a', req.query)
}
const controller = require('./controller');

server.get('/b', controller.somePage(app))

The double arrow in this case is just a shorthand for this:

exports.somePage = (app) => {
     return (req, res) => {
          return app.render(req, res, '/a', req.query)
     }
}
Was this page helpful?
0 / 5 - 0 ratings

Related issues

flybayer picture flybayer  路  3Comments

irrigator picture irrigator  路  3Comments

ghost picture ghost  路  3Comments

olifante picture olifante  路  3Comments

jesselee34 picture jesselee34  路  3Comments