src
├── main.ts
├── app.module.ts
│
├── modules
│ ├── users/
│ │ ├── users.controller.ts
│ │ ├── users.service.ts
│ │ ├── users.module.ts
│ ├── auth
│ ├── pets
│
├── common
│ ├── guards
│ ├── interceptors
│ ├── filters
│ ├── decorators
│
├── infrastructure
│ ├── database
│ ├── redis
│ ├── logger
main.ts (Entry point)Initializes the NestJS app instance
console.log)
Configures the HTTP adapter and global framework behavior
Set global configs (to whole server)
/api prefixSet HTTP security header
X-Frame-Options
Content-Security-Policy
X-XSS-Protection
Strict-Transport-Security
Enable response compression (can set threshold)
Enabling validation
Enabling Swagger docs
Enabling CORS
Set graceful shutdown
Starting the HTTP server
NestFactory.create(AppModule)
↓
Create dependency injection container
↓
Scan all modules
↓
Resolve providers
↓
Create controllers
↓
Attach middleware / guards / pipes
↓
Start HTTP adapter (Express/Fastify)
Code:
async function bootstrap() {
// 1. Create application (AppModule is the root module)
// - Create DI container
// - Scans modules
// - Registers providers
// - Connects middleware
// - Prepares HTTP server (Express by default)
const app = await NestFactory.create(AppModule);
// 2. Set global API prefix (/api/...)
app.setGlobalPrefix('api');
// 3. Security Headers
app.use(helmet());
// 4. Compresses responses -> faster network
app.use(
compression({
threshold: 1024, // only compress > 1KB
}),
);
// 5. Global Validation Pipe
// - Apply validation to all requests
app.useGlobalPipes(
new ValidationPipe({
// Removes fields that NOT defined in DTO
whitelist: true,
// Auto converts types
transform: true,
// If user sends extra fields, throw error
forbidNonWhitelisted: true,
}),
);
// 6. Swagger Documentation
const config = new DocumentBuilder()
.setTitle('Find-My-Pet API')
.setDescription('The community-driven lost and found pet platform API')
.setVersion('1.0')
.addBearerAuth() // enables JWT authentication
.build();
// 7. Creating Swagger Document
// - Scans all controllers
// - Reads decorators
// - Generates OpenAPI JSON
// - Hosts Swagger UI
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('docs', app, document);
// 8. Enable CORS on specific origin
app.enableCors({
origin: ['<https://your-frontend.com>'],
credentials: true,
});
// 9. Global Exception Filter
const httpAdapter = app.get(HttpAdapterHost);
app.useGlobalFilters(new GlobalExceptionFilter());
// 10. Graceful Shutdown (for Docker, Kubernetes)
app.enableShutdownHooks();
// 11. Start the server on port 3000
await app.listen(process.env.PORT ?? 3000);
}
// 12. Runs the async function
bootstrap();