npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@nestjsvn/swagger-sse

v0.0.5

Published

OpenAPI documentation and interactive Swagger UI for NestJS Server-Sent Events endpoints

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).

npm version License: MIT Build Status Coverage Status

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-sse

Basic Setup

  1. 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();
  1. 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))
    );
  }
}
  1. Visit your Swagger UI:

Navigate to http://localhost:3000/api-docs and interact with your SSE endpoints using the enhanced UI!

🎯 Interactive Demo

SSE Swagger UI 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

🧪 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:

Quick pre-commit command:

npm run quality:fix && npm run test

Code 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 quality passes 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:e2e

Contribution Workflow

  1. Setup: Follow the Development & Code Quality setup instructions
  2. Development: Use the recommended daily workflow
  3. Quality: Run npm run quality:fix before committing
  4. Testing: Ensure all tests pass with npm run test
  5. 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

GitHub stars GitHub forks GitHub issues GitHub pull requests

🔗 Related Projects


Made with ❤️ by the NestJS community

Report Bug · Request Feature · Documentation · Examples