This project demonstrates how to consume Server-Sent Events (SSE)
from a .NET
backend using two different front-end clients: Angular
and Next.js.
Server-Sent Events (SSE) provide a simple way for a server to push
real-time updates to the browser over HTTP. Unlike WebSockets, SSE is
one-way (server β client) and built into modern browsers via the
EventSource
API.
In this repository, we have: - Backend (.NET) β SSE endpoint streaming notifications - Frontend (Angular) β SSE client that listens and displays messages - Frontend (Next.js) β SSE client that listens and displays messages
- .NET 8 API with SSE
- Angular 17 for the first client
- Next.js 14 (React) for the second client
- TypeScript in both frontends
-
Navigate to the backend folder
-
Run:
dotnet restore dotnet run
-
Your SSE endpoint should be available at:
https://localhost:7073/api/v1/Notifications/getstream
Ensure CORS is enabled in .NET
so clients can connect:
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowAll", b =>
{
b.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
});
});
app.UseCors("AllowAll");
-
Go to the Angular project folder:
cd angular-client
-
Install dependencies:
npm install
-
Start the dev server:
ng serve
-
Open:
http://localhost:4200
Angular NotificationService
example:
getServerEvents() {
const source = new EventSource('https://localhost:7073/api/v1/Notifications/getstream');
source.onmessage = event => {
this.messages.push(event.data);
};
source.onerror = error => {
console.error('SSE Error:', error);
source.close();
};
}
-
Go to the Next.js project folder:
cd nextjs-client
-
Install dependencies:
npm install
-
Start the dev server:
npm run dev
-
Open:
http://localhost:3000
Next.js SSE example (app/page.tsx
):
"use client";
import { useEffect, useState } from "react";
export default function Home() {
const [messages, setMessages] = useState<string[]>([]);
useEffect(() => {
const source = new EventSource("https://localhost:7073/api/v1/Notifications/getstream");
source.onmessage = (event) => {
setMessages((prev) => [...prev, event.data]);
};
source.onerror = (err) => {
console.error("SSE error:", err);
source.close();
};
return () => {
source.close();
};
}, []);
return (
<div style={{ color: "#000", background: "#fff", padding: "1rem" }}>
<h2>NotificaΓ§Γ΅es</h2>
{messages.map((msg, index) => (
<div key={index}>{msg}</div>
))}
</div>
);
}
This project is licensed under the MIT License.