Wdrożenie Informowanie o czasie rzeczywistym in Javascript Aplikacje Web
Real- time notifications have a cornerstone of modern web application design. Users expect instant feed back when events occur: a new chat message arrives, a collegage approves a document, or a server alert triggers. Building this functionality into a JavaScript web app cesss careful planning, thee right communicatoon procurs, and thoydful UI Design. This guidee walks you dioptig implementing real- timationg, time notificions using WebSocketandd Server- Sent Events (SSE), integrating them backend lics, antud Directud, anensuring a polhed, productiong.
Dlaczego naprawdę -Notyfikacje czasu Matter
Real- time notifications eliminate thee need d for manual page refreshes or polling, which drains bandwidth and degrades user experience. When a user receives an instant alert, they stay actived and can react promptly. For SaaS platforms, collaboration tools, or e-commerce dashboards, this exacy directly impacts productivity and actionion. Studies show that reducing notification latency from seconsecondiscon caudiscon boost rest rest ven ver 20% (ver 1; FLT: 0; FLT: 3XD; next; ND; ND; ND; ND; ND; ND; ND; ND; ND; NT; NT; NT; 1T;
Beyond user experience, real-time notifications also enable new interaction Patterns: live comparat streams, collaborative editing cursors, and server-side event feds. Choosing the right t transport layer is the first technical decision.
WebSocket: Full- Duplex Communication
Refl1; FLT: 0 is 3; WebSockets present 1; Refl1; FLT: 1 is 3; FLT: 1 is 3; Suppore a persistent, bidirectional channel between a client andd server. Unlike HTTP, the connection stays, live financial feed, and multiplayer games - any measo where low-ency, two-way mesaging critiail.
Założenie WebSocket Connection in JavaScript
Then browser 's nativie injection 1; Xi1; FLT: 0 is 3; Xi3; API makes connection setup exactörord. You instantiate a new direction 1; Xi1; FLT: 1 directu3; object with the server' s URL (using the direcodes 1; XI1; FLT: 2 direcodes 3; scheme for secre connections). Then attach event listeners for direcoder 1; XIF: 3; FLT: 3; X3; FLT; X3; XE 1; FLT: 3; FLT: 3; FLT: 3; FLT; FLT: 4 direcoder. 3; FLT; 3.
const socket = new WebSocket('wss://api.directus.app/websocket');
socket.onopen = () => {
console.log('WebSocket connection established.');
// Optionally send an authentication token
socket.send(JSON.stringify({ type: 'auth', token: 'your-jwt' }));
};
socket.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.type === 'notification') {
showToast(data.payload.message);
}
};
socket.onerror = (err) => {
console.error('WebSocket error:', err);
};
socket.onclose = (event) => {
console.warn('WebSocket closed:', event.code, event.reason);
// optional reconnect logic
};
After establishing the connection, you can send JSON-formatted messages and handle le responses in thee incorporation 1; direction 1; FLT: 8 connection, direc3; handler. The server must support the WebSocket protocol; many Node.js frameworks (e.g., direc.1; FLT: 9 context 3; directed 3; direc1; FLT: 10 contex3; direc3;) and CMRS backends like Directus offer built-in or plugin-based Web Socket support.
Handling Reconnection andd Heartbeats
A robut real- time system mutt handle network interruptions gracefuly. Wdrożenie reconnection strategiy that backs of f wykładniczy:
function connectWebSocket() {
const socket = new WebSocket('wss://api.directus.app/websocket');
let retryDelay = 1000;
socket.onclose = () => {
setTimeout(() => {
console.log('Reconnecting...');
connectWebSocket();
}, retryDelay);
retryDelay = Math.min(retryDelay * 2, 30000);
};
// ...other handlers
}
connectWebSocket();
Dodatek, send periodic heartbeat pings (every 30- 60 seconds) to detect stale connections. Many WebSocket libraries handle thi automatically, but if you 're using thee raw API, set an interval to send a meat.1; FLT: 12 mettle3; message and expect a methall 1; FLT: 13 methle3; FLT 3response.
Server- Sent Events: Simpler, One- Way Streaming
W przypadku gdy w ramach programu nie ma już żadnych informacji, należy podać, że w przypadku gdy w danym programie nie ma żadnych informacji, które mogłyby być dostępne, należy podać dane dotyczące klientów, które nie są dostępne.
SSE is simpler to implement than WebSockets, works over HTTP / 2, and automatically reconnects the connection drops. However, it does not support bidirectional communication, so it 's best suppled for news feed, stock tickers, or system alerts.
Using EventSource in the Browser
Te browser 's preci1; Xi1; FLT: 16 precidi3; Xi3; interface is minimal:
const eventSource = new EventSource('/api/events?user_id=42');
eventSource.onopen = () => {
console.log('SSE connection opened.');
};
eventSource.addEventListener('notification', (event) => {
const data = JSON.parse(event.data);
displayNotification(data);
});
eventSource.onerror = (err) => {
console.error('EventSource error:', err);
// The browser will automatically attempt to reconnect
};
function displayNotification(data) {
// Update UI
}
On thee server side, you format each event as text lines:
event: notification
data: {"message":"Your report is ready","severity":"info"}
Note that thee eng1; Xi1; FLT: 19 context 3; Xi3; API only supports GET requests and cannot t send conserm headers. If you need to pass uwierzytelniania tokens, addid them as query parameters (use HTTPS to avoid exposing thee token).
WebSocket vs. SSE: Choosing the Right Approach
Both technologies are e capable of handling real- time notifications, but they serve different use case:
| Feature | WebSocket | SSE |
|---|---|---|
| Direction | Bidirectional | Server → Client only |
| Auto‑reconnect | Must implement manually | Built‑in |
| Binary data | Yes (ArrayBuffer, Blob) | Text only (UTF‑8) |
| Browser support | Excellent (IE10+) | Good (no IE/Edge Legacy) |
| Complexity | Higher | Lower |
If the the client needs to send commands or data back to the server (np., marking a notification as read), WebSocket is the natural choice. For simple notification feed, SSE reduces development overhead and is easyr to debug because it uses standard HTTP headers.
Integriting Real- Time Notifications with Directus
Rev.1; Xi1; FLT: 0 + 3; Directus Xi1; Xi1; FLT: 1 + 3; Xi3; is a headless CMS that exposes a REST and GraphQL API. To add real- time capabilities, you can leverage its WebSocket support (informud in Directus 10.x) or set up an SSE endpoint via custem extension. Thee WebSocket API allows you to subskrybe tlo changes on specific collections, making it exaford two push notifications when a new.
WebSocket Subscription in Directus
Directus WebSocket endpoint (Xi1; Xi1; FLT: 20 Xi3; Xi3;) akceptuje wiadomości JSON to subskrybe, unsubskrybbbe, or authenticate. For example, to listen for new messages in a Xiun1; Xion1; FLT: 21 Xion3; Xion3; collection:
const ws = new WebSocket('wss://cms.example.com/websocket');
ws.onopen = () => {
// Subscribe to changes on the notifications collection
ws.send(JSON.stringify({
type: 'subscribe',
collection: 'notifications',
query: { filter: { user_id: { _eq: currentUserId } } }
}));
};
ws.onmessage = (event) => {
const msg = JSON.parse(event.data);
if (msg.type === 'subscription' && msg.event === 'create') {
showNotification(msg.data);
}
};
Thile approach offloads thee compledity of real- time synchronization te te CMS, while you JavaScript app only neds to handle the incoming data. For authentiation, send a token in thee first WebSocket message (as shown earlier).
Wyświetlanie powiadomień o ich użyciu
Once you have thee data, thee user experience depends on how you present it. Styled toast notifications are te e most compatin parafine: a small, non-intrusive popup that appears at te hourr of thee screen and auto-disses after a few seconds. Libraries like present 1; FOR 1; FOR: 0 Provide 3; TOastr present 1; FOR 1; FOR 1 Provident 3; FOR 3; FOR 3; FOR 3; FOR 3L 3D; FOL: 2 Reference 3; FOR 3XD; FOR 1F; FOR 1OF; FOR 3D; FLT: 1BL; SON 1R; FLT: 5; FLT: 3XD; FLT: 3XD; FLT: 3XD; FLT: 3XD
Alternatywne, build a custem notification contribuent. Here 's a minimal example using vanilla JavaScript andd CSS:
function showToast(message, type = 'info') {
const toast = document.createElement('div');
toast.className = `toast toast-${type}`;
toast.textContent = message;
toast.setAttribute('role', 'alert');
document.getElementById('toast-container').appendChild(toast);
setTimeout(() => toast.remove(), 3000);
}
// CSS (simplified):
.toast {
padding: 12px 20px;
margin-bottom: 8px;
border-radius: 4px;
color: #fff;
opacity: 0.9;
transition: opacity 0.3s;
}
.toast-info { background: #007bff; }
.toast-error { background: #dc3545; }
.toast-success { background: #28a745; }
Make sure thee container is fixed tich top-right rogder and that toasts stack vertically. Use container 1; eng.1; FLT: 24 contain3; eng3; on thee container to ensure screen readers invecte new notifications.
User Preferences andNotification Management
Nie ma powodu, by się o tym martwić, ale nie chcę, żeby ktoś się o to troszczył.
In your JavaScript app, periodically fetch the user 's preference profile and adjuss the subscription filters accordingly. If using Directus WebSockets, you can send an updated subscription query wheen preferences change.
Fallback for Unsupported Browsers
While modern browsers broadly support WebSockets andd SSE, older environments (np., Internet Explorer 11 for WebSockets, IEE / Edge Legacy for SSE) may require polyfuels or fallback strategies. A compact:
- Xi1; Xi1; FLT: 0 Xi3; Xi3; Detect support Xi1; Xi1; FLT: 1 Xi3; Xi3; Witch Xi1; Xi1; FLT: 25 Xi3; Xi3; Or Xi1; Xi1; FLT: 26 Xi3; Xi3;.
- W przypadku gdy w wyniku zastosowania środka nie ma zastosowania art. 3 ust. 1 lit. a), w przypadku gdy środek jest stosowany w celu zapewnienia, aby środek nie został uznany za pomoc państwa, należy go uznać za pomoc państwa.
- Xi1; Xi1; FLT: 0 Xi3; Xi3; Library abstraction Xi1; Xi1; FLT: 1 Xi3; Xi3;: Use a library like Xi1; Xi1; FLT: 27 Xion3; Xion3; that transparently falls back frem WebSocket to HTTP long-polling.
When polling, set a rearable interval (np., 5-10 seconds) and return an empty responsie if no events are pending. Tu reduce load, use eng1; engine 1; FLT: 28 contex3; eng3; headers or timestamp-based queries.
Kwestie bezpieczeństwa
Real- time connections inpute e serelal security vectors that mutt be adressed:
- Xi1; Xi1; FLT: 0 XI3; XI3; Authenticate every connection XI1; XI1; FLT: 1 XI3; XI3;. For WebSockets, send a JWT or session token in thee first message. For SSE, append a token as a query parameter (but never it the URL if you log it).
- Xi1; Xi1; FLT: 0 XI3; XI3; Validate and sanitize all data XI1; XI1; FLT: 1 XI3; XI3; before pushing it to the client. Even if your backend is trusted, never output raw user-generated content into a notification with out escape ing.
- (Dz.U. L 311 z 15.11.2014, s. 1).
- Reference: 1; Reference: 1; FLT: 0 Revenge 3; Revenge 3; Rate-limit connections; Revenue 1 Reveny3; Revenge 3; per user to prevent abuse. Directus exposes rate-limiting settings that you can configue.
- Xi1; Xi1; FLT: 0 Xi3; Xi3; Do not expose internal server state Xi1; Xi1; FLT: 1 Xi3; Xi3; Treagh WebSocket or SSE messages. Always return only the te data the user is authorized tu see.
Wykonanie i skalability
To jest number of concurrent connections grows, you server must efficiently manage them. Consider these optimizations:
- Xi1; Xi1; FLT: 0 Xi3; Xi3; Usie a decretated WebSocket server Xi1; Xi1; FLT: 1 Xi3; Xi3; (np., separate Node.js process) and scale horizontally with a load balancer that supports WebSocket sticky sessions.
- Reference: 1; Department 1; FLT: 0 Department 3; Description 3; Description 3; Description 3; Description 3; Description 3; Description 3; Description.
- Xi1; Xi1; FLT: 0 Xi3; Xi3; Compress messages Xi1; Xi1; FLT: 1 Xi3; Xi3;. For text-based procols, enable per-message deflate (WebSocket) or gzip (SSE over HTTP / 2).
- Xion1; Xion1; FLT: 0 Xion3; Xion3; Xion3; Monitoring connection health Xion1; Xion1; FLT: 1 Xion3; Xion3; FLT: 0 Xion3; Xion3; Xion3; Xion3; Xion3; Xion3; Xion1; Xion1; Xion1; Xion1; Xion1; Xion1; Xion1; Xion1; Xion1; Xion1; Xion3; Xion3; Xion3; Xion3; Xion3; Xion3; Xion3; Xion3; Xion3; Xyyxykyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy@@
- Xiv1; Xiv1; FLT: 0 XI3; XIX3; Consider server-sent events caching Xiv1; XI1; FLT: 1 XI3; XIX3; XIX3;. With SSE, you can leverage HTTP caching headers if the stream im is static for a period (though notifications are usually dynamic).
Putting It All Together: A Complete Workflow
Tu illustrate a real-worldd example, let 's combinate a Directus backend with a JavaScript frontend that uses SSE for notifications.
- Xi1; Xi1; FLT: 0 is 3; Xi3; Backend (Directus Extension): Xi1; FLT: 1 is 3; Xi1; FLT: 1 is; Flete a create endpoint at ere1; Xi1; FLT: 31 is 3; That checks the user 's JWT token, then streams new notifications from frem a queue (e.g., Redis pub / sur a Directus hook that writes to a mexide 1; FLT: 32 mexide 3contribuiltion). The endpot returns div.1; FLT: 3phyphad; 33d;
- Xi1; Xi1; FLT: 0 Xi3; Xi3; Frontend: Xi1; Xi1; FLT: 1 Xi3; Xi3; Upon page load, uwierzytelnione With Directus andd open an Xi1; Xi1; FLT: 34 XI3; Xi3; pointing to Xif1; Xif1; FLT: 35 XI3; XI3; XI1; FLT: 36 XIf3; XI3; Xents.
- Xi1; Xi1; FLT: 0 Xi3; Xi3; Display: Xi1; Xi1; FLT: 1 Xi3; Xi3; Each received notification is rendered as a toast using a crest contrient, with options to requis or open thee related resource.
- W przypadku gdy nie można określić, czy dany produkt jest przeznaczony do produkcji, należy podać numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny
This architecture keeps the client lean and pushes the heavy lifting to Directus ande it hook system.
Testing Real- Time Notifications
Before deploying, cwany tect your implementation:
- Xi1; Xi1; FLT: 0 Xi3; Xi3; Load testing: Xi1; Xi1; FLT: 1 Xi3; Xi3; FLT: 1 XI3; Xi1; FLT: 2 XI3; XI3; FLT: 3 XI3; XI3; TO simulate hundreds of concurrent WebSocket or SSE connections. Measure latency andd connection stability.
- Xi1; Xi1; FLT: 0 XI3; XI3; Network throttling: XI1; XI1; FLT: 1 XI3; XI3; FLT: 0 XI3; FLT: 0 XI3; XI3; XI3; Network threttling: XI1; XI1; FLT: 1 XI3; XI3; XI3; FLT: 1 XI3; FLT: XI1; FLT: 0 XIXIXIXIXIXIXIXIXIXIXIXIXIXIXIXIXIXIXIXIXIXYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY@@
- Xi1; Xi1; FLT: 0 Xi3; Xi3; Cross-browser testing: Xi1; Xi1; FLT: 1 Xi3; Xi3; Tess in Firefox, Safari, Chrome, and Edge. For SSE, tect in Safari (which lacks full EventSource support for conserm events - you may need to use a polyfill).
- Xi1; Xi1; FLT: 0 Xi3; Xi3; Security edge cases: Xi1; Xi1; FLT: 1 Xi3; Xi3; Attempt to connect with Xired tokens, or inject malformed JSON to ensure your error handlers don 't crash the client.
Konkluzja
Real- time notifications are no longer a luxury; they are a baseline expectation in modern web applications. By leveraging WebSockets or SSE, combined with a backend like Directus that provides real-time hooks, you can deliver instant updates updates with out subsiming your infrastructure. Focus on user customization, graceful fallbacks, and robuss conficatione to cure a notification system that feelles and relieble.
Start small: implement a simple toast for on e even type, then gradually exploid to multiple channels andd user preferences. The key is to iterate on thee user experience while keeping thee underlying transport efficient and maintainable. With the the approaches outlined here, you 'll be well on your way to a production-ready ready l-time emplure.