NestJS Notes
Notes on integrating Fastify, Swagger, Prisma, and Zod in NestJS, plus MongoDB connection and transaction issues.
Updated
NestJS Components
Fastify
NestJS mainly encapsulates application-layer functionality; the underlying network request handling framework can be swapped through an adapter. Express and Fastify are supported by default, and switching to Fastify is recommended for better performance.
import { FastifyAdapter } from '@nestjs/platform-fastify'
async function bootstrap() {
const app = await NestFactory.create(
AppModule,
// Use fastify as the underlying framework
new FastifyAdapter({
// fastify configuration
logger: false,
ignoreTrailingSlash: true,
}),
)
await app.listen(process.env.PORT ?? 3000)
}
You can get the Fastify instance through app.getHttpAdapter().getInstance() to use Fastify-specific features, such as fastify.register(helmet, {}) to add security policy configuration.
Swagger
Install Swagger first; it lets you send requests through a UI, saving the time spent with curl and postman. NestJS officially provides @nestjs/swagger for Swagger support, and getting started is quick:
// main.ts
async function bootstrap() {
// Initialize the NestJS application
const app = await NestFactory.create(AppModule)
// Initialize Swagger
initSwagger(app)
// Listen on the port
await app.listen(process.env.PORT ?? 3000)
}
bootstrap()
function initSwagger(app: INestApplication) {
// Check whether this is the development environment
const isDev = process.env.NODE_ENV === 'development'
if (!isDev) {
return
}
// Initialize the Swagger description information here
const config = new DocumentBuilder()
.setTitle('My API')
.setDescription('My API description')
.setVersion('1.0')
.addTag('He110')
.build()
const documentFactory = () => SwaggerModule.createDocument(app, config)
// Set the swagger URL to /swagger
SwaggerModule.setup('swagger', app, documentFactory)
}
Prisma
Usage
- Prisma is strongly typed; you can run
npx prisma generateto generate the ORM types from the Schema that describes the data. - Initialize the database with
npx prisma db push --force-reset, which also tests the connection status.
Environment Variables
Prisma does not support automatically switching .env files based on the runtime environment, so a feature like vite's priority-based dotenv loading needs to be implemented yourself.
MongoDB
Cannot connect to the database
Connecting to MongoDB reports Error in connector: SCRAM failure: Authentication failed.
Refer to the official documentation; with newer versions of MongoDB you need to add the ?authSource=admin query parameter to connect.
Cannot insert data
Prisma only allows transactions on a replica set when connecting to MongoDB. A local deployment generally has no replica set enabled, so you need to set up a replica set first, or connect to the hosted MongoDB Atlas.
Parameter Validation
For request parameter validation, NestJS officially recommends handling it with Pipes. If you use zod, you need to pair it with nestjs-zod.
If you follow the official zod integration tutorial, Swagger display will break and fail to read the content.
nestjs-zod provides patchNestJsSwagger, which can inject zod-defined Schemas into Swagger, avoiding the problem of duplicating data structure definitions.