Implementing Server-Sent Events (SSE) in Next.js API can be achieved by creating an API route that responds to HTTP requests and streams events to the client. Below are detailed steps and examples:
Step 1: Create a Next.js API Route
First, create a Next.js API route to handle SSE. In your Next.js project, create a new file in the pages/api directory, such as events.js.
Step 2: Set HTTP Response Headers
Set the correct HTTP response headers to indicate an event stream.
Step 3: Send Events
Send events to the client using the appropriate format, typically a line starting with data:, followed by the actual data, and ending with two newline characters.
Step 4: Maintain the Connection
Maintain the connection to continuously send events. If the connection is closed, handle reconnection logic on the client side.
Example Code
javascript// pages/api/events.js export default function handler(req, res) { // Set HTTP headers for event stream format res.writeHead(200, { Connection: 'keep-alive', 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', }); // Function to send events const sendEvent = (data) => { res.write(`data: ${JSON.stringify(data)}\n\n`); }; // Send an initial event sendEvent({ message: 'Connection established' }); // Set a timer to simulate event sending const intervalId = setInterval(() => { sendEvent({ dateTime: new Date().toISOString() }); }, 5000); // If the request is closed, clear the timer req.on('close', () => { clearInterval(intervalId); res.end(); }); }
Client Code Example
On the client side, use EventSource to connect to the API route created above and listen for events.
javascript// Client JavaScript const evtSource = new EventSource('/api/events'); evtSource.onmessage = (event) => { const data = JSON.parse(event.data); console.log('Received new event:', data); }; // Handle errors evtSource.onerror = (error) => { // Handle connection errors console.error('EventSource error:', error); evtSource.close(); };
When using SSE, note that Server-Sent Events (SSE) is a unidirectional channel, used only for server-to-client communication. For bidirectional communication, consider using WebSockets.
Note that since SSE requires maintaining a long-lived connection, it may not be compatible with Next.js's serverless environment, as serverless functions typically have execution time limits. If your Next.js application is deployed in a serverless environment, you may need to use other real-time data transmission solutions, such as WebSockets or third-party services.