N
N
Nikita2020-06-23 08:10:15
Node.js
Nikita, 2020-06-23 08:10:15

How to integrate neXt into neSt?

Trying to accomplish this by connecting neXt in a custom neSt adapter

// custom.adapter.ts
import { ExpressAdapter } from '@nestjs/platform-express';
import { Response } from 'express';
import next  from 'next';

const dev = true;
const nextApp = next({ dev });
const handle = nextApp.getRequestHandler();

export class NextAdapter extends ExpressAdapter {
    constructor() { super() }
    
    render(res: Response, view: string, options: any) {
        const { req } = options;
        return new Promise<void>(async (resolve) => {
            nextApp.prepare().then(async () => {

                if (req.query = '/a') {
                    await nextApp.render(req, res, '/a', req.query)
                } else {
                    handle(req, res);
                }
                resolve();
            });
        });
    }
}

And I connect the adapter like this:
// main.ts
import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { AppModule } from './app.module';
import { NextAdapter } from './next.adapter';



async function bootstrap() {
  const app = await NestFactory.create(AppModule, new NextAdapter());

  const options = new DocumentBuilder()
    .setTitle('Blog Rest API dosc')
    .build();
  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup('api', app, document);

  await app.listen(3000);
}

bootstrap();

But, if this approach can work, I am doing something wrong and, when trying to access the page, neXt cannot find its statics and gives empty html, and in the browser console, respectively, a lot of 404 errors about files not found .
I posted the rest of the code on github - https://github.com/MiiZZo/nest-next/tree/master/ne...
Please help me with this problem. Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly, 2020-06-23
@vshvydky

judging by your code, you call an empty constructor in which the express is ititated separately, you, in turn, separately init next, how it lives at all, I don’t understand you
have a look here: git
if you want to cross an elephant and a rhinoceros, then obviously look on this class, and within the same instance, overload the methods you
need, but if nothing has changed in the next, it doesn’t know how to /some/:someID routes, everything is done through Queri.
Perhaps it would be more correct to use the server render utility and just tune a couple of methods without trying to replace one express with a wrapper for the sake of it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question