Lesson 24-Preact and Server-Side Rendering

Server-Side Rendering (SSR) is a technique for generating HTML pages on the server and sending them to the client, rather than relying on client-side JavaScript to render the page. Preact supports SSR, offering faster initial page loads, better SEO, and compatibility with devices that don’t support JavaScript.

Setting Up the SSR Environment

Installing Required Packages

Ensure you have installed Preact and the necessary SSR-related packages.

npm install preact preact-render-to-string express

Here, we use Express as the server-side HTTP framework.

Creating an SSR Server

Set up a basic Express server to render Preact components.

// server.js
const express = require('express');
const { renderToString } = require('preact-render-to-string');
const App = require('./src/App').default;

const app = express();

app.get('/', (req, res) => {
  const html = renderToString(<App />);
  res.send(`
    <!DOCTYPE html>
    <html>
      <head>
        <title>Preact SSR Example</title>
      </head>
      <body>
        <div id="root">${html}</div>
        <script src="/bundle.js"></script>
      </body>
    </html>
  `);
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

Rendering Components to Strings

Using renderToString

The preact-render-to-string package provides the renderToString method to convert Preact components into HTML strings.

const html = renderToString(<App />);

Handling Asynchronous Data Fetching

Importance of Asynchronous Data Fetching

In SSR, you must fetch all necessary data before rendering components to avoid incomplete or incorrect pages.

Using getInitialProps

In Preact components, you can define a static getInitialProps method to fetch initial data.

// src/App.js
import { h, Component } from 'preact';

class App extends Component {
  static async getInitialProps() {
    const response = await fetch('/api/data');
    const data = await response.json();
    return { data };
  }

  render({ data }) {
    return (
      <div>
        <h1>Data from Server:</h1>
        <pre>{JSON.stringify(data, null, 2)}</pre>
      </div>
    );
  }
}

export default App;

On the server side, call getInitialProps before invoking renderToString.

// server.js
const App = require('./src/App').default;

app.get('/', async (req, res) => {
  const initialProps = await App.getInitialProps();
  const html = renderToString(<App {...initialProps} />);
  // ...
});
Share your love