Reputation: 1309
I'm developing an SSR Nuxt.js app with an integrated REST API server.
To do this, I've added my /api
endpoint inside Nuxt server.js
code as following
const express = require('express')
const consola = require('consola')
const { Nuxt, Builder } = require('nuxt')
const app = express()
// Import and Set Nuxt.js options
const config = require('../nuxt.config.js')
config.dev = process.env.NODE_ENV !== 'production'
// MY REST API ENDPOINT (It's the right approach?)
const routesApi = require('./api/routes')
app.use('/api', routesApi)
async function start() {
// Init Nuxt.js
const nuxt = new Nuxt(config)
const { host, port } = nuxt.options.server
await nuxt.ready()
// Build only in dev mode
if (config.dev) {
const builder = new Builder(nuxt)
await builder.build()
}
// Give nuxt middleware to express
app.use(nuxt.render)
// Listen the server
app.listen(port, host)
consola.ready({
message: `Server listening on http://${host}:${port}`,
badge: true
})
}
start()
I didn't found examples related to this approach.
I need some help to understand if it's the right way.
Thank you for your support.
Upvotes: 4
Views: 13106
Reputation: 1141
You would probably like to read following article: https://blog.lichter.io/posts/nuxt-with-an-api/ It has common takes to solve "API with Nuxt" case.
Your solution is already enough for small integrated API, I guess, that way you avoid setting up proxy against CORS issues. :) You could add some sugar with serverMiddleware
:
// nuxt.config.js
export default {
...
serverMiddleware: [
'/api': '~/api/index.js'
],
...
}
// api/index.js
export default function (req, res, next) {
... // Well, here comes nothing
next()
}
But big API scales nice on separate server, it's also a separation of concerns to consider. Nuxt serves better as universal app rendering middleware, but API can be written even in another language, backend. For defying problems with CORS, you'll need to place /api
on same domain, as you intended, thus it's more easier with Nuxt proxy-module.
Upvotes: 9