Home

Issue: 2450

How to use nuxt in koa-router or express-router?

[issue link]

I have some problems to use nuxt.js. I have a backend router hybrid, I want to use nuxt.render in this router, but I found 404 error in all assets, like ‘/_nuxt/app.xxxx.js’, ‘_nuxt/layout.xxx.js’. Could you give any tips or a example which use koa-router.Thank you.

project structure

  • routes/hybrid/index.js
  • nuxt.config.js
  • .nuxt/
import Router from 'koa-router';
import { Nuxt, Builder } from 'nuxt';
const config = require('../../nuxt.config.js');
config.dev = !(process.env.NODE_ENV === 'production');
const nuxt = new Nuxt(config);
const hybrid = new Router();
hybrid.use('/', async (ctx, next) => {
  if (config.dev) {
    const builderIgnored = new Builder(nuxt);
    await new Builder(nuxt).build();
  }
  await next();
  ctx.status = 200; // koa defaults to 404 when it sees that status is unset
  return new Promise((resolve, reject) => {
    ctx.res.on('close', resolve);
    ctx.res.on('finish', resolve);
    nuxt.render(ctx.req, ctx.res, promise => {
      // nuxt.render passes a rejected promise into callback on error.
      promise.then(resolve).catch(reject);
    });
  });
});
export default hybrid;
This question is available on Nuxt.js community (#c2125)