Blog>
Snippets

Streaming Server-Side Rendered Content

Stream server-side rendered content with a simple loading UI until the full page is delivered to the client.
const http = require('http');
const { Readable } = require('stream');

// Sample server-side rendering function
function renderPart(data) {
    // Dummy function to simulate part of a template rendering
    return `<div>${data}</div>`;
}

const server = http.createServer((req, res) => {
    res.writeHead(200, {'Content-Type': 'text/html'});
    // Opening HTML before data is fully loaded
    res.write('<html><head><title>Streaming SSR Example</title></head><body>');
    res.write('<h1>Loading content...</h1>');

    // Simulating a stream of data
    const stream = new Readable({
        read(size) {
            setTimeout(() => {
                this.push(renderPart('Part of the page loaded'));
                this.push(null); // No more data
            }, 1000); // Simulating async operation
        }
    });

    stream
        .on('data', (chunk) => {
            res.write(chunk);
        })
        .on('end', () => {
            res.write('</body></html>');
            res.end();
        });
});

server.listen(3000, () => {
    console.log('Server running at http://localhost:3000/');
});
This JavaScript code sets up an HTTP server that streams server-side rendered content. It creates an HTML skeleton, then simulates an asynchronous data stream, rendering and pushing parts of the content to the client. When the stream ends, it closes the HTML document.