Skip to content

opengig/next-nest-sse-template

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 

Repository files navigation

Next.js + NestJS SSE Template

A production-grade proof of concept demonstrating Server-Sent Events (SSE) for real-time data streaming.

Architecture

Frontend (Next.js)

  • /src/queries/ - TanStack Query logic only (no React hooks)
  • /src/hooks/ - React hooks for SSE connection management
  • /src/components/ - UI components
  • /src/app/ - Next.js app router pages

Backend (NestJS)

  • /src/process/ - Supply chain process controller and service
  • /src/data/ - Dummy data and configuration
  • /src/app.module.ts - Main application module

Key Features

  • Real-time SSE streaming from NestJS to Next.js
  • Automatic reconnection and error handling
  • TanStack Query for state management and caching
  • Manual stage advancement with Next button
  • Production-grade code with clear separation of concerns
  • TypeScript throughout for type safety
  • Clean architecture following React/Next.js best practices

Getting Started

1. Start the Backend

cd server
npm install
npm run start:dev

2. Start the Frontend

cd web
npm install
npm run dev

3. View the Demo

Open http://localhost:3001 to see the real-time SSE data streaming in action.

Try the Next Button: Click the "Next Stage" button to manually advance to the next stage and see the SSE updates in real-time!

How It Works

Architecture Overview

This template demonstrates a hybrid approach combining Server-Sent Events (SSE) with TanStack Query for optimal real-time data management:

  1. Backend automatically progresses data stages every 3 seconds
  2. SSE endpoint (/process/stream) streams updates every 2 seconds
  3. Frontend connects to SSE and displays real-time data
  4. TanStack Query handles data fetching, caching, and refetching
  5. React hooks manage SSE connection lifecycle
  6. Next button allows manual stage advancement for demonstration

Technology Stack

Backend (NestJS)

  • Framework: NestJS with TypeScript
  • SSE Implementation: Built-in @Sse() decorator with RxJS Observables
  • Data Management: In-memory service with automatic progression
  • CORS: Enabled for cross-origin requests
  • Port: 3000

Frontend (Next.js)

  • Framework: Next.js 15 with App Router
  • State Management: TanStack Query v5
  • SSE Client: Native EventSource API
  • Styling: Tailwind CSS
  • TypeScript: Full type safety
  • Port: 3001

Frontend vs Backend Logic Differences

Backend Logic (Server-Side)

// Automatic progression every 3 seconds
if (timeSinceLastUpdate >= 3000) {
  // Update stage progress
  // Complete stages when 100%
  // Move to next stage
}

Key Characteristics:

  • Time-based progression: Updates every 3 seconds
  • Stateful service: Maintains current stage and progress
  • Automatic advancement: No manual triggers needed
  • Persistent data: Data survives between requests

Frontend Logic (Client-Side)

// TanStack Query refetch every 2 seconds
refetchInterval: 2000

// SSE connection triggers refetch on message
eventSource.onmessage = () => {
  refetch(); // Immediate refetch on SSE event
}

Key Characteristics:

  • Dual refresh strategy: 2-second intervals + SSE-triggered
  • Stateless components: Data comes from queries
  • Optimistic updates: SSE provides instant feedback
  • Fallback mechanism: Query continues if SSE fails

Data Flow Architecture

┌─────────────────┐    SSE Stream    ┌─────────────────┐
│   NestJS        │ ────────────────► │   Next.js       │
│   Backend       │                  │   Frontend      │
│                 │                  │                 │
│ • Auto-progress │                  │ • TanStack Query│
│   every 3s      │                  │   refetch 2s    │
│ • SSE stream    │                  │ • SSE listener  │
│   every 2s      │                  │ • UI updates    │
└─────────────────┘                  └─────────────────┘

Why This Hybrid Approach?

  1. Reliability: TanStack Query provides fallback if SSE fails
  2. Performance: SSE gives instant updates, Query handles caching
  3. Consistency: Both systems ensure data stays fresh
  4. Resilience: Automatic reconnection and error handling
  5. Developer Experience: Clear separation of concerns

File Structure & Responsibilities

web/src/
├── queries/sse.ts          # TanStack Query logic only
│   ├── useSSEQuery()       # Data fetching with 2s intervals
│   ├── SSEData interface   # Type definitions
│   └── SSEStage interface  # Stage type definitions
├── hooks/useSSE.ts         # React hook for SSE management
│   ├── EventSource setup   # SSE connection logic
│   ├── Connection state    # isConnected tracking
│   └── Query integration   # Triggers refetch on SSE events
├── components/             # UI components
│   ├── SupplyChainProgressBar.tsx
│   └── SupplyChainStatus.tsx
└── app/page.tsx           # Main page using useSSE hook

Production Considerations

The current implementation includes comments indicating production differences:

  • Database Integration: Replace in-memory data with PostgreSQL/MongoDB
  • Authentication: Add JWT tokens and user permissions
  • Rate Limiting: Implement request throttling
  • Monitoring: Add logging and error tracking
  • Scaling: Use Redis for multi-instance state sharing
  • Security: Add CORS policies and input validation

File Structure

├── server/                 # NestJS backend
│   ├── src/
│   │   ├── process/        # SSE controller & service
│   │   ├── data/          # Dummy data & config
│   │   └── app.module.ts  # Main module
│   └── package.json
├── web/                   # Next.js frontend
│   ├── src/
│   │   ├── queries/       # TanStack Query logic
│   │   ├── hooks/         # React hooks
│   │   ├── components/    # UI components
│   │   └── app/          # Next.js pages
│   └── package.json
└── README.md

This template provides a solid foundation for building real-time applications with SSE and can be easily extended for production use.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •