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.
@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)
}
}
Most helpful comment
It's actually fairly easy, you can just return a function inside a function which takes
app馃槃The double arrow in this case is just a shorthand for this: