@nestjsvn/swagger-sse
v0.0.5
Published
OpenAPI documentation and interactive Swagger UI for NestJS Server-Sent Events endpoints
Maintainers
Readme
@nestjsvn/swagger-sse
🚧 Development Status: This project is currently in active development. Version 1.0.0 will be released soon with full production-ready features. The core functionality is implemented and tested, but the package is still in pre-release (v0.0.1).
OpenAPI documentation and interactive Swagger UI for NestJS Server-Sent Events endpoints.
@nestjsvn/swagger-sse bridges the gap between NestJS's excellent SSE support and OpenAPI documentation by providing automatic schema generation, interactive Swagger UI integration, and comprehensive TypeScript support for real-time event streaming APIs.
✨ Features
- 🚀 Zero-configuration setup with CLI plugin
- 📝 Automatic OpenAPI schema generation for SSE endpoints
- 🎯 Interactive Swagger UI with real-time event streaming
- 🔒 Full TypeScript support with compile-time validation
- ⚡ High-performance event processing
- 🛡️ Authentication support (JWT, API keys, OAuth)
- 🔧 Flexible configuration options
🚀 Quick Start
Installation
npm install @nestjsvn/swagger-sseBasic Setup
- Update your main application file:
// main.ts
import { NestFactory } from '@nestjs/core';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { setupSsePlugin } from '@nestjsvn/swagger-sse';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const config = new DocumentBuilder()
.setTitle('My API')
.setDescription('API with SSE support')
.setVersion('1.0')
.build();
const document = SwaggerModule.createDocument(app, config);
// Replace SwaggerModule.setup with setupSsePlugin
setupSsePlugin(app, document, 'api-docs');
await app.listen(3000);
}
bootstrap();- Create your first SSE endpoint:
// events.controller.ts
import { Controller, Sse } from '@nestjs/common';
import { Observable, interval, map } from 'rxjs';
import { ApiSse } from '@nestjsvn/swagger-sse';
export class UserCreatedDto {
userId: string;
username: string;
email: string;
timestamp: Date;
}
@Controller('events')
export class EventsController {
@Sse('user-stream')
@ApiSse({
summary: 'User events stream',
description: 'Real-time stream of user-related events',
events: {
'user-created': UserCreatedDto,
},
})
streamUserEvents(): Observable<MessageEvent> {
return interval(2000).pipe(
map((i) => ({
data: JSON.stringify({
userId: `user-${i}`,
username: `User${i}`,
email: `user${i}@example.com`,
timestamp: new Date(),
}),
type: 'user-created',
} as MessageEvent))
);
}
}- Visit your Swagger UI:
Navigate to http://localhost:3000/api-docs and interact with your SSE endpoints using the enhanced UI!
🎯 Interactive Demo

The enhanced Swagger UI provides:
- Real-time connection management with connect/disconnect controls
- Live event streaming with formatted JSON display
- Event filtering and search capabilities
- Connection status indicators and error handling
- Mobile-responsive design for all devices
🔧 Advanced Usage
Automatic Documentation with CLI Plugin
Enable zero-configuration documentation by adding the CLI plugin:
// nest-cli.json
{
"compilerOptions": {
"plugins": [
"@nestjs/swagger",
{
"name": "@nestjsvn/swagger-sse/plugin",
"options": {
"eventNamingConvention": "kebab-case",
"introspectComments": true
}
}
]
}
}Now you can create SSE endpoints without explicit decorators:
@Controller('notifications')
export class NotificationsController {
/**
* Streams notification events
* @summary Real-time notification stream
*/
@Sse('updates')
streamNotifications(): Observable<MessageEvent<NotificationDto>> {
// Plugin automatically generates documentation!
return this.notificationService.getStream();
}
}Multiple Event Types
Handle complex event scenarios with union types:
@ApiSse({
summary: 'Multi-type event stream',
events: {
'user-created': UserCreatedDto,
'user-updated': UserUpdatedDto,
'user-deleted': UserDeletedDto,
'system-alert': SystemAlertDto,
},
})
streamEvents(): Observable<MessageEvent> {
return merge(
this.userEvents$,
this.systemEvents$,
this.alertEvents$
);
}Authentication & Security
Secure your SSE endpoints with guards and authentication:
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@ApiSse({
summary: 'Authenticated event stream',
security: [{ bearer: [] }],
events: {
'private-event': PrivateEventDto,
},
})
streamPrivateEvents(@Request() req): Observable<MessageEvent> {
return this.eventService.getPrivateEvents(req.user.id);
}Error Handling
Implement robust error handling in your streams:
@ApiSse({
events: {
'data-update': DataUpdateDto,
'error': ErrorEventDto,
},
})
streamWithErrorHandling(): Observable<MessageEvent> {
return this.dataService.watchData().pipe(
map(data => ({ type: 'data-update', data: JSON.stringify(data) })),
catchError(error => of({
type: 'error',
data: JSON.stringify({ message: error.message })
}))
);
}📚 Documentation
- Getting Started Guide - Step-by-step setup instructions
- API Reference - Complete API documentation
- Plugin Usage - CLI plugin configuration
- UI Plugin Usage - Swagger UI integration
- Troubleshooting - Common issues and solutions
- Examples - Real-world usage examples
🧪 Testing
The package includes comprehensive testing suites:
# Unit tests
npm run test
# Unit tests with watch mode
npm run test:watch
# Test coverage report
npm run test:coverage🔧 Configuration
Basic Configuration
setupSsePlugin(app, document, 'api-docs', {
customSiteTitle: 'My API Documentation',
customCss: '.swagger-ui .topbar { display: none }',
swaggerOptions: {
persistAuthorization: true,
},
});Plugin Configuration
{
"name": "@nestjsvn/swagger-sse/plugin",
"options": {
"eventNamingConvention": "kebab-case",
"introspectComments": true,
"autoGenerateOperationId": false,
"customEventMappings": {
"UserCreatedDto": "user.created"
}
}
}🔧 Development & Code Quality
This project maintains high code quality standards through comprehensive ESLint and Prettier configurations. Our setup has achieved a 95.7% reduction in lint errors while maintaining excellent developer experience.
📋 Code Quality Overview
The project uses a modern code quality stack:
- ESLint with TypeScript support, accessibility rules, and code quality enforcement
- Prettier for consistent code formatting across the entire codebase
- TypeScript strict mode with comprehensive type checking
- Accessibility rules via
eslint-plugin-jsx-a11y - Automated workflows with pre-commit hooks and CI integration
Quick Script Reference
# Linting
npm run lint # Check all files for lint errors
npm run lint:fix # Fix all auto-fixable lint errors
npm run lint:src # Check only src/ directory
npm run lint:src:fix # Fix only src/ directory
# Formatting
npm run format # Format all files with Prettier
npm run format:check # Check formatting without changes
npm run format:src # Format only src/ directory
npm run format:src:check # Check src/ formatting only
# Combined workflows
npm run quality # Run lint + format:check + type-check
npm run quality:fix # Run lint:fix + format + type-check
npm run type-check # TypeScript compilation check🚀 Setup Instructions
After cloning the repository, verify your setup:
# Install dependencies
npm install
# Verify linting works
npm run lint:src
# Verify formatting works
npm run format:src:check
# Run complete quality check
npm run quality
# Expected output: ✅ All checks should pass⚡ Development Workflow
Pre-commit Workflow
Recommended pre-commit checklist:
- [ ] Run
npm run quality:fixto fix all auto-fixable issues - [ ] Run
npm run testto ensure all tests pass - [ ] Review ESLint warnings and address critical issues
- [ ] Verify TypeScript compilation with
npm run type-check
Quick pre-commit command:
npm run quality:fix && npm run testCode Review Process
For reviewers:
- Focus on logic and architecture rather than formatting
- All formatting issues are automatically handled
- ESLint warnings indicate potential code quality issues
- TypeScript errors must be resolved before merge
For contributors:
- Ensure
npm run qualitypasses before requesting review - Address any ESLint warnings in your changes
- Maintain test coverage for new functionality
🤝 Contributing
We welcome contributions! Please see our Contributing Guide for details.
Before contributing, please review our Development & Code Quality section for setup instructions and workflow guidelines.
Development Setup
# Clone the repository
git clone https://github.com/dragonxsx/nestjsx-swagger-sse.git
cd swagger-sse
# Install dependencies
npm install
# Verify setup with quality checks
npm run quality
# Run tests
npm run test
# Build the project
npm run build
# Run E2E tests
npm run test:e2eContribution Workflow
- Setup: Follow the Development & Code Quality setup instructions
- Development: Use the recommended daily workflow
- Quality: Run
npm run quality:fixbefore committing - Testing: Ensure all tests pass with
npm run test - Documentation: Update relevant documentation for new features
Code Standards
All contributions must meet our code quality standards:
- ✅ ESLint rules must pass (zero errors)
- ✅ Prettier formatting must be consistent
- ✅ TypeScript compilation must succeed
- ✅ Test coverage must be maintained
- ✅ Documentation must be updated for new features
See our Configuration Details for specific rules and rationale.
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🙏 Acknowledgments
- NestJS Team - For the excellent framework and SSE support
- Swagger UI Team - For the extensible documentation interface
- Community Contributors - For feedback, bug reports, and contributions
📊 Project Stats
🔗 Related Projects
- @nestjs/swagger - OpenAPI documentation for NestJS
- @nestjs/common - NestJS framework
Made with ❤️ by the NestJS community
