frandiox / vite-ssr

Use Vite for server side rendering in Node
MIT License
823 stars 91 forks source link

What should I do if the client repeatedly renders after SSR? #209

Closed youyuByChina closed 1 year ago

youyuByChina commented 1 year ago

Thank you for your excellent code that helped me!

After packaging and publishing to the server through vite-ssr build, the server has already sent the complete HTML+CSS+JavaScript to the client's browser (i.e. SSR). However, the client browser will re render the entire interface. How can we avoid duplicate rendering by the client? After all, the server has already sent the complete HTML+CSS+JavaScript to the client, and the client's browser can directly parse HTML+CSS+JavaScript, so there is no need to perform client rendering (i.e. CSR) again.

Here is my server deployment code. Can you help me see why the client renders repeatedly? Is it a configuration issue with packaging or a deployment issue?

global.fetch = require("node-fetch");
const path = require("path");
const express = require("express");
const dist = `../dist`;
const { ssr } = require(`${dist}/server/package.json`);
const manifest = require(`${dist}/client/ssr-manifest.json`);
const renderPagePromise = import(`${dist}/server/main.js`).then(
  (result) => result.default
);
const api = require("./api");
const server = express();
for (const asset of ssr.assets || []) {
  server.use(
    "/" + asset,
    express.static(path.join(__dirname, `${dist}/client/` + asset))
  );
}

api.forEach(({ route, handler, method = "get" }) =>
  server[method](route, handler)
);

server.get("*", async (request, response) => {
  const url =
    request.protocol + "://" + request.get("host") + request.originalUrl;
  const renderPage = await renderPagePromise;
  const { html, status, statusText, headers } = await renderPage(url, {
    manifest,
    preload: true,
    request,
    response,
  });

  response.type("html");
  response.writeHead(status || 200, statusText || headers, headers);
  response.end(html);
});

server.listen(9303);

This is the file structure that I packaged through vite-ssr build image

After SSR renders the complete HTML+JavaScript+CSS, it sends it to the client, and the client's browser renders it again, which is a waste of performance. I hope you can help me. Thank you very much.