- Do not start Nest server, instead, just export an async function which returns its initialized app instance:
// path/to/nest/src/main.ts
import { NestFactory } from '@nestjs/core';
import { ExpressAdapter, NestExpressApplication } from '@nestjs/platform-express'; // Optional because the `@nestjs/platform-express` package is used by default
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule); // Optionally, `const app = await NestFactory.create<NestExpressApplication>(AppModule, new ExpressAdapter());`
await app.init();
return app.getHttpAdapter().getInstance();
}
export default bootstrap;
- Nuxt's built-in server uses connect to form its middleware stack. Beacuse the Nest (express) instance returned by the
bootstrap
function above is compatible with connect/express, we can use is just like a normal middleware:
// path/to/nuxt/nuxt.config.js
import bootstrap from 'path/to/nest/dist/main.js'; // import the compiled JS (do not import TS)
export default async () => ({
// ...
serverMiddleware: [
{
path: '/api',
handler: await bootstrap(), // use nest app instance as a normal nuxt server middleware
}
],
});
That's it.
Start the Nuxt app and we can see the Nest API response at: localhost:3000/api
✨ Bonus: Nuxt + Nest (Fastify version)
Credit: @ekoeryanto's comment♥️