- 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
Something not work
If to main.ts from this example to add any database orm (sequalize/prisma/typeorm)
Prism controller from https://github.com/prisma/prisma-examples/tree/latest/typescript/rest-nestjs
import {
Controller,
Get,
Param
// Post,
// Body,
// Put,
// Delete,
// Query
} from '@nestjs/common'
import {
// User as UserModel,
Post as PostModel
// Prisma
} from '@prisma/client'
import { AppService } from './app.service'
@controller()
export class AppController {
// eslint-disable-next-line no-useless-constructor
constructor (private readonly prismaService: AppService) {}
get an error:
ERROR [ExceptionsHandler] Cannot read property 'post' of undefined TypeError: Cannot read property 'post' of undefined
Sequalize controller from https://github.com/nestjs/nest/tree/master/sample
import { Body, Controller, Delete, Get, Param, Post } from '@nestjs/common'
import { CreateUserDto } from './dto/create-user.dto'
import { User } from './user.model'
import { UsersService } from './users.service'
ERROR [ExceptionsHandler] Cannot read property 'findOne' of undefined TypeError: Cannot read property 'findOne' of undefined
Main.ts from
import { NestFactory } from '@nestjs/core';
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify'; // npm i --save @nestjs/platform-fastify
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule, new FastifyAdapter({ ignoreTrailingSlash: true, logger: true }));
await app.init();
}
export default bootstrap;