SSR Demystified

tldr; it's not complicated at all 🤫

Don't let lingo like SSR/ CSR confuse you -- there's really just two major ways to serve HTML over an HTTP server in JS - either the server sends the HTML to the client (ssr) or the client generates the HTML for itself (csr/ spa) by using the Web API.

To demystify SSR we are going to look at the world's simplest dynamic SSR example:

// Let's create a server
import express from 'express';

const app = express();

function generateHTML() {
  const date = new Date();
  const localTime = date.toLocaleTimeString();
  const localDate = date.toLocaleDateString();
  const doc = `
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Wow</title>
  </head>
  <body>
    <span>Hello World!</span>
    <span> The date is ${localDate}</span>
    <span> It's currently: ${localTime} </span>
  </body>
</html>
`;
  return doc;
}

// Every get request to the '/' page will send the current date and time to the client
app.get('/', (req, res) => {
  const doc = generateHTML();
  res.send(doc);
});

const port = process?.env?.PORT ?? 3000;

app.listen(3000, () => {
  console.log(`🚀 Live on http://localhost:${port}`);
});

That's it.