Implementation Plan:
a. Build Process:
- We'll have a build step that runs for each route (or for each entry point if we are using code splitting for routes).
- For each route, we generate:
- A critical CSS chunk (only the CSS needed for the initial paint of that route).
- A full CSS chunk (the entire CSS for the application, or at least for the chunk that includes the route).
However, note that we are in a monolithic setup, so we might have one big CSS file for the entire app. But we can still split the critical CSS per route and then have the full CSS file.
How about:
- We build the entire CSS (all routes) into one file: `app.css`.
- Then, for each route, we extract the critical subset and store it as a separate file (or in a map) so that we can inline it for that route.
But wait, if we have one big CSS file, then the critical CSS for each route is just a subset of that one file?
Alternatively, we can do:
- Build the CSS per route (if we have code splitting for CSS, then each route might have its own CSS chunk). But the requirement says "monolithic", so let's assume one CSS file.
Let me re-read: "monolithic CSS extraction plan splitting per-route critical CSS"
It might mean that we have one CSS file (monolithic) but we split the critical parts per route and inline them. Then we load the monolithic CSS file asynchronously.
So:
- `app.css`: contains all CSS for the entire app (maybe built from multiple CSS modules, but bundled into one).
- For each route, we have a `critical-[route].css` (or we store them in a JSON map) that contains only the critical rules for that route (and we can inline that in the HTML for that route).
But note: if we inline the critical CSS for each route, then we are inlining different CSS for different routes. That's acceptable because the HTML for each route is different.
b. Server-side Rendering (SSR) with Streaming:
For a request to a route (say `/about`):
1. We start the response and write the initial HTML chunk.
2. In the `<head>` of the initial chunk, we inline the critical CSS for the `/about` route (from `critical-about.css` or from a map).
3. We also include a `<link>` for the full `app.css` but with `rel="preload"` and `as="style"` and then switch it to `rel="stylesheet"` via JavaScript? Or we can use `media="print"` and then change to `all` on load.
Example:
```html
<head>
<style id="critical-css">/* critical CSS for about page */</style>
<link rel="preload" href="/app.css" as="style" onload="this.rel='stylesheet'">
<noscript><link rel="stylesheet" href="/app.css"></noscript>
</head>
```
4. Then we stream the rest of the HTML (the body) and then we can start hydrating.
But note: we are using React (or similar) with streaming hydration. We might use `ReactDOM.hydrate` or `ReactDOM.createRoot` with `hydrate: true`? Actually, for streaming we use `ReactDOM.hydrate` on the client?
Actually, with streaming SSR, we send the HTML in chunks and then the client hydrates when it receives the closing `</body>` or when the entire HTML is received?
Alternatively, we can use `ReactDOM.hydrate` on the client and it will wait for the entire HTML? Not exactly, with streaming we can use `ReactDOM.hydrate` on the client and it will start hydrating as soon as the root node is available?
But note: we are inlining critical CSS, so the initial paint can happen without waiting for `app.css`.
c. How to generate critical CSS per route?
We need to run a critical CSS extraction for each route. We can do this at build time.
Steps for build:
- For each route (we have a list of routes, maybe from our router configuration or from the pages directory if using Next.js-like structure), we:
- Render the route to static HTML (or to a virtual DOM that we can analyze) without the full CSS.
- Then, we use a tool (like `critters` or `penthouse`) to generate the critical CSS by taking a screenshot (or by analyzing the DOM and styles) and see which rules are used in the above-the-fold content.
However, note that `penthouse` requires a URL and a viewport, so we might need to run a headless browser for each route. That can be slow.
Alternatively, we can use `critters` which can work on a static HTML string and the CSS file(s). But note: we are in a monolithic CSS setup, so we have one CSS file.
We can use `critters` in the following way for each route:
```javascript
const critters = require('critters');
const fs = require('fs');
const html = fs.readFileSync(`./build/routes/${route}/index.html`, 'utf8');
const css = fs.readFileSync('./build/app.css', 'utf8');
critters(html, {
// options
css: css,
// We want to extract the critical CSS for this route and then inline it, and remove the critical rules from the original CSS?
// But note: we are not going to use the original HTML from the route, we are going to use the critical CSS in our streaming HTML.
// Actually, we don't want to modify the original HTML because we are streaming. We just want the critical CSS string.
// critters by default inlines the critical CSS and leaves the rest in a new CSS file. But we don't want that because we have one monolithic CSS.
// Instead, we want to extract the critical CSS and then we will inline that in the HTML for the route, and then load the full `app.css` asynchronously.
// So we can use `critters` with the `extract` option? Actually, critters doesn't have an extract option, it inlines and then removes from the CSS.
// Alternatively, we can use `penthouse` which just returns the critical CSS as a string.
});
```
Since we want to keep the monolithic CSS, we might use `penthouse`:
```javascript
const penthouse = require('penthouse');
const fs = require('fs');
const html = fs.readFileSync(`./build/routes/${route}/index.html`, 'utf8');
const css = fs.readFileSync('./build/app.css', 'utf8');
penthouse({
css: css,
html: html,
// ... other options like dimensions, etc.
}, (err, criticalCSS) => {
// Save criticalCSS for this route.
});
```
But note: `penthouse` requires a running server? Actually, it can take a string of HTML and CSS.
However, `penthouse` is designed to work with a URL and a headless browser? Actually, it can work with strings too.
But there's a caveat: we need to make sure that the HTML string we pass includes all the elements that are above the fold, and that the CSS is the same as the one we serve.
Also, note that the HTML we generate for the route (for SSR) might be different from the one we use for critical CSS extraction? We want to use the same HTML that we will serve.
So, we should generate the HTML for the route (with all the components) and then use that HTML string for critical CSS extraction.
But wait: the HTML we serve for a route might be different for each user? In a static site, no. In a dynamic site, we might have user-specific content. We cannot generate critical CSS for every user. So we assume that the above-the-fold content is the same for all users for a given route.
So, we generate the HTML for the route without any user-specific data (or with placeholder data) and then extract critical CSS.
This is a common practice.
d. Storage of Critical CSS:
We can store the critical CSS for each route in a file (e.g., `critical-${route}.css`) or in a JSON file that maps route to critical CSS string.
Then, at runtime (on the server), we read the critical CSS for the requested route and inline it.
But note: if we have many routes, we might have many critical CSS files. We can also combine them into one JSON file and load it at server start.
Alternatively, we can embed the critical CSS in the server code? Not recommended if it's large.
We can have a `critical.css` map:
```json
{
"/": "...",
"/about": "...",
"/contact": "..."
}
```
And then load this JSON at server start and then for each request, we look up the route (or the closest route if we have dynamic routes).
But note: if we have dynamic routes (like `/users/:id`), we might not have critical CSS for every user. We can generate for a sample user? Or we can have a default critical CSS for all user pages? Or we can generate for a few sample users and then use the most common one?
This is a challenge. One approach is to have a fallback: if we don't have critical CSS for the exact route, we use the critical CSS for the parent route (or a default). Or we can generate critical CSS for the dynamic route by ignoring the dynamic part (so for `/users/123` we use the critical CSS for `/users/:id`). But that requires us to define the dynamic routes and generate for them.
Alternatively, we can generate critical CSS for each dynamic route pattern (like `/users/:id`) by using a sample dynamic value (like `123`). Then, when we get a request for `/users/456`, we use the same critical CSS because the structure is the same.
So, we need to have a mapping from route pattern to critical CSS.
How about:
- We define our routes (with dynamic segments) and then for each route pattern, we generate critical CSS using a sample value for each dynamic segment.
Then, at runtime, we match the request URL to the route pattern and use the corresponding critical CSS.
This requires that we have the same routing configuration on the server as on the client.
e. Streaming the HTML:
We are going to stream the HTML for the route. We have:
- The critical CSS for the route (from the map).
- The rest of the HTML (the body) which we can stream from the React render function? Actually, with React 18 and streaming SSR, we use `renderToPipeableStream` or `renderToString`?
We want to stream, so we use `renderToPipeableStream` (if using React 18). Then we can write the head (with the critical CSS) and then the body in chunks.
But note: the critical CSS must be in the head, and we want to send the head first? Actually, we can send the entire head (with critical CSS) in the first chunk, then stream the body.
Steps:
1. Start the response and write the beginning of the HTML and the head with critical CSS.
2. Then, we start the React streaming and pipe the body (which comes from `renderToPipeableStream`) to the response.
But wait: the head is already written? Then the React stream will only write the body? Actually, with `renderToPipeableStream` we can control what we write?
Alternatively, we can use `renderToString` and then send the entire HTML at once? But that doesn't stream.
With `renderToPipeableStream`, we get a stream that writes the entire HTML (including the head and body). We don't want that because we want to write the critical CSS in the head and then the body.
Actually, we can do:
- We write the head (with critical CSS and the link for the full CSS) and then we write the opening body tag and then we pipe the React stream (which will write the children of the body?).
But `renderToPipeableStream` by default writes a complete HTML document. We don't want that because we already wrote the head.
So, we can use `renderToPipeableStream` with the option `{ onShellReady: ... }` and then we can write the head and then pipe the body?
Actually, `renderToPipeableStream` returns a stream that we can pipe to the response, but it includes the entire document. We don't want to duplicate the head.
Alternatively, we can use `renderToStaticMarkup`? That doesn't include the head.
Let me think about the flow:
We want:
```html
<!DOCTYPE html>
<html>
<head>
<style id="critical-css">...</style>
<link rel="preload" href="/app.css" as="style" onload="this.rel='stylesheet'">
<noscript><link rel="stylesheet" href="/app.css"></noscript>
</head>
<body>
<div id="root">...streamed content...</div>
<script>...</script>
</body>
</html>
```
We can generate the head (with critical CSS) on the server and then stream the body from React.
How?
We can use `renderToPipeableStream` for the children of the body? Actually, we can use `renderToString` for the children and then write them as a string? But that doesn't stream.
Alternatively, we can use `renderToPipeableStream` for the entire React tree (which will generate the body content) and then we write the head and the opening body tag, then pipe the React stream, and then write the closing body and html tags?
But `renderToPipeableStream` will generate a complete HTML document? Actually, by default, `renderToPipeableStream` will generate a complete HTML document if you pass a React element that is the entire document?
We are probably rendering a React component that is the entire page (without the head). So we can do:
```javascript
const { pipe } = renderToPipeableStream(
<App />,
{
onShellReady() {
// We are ready to stream the body? But we haven't written the head yet.
}
}
);
```
Actually, the stream from `renderToPipeableStream` will write the entire HTML document? Let me check the React 18 docs.
According to the React 18 docs, `renderToPipeableStream` can be used to stream the entire HTML document. But we want to control the head.
So, we might have to split:
- Head: generated by us (with critical CSS and the link for the full CSS).
- Body: generated by React (streamed).
How about we use `renderToStaticMarkup` for the body? That doesn't stream.
Alternatively, we can use `renderToPipeableStream` for the entire document but then we have to inject the critical CSS into the head. That's tricky because the stream is already writing the head.
Another idea: we can use `renderToPipeableStream` and then intercept the stream to modify the head? That's complex.
Maybe we should use a different approach:
- We write the head (with critical CSS) and then we use `renderToString` for the body? But then we don't get streaming for the body.
Wait, we are streaming the entire response, but the body is generated by React. We want to stream the body as React generates it.
So, we want to combine:
- A static head (with critical CSS) and a static link to the CSS.
- A streamed body (from React).
We can do:
```javascript
res.write(`<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style id="critical-css">${criticalCSS}</style>
<link rel="preload" href="/app.css" as="style" onload="this.rel='stylesheet'">
<noscript><link rel="stylesheet" href="/app.css"></noscript>
</head>
<body>
<div id="root">`);
const { pipe } = renderToPipeableStream(
<App />,
{
onShellReady() {
pipe(res);
},
onError(error) {
console.error(error);
res.end();
}
}
);
// But note: the React stream will write the entire HTML for the App? It will write the opening div for the root? Actually, we already wrote the opening div for the root. We don't want two.
So we should not write the opening div for the root? But then React will write it.
Actually, we are rendering the entire App, which includes the root div? In a typical React app, we have:
```jsx
ReactDOM.hydrate(
<App />,
document.getElementById('root')
);
```
But in the server, we render:
```jsx
<App />
```
And then we put it inside a div with id="root"?
So the server HTML should be:
```html
<div id="root"><!-- React rendered content --></div>
```
So we are writing:
```html
<div id="root>
```
and then we want to pipe the React stream which should write the content of the root div? But React will write the entire element?
Actually, if we render `<App />` and the App returns a div, then we will have two divs?
We should not write the `<div id="root">` manually. Instead, we should let React render the entire root element.
So:
We write:
```html
<body>
```
Then we pipe the React stream which will write:
```html
<div id="root">...</div>
```
Then we write:
```html
<script>...</script>
</body>
</html>
```
But then we have to write the script tag after the React stream? We can do:
```javascript
res.write(`<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style id="critical-css">${criticalCSS}</style>
<link rel="preload" href="/app.css" as="style" onload="this.rel='stylesheet'">
<noscript><link rel="stylesheet" href="/app.css"></noscript>
</head>
<body>`);
const { pipe, abort } = renderToPipeableStream(
<App />,
{
onShellReady() {
pipe(res);
},
onAllReady() {
// When the entire React tree is ready, we can write the script and close the body?
// But note: we are streaming, so we might not want to wait for onAllReady to write the script?
// Actually, we want to write the script as soon as the root is ready?
// The script should be at the end of the body.
}
}
);
// But how do we know when the React stream is done? We can listen to the 'end' event on the res? Actually, the pipe will end when the React stream ends.
// Alternatively, we can write the script and close the body after the React stream ends.
// But note: we are using `pipe(res)`, so when the React stream ends, the res will end? Not necessarily, we can write more after?
// Actually, when we pipe, the res will be ended when the React stream ends? We don't want that because we want to write the script.
// So we should not use pipe? We can read the React stream and write it to res, and then when the React stream ends, we write the script and end the response.
// But then we lose the benefit of piping? We can do:
let reactStreamEnded = false;
const reactStream = renderToPipeableStream(...); // This returns an object with a pipe method? Actually, it returns an object with a pipe method and also we can listen to events.
// We can do:
reactStream.pipe(res);
reactStream.on('end', () => {
res.write(`
<script src="/bundle.js"></script>
</body>
</html>
`);
res.end();
});
// But wait, the React stream will write the entire HTML for the App? That includes the root div? And then we write the script and close the body? That's okay.
// However, note that the React stream might write the closing body and html tags? We don't want that because we are writing them.
// So we must ensure that the React stream does not write the closing body and html. We can set `bootstrapScripts` to false? Actually, `renderToPipeableStream` does not add any scripts.
// We are in control of the entire document, so we write the head and the opening body, then the React stream writes the content (the root div and its children) and then we write the script and close the body.
// But wait: the React stream will write the root div and then when it's done, it will end? We don't want it to write the closing body and html.
// Actually, `renderToPipeableStream` only writes the content of the component you pass. So if we pass `<App />`, it will write the HTML for the App (which is the root div and its children). It does not write the body or html tags.
// So we are safe.
// But note: the React stream might write the root div and then we write the script inside the body? That's correct.
// So:
// 1. Write the beginning of the HTML, head with critical CSS, and opening body tag.
// 2. Pipe the React stream (which writes the root div and its children) to the response.
// 3. When the React stream ends, write the script tag and close the body and html.
// However, we also want to send the hydration script? We can include the bundle.js that does the hydration.
// But note: we are using streaming hydration, so the client will hydrate when it receives the entire HTML? Or when the root div is available?
// Actually, with React 18 streaming, the client uses `createRoot` and then `hydrate`? The client will wait for the entire HTML? Not necessarily, but we are inlining the critical CSS so the initial paint can happen without waiting for the full CSS.
// We are also sending the full CSS asynchronously, so the page might look unstyled until the CSS loads? But we inlined critical CSS, so above-the-fold is styled.
// Now, what about the full CSS? We are preloading it, so it will be fetched early and then applied.
// This plan seems okay.
// But wait: what if the React stream takes a long time to generate? We are writing the head and then the body as it streams. That's fine.
// However, we must be cautious: the critical CSS is in the head, so the browser can start parsing the body and apply the critical CSS immediately.
// Also, we are preloading the full CSS, so it will be fetched in parallel.
// So the plan:
// - Build: generate `app.css` (monolithic) and critical CSS per route (or per route pattern).
// - Server: for each request, look up the critical CSS for the route (or pattern) and inline it.
// - Then, stream the React app (the body) and then write the script tag.
// But note: the React app might have client-side routing? We are doing SSR for the initial route, and then the client will take over.
// We must also include the bundle.js that does the hydration and client-side routing.
// So the script tag we write at the end should be the bundle that includes React and our app.
// We are assuming that the bundle.js is already built and available at `/bundle.js`.
// This plan is for a custom setup (not Next.js). If we are using Next.js, it handles a lot of this.
// But the question is about designing a plan, so we are designing a custom solution.
f. Caveats:
- Dynamic routes: we need a way to map a URL to a route pattern and then to the critical CSS for that pattern.
- Generation of critical CSS for dynamic routes: we generate for a sample value.
- The critical CSS might be large for some routes? We are inlining it, so it increases the HTML size. But it's only for the initial route.
- We must make sure that the critical CSS does not contain any @font-face rules that are not used? Actually, critical CSS extraction tools usually include @font-face if they are used. But we might want to preload fonts separately? That's a separate optimization.
- We are using a monolithic CSS, so the full `app.css` might be large. We are preloading it, so it will be fetched early, but it might block rendering? Actually, we are inlining critical CSS, so the page can render without it, but then when it arrives, it might cause a reflow? That's why we use `rel="preload"` and then switch to `stylesheet` on load.
- Alternatively, we can split the monolithic CSS into critical and non-critical? But the requirement says monolithic, so we keep it monolithic and then preload.
- Another idea: we can split the monolithic CSS into two: critical (which we inline) and non-critical (which we load asynchronously). But that would break the monolithic requirement? Actually, the requirement says "monolithic CSS extraction plan", meaning we have one CSS file for the entire app?
The requirement says: "monolithic CSS extraction plan splitting per-route critical CSS"
So we have one monolithic CSS file (for the entire app) and we split the critical CSS per route (so we inline the critical part for the current route). Then we load the monolithic CSS asynchronously.
But note: the monolithic CSS includes the critical CSS for all routes? Yes, so when we inline the critical CSS for a route, we are inlining a subset of the monolithic CSS. Then when the monolithic CSS loads, it will have the same rules again? That's duplication.
Actually, we are inlining the critical CSS and then loading the entire monolithic CSS. That means the critical rules are present twice: once in the style tag and once in the app.css. That's not efficient.
We want to avoid duplication. So we should remove the critical rules from the monolithic CSS? But then the monolithic CSS would be different for each route? That breaks the monolithic idea.
Alternatively, we can have the monolithic CSS without the critical rules? But then how do we get the critical rules? We extract them and inline, and then the monolithic CSS does not include them?
That would mean we have two CSS files: one for critical (inlined) and one for non-critical (the monolithic CSS without the critical rules). But then the monolithic CSS is not monolithic? It's split.
This is a problem.
Let me re-think:
We want:
- One CSS file for the entire app (monolithic) so that we don't have multiple CSS requests for SPA navigation.
- But we also want to inline critical CSS per route.
If we inline critical CSS and then load the monolithic CSS (which includes the same critical CSS), then we have duplication.
Solution:
We can have two CSS files:
1. `critical-[route].css` (inlined) - only the critical rules for that route.
2. `app-non-critical.css` (monolithic) - all the non-critical rules for the entire app.
Then, when we load `app-non-critical.css`, it will not have the critical rules (because they are inlined). But then when we navigate to another route, we might need to load a different set of critical rules?
Actually, for SPA navigation, we don't want to load a new CSS file. We want to load the entire app's CSS once. So we want the entire app's CSS to be in one file? But then we have duplication if we inline critical CSS.
Alternatively, we can have:
- `app.css` (monolithic) that contains all CSS (critical and non-critical) for the entire app.
- For each route, we inline the critical CSS (which is a subset of `app.css`).
- Then, when `app.css` loads, it will override the inlined critical CSS? Actually, the inlined critical CSS has higher specificity? No, they are the same. The order matters: the inlined CSS comes first, then the `app.css` comes later? Actually, the inlined CSS is in the head and then the `app.css` is preloaded and then applied? The order of application might be:
- The inlined CSS (critical) is applied first.
- Then, when `app.css` loads, it is applied and might override the inlined rules? But they are the same rules, so it doesn't matter.
But we are loading the same rules twice. That's wasteful.
So we need to remove the critical rules from `app.css`? Then `app.css` becomes the non-critical part. But then we have two files: one inlined (critical) and one non-critical (monolithic). But the non-critical file is monolithic in the sense that it contains all non-critical rules for the entire app? Yes.
Then, for a route, we inline the critical CSS and load the non-critical monolithic CSS. That way, we avoid duplication.
But then the non-critical monolithic CSS is the same for all routes? Yes, because it contains all non-critical rules for the entire app.
So:
- `critical-[route].css` (inlined) - critical rules for the route.
- `app-non-critical.css` (monolithic) - all non-critical rules for the entire app.
Then, when we navigate to another route (SPA), we don't need to load a new CSS file because `app-non-critical.css` already has all the non-critical rules. But what if the new route has different critical rules? We don't inline them again because we are in an SPA and we didn't do a full page load. So the critical CSS for the first route remains in the head. That might be okay because the critical CSS for the first route might also be used in the second route? Not necessarily.
Actually, for SPA navigation, we don't do a full page load, so we don't inline new critical CSS. So the critical CSS for the initial route stays. That might be acceptable because the critical CSS for the initial route might cover the critical CSS for the next route? Not always.
This is a problem for SPAs.
So, for SPAs, we usually want to load the entire CSS (both critical and non-critical) in one go, and then for the initial route, we inline the critical CSS to speed up first paint, but for subsequent routes we don't need to inline because the CSS is already loaded.
But note: the initial route's critical CSS might not be enough for the next route. So when we navigate to a new route, we might need to load new CSS? That would break the monolithic CSS idea.
Actually, in an SPA, we usually load the entire CSS bundle once (at the initial load). So if we split the CSS into critical (inlined) and non-critical (loaded asynchronously), then for the initial route we have:
- Inlined critical CSS for the initial route.
- Async non-critical CSS for the entire app.
Then, when we navigate to a new route, we don't need to load any new CSS because the non-critical CSS already contains the styles for the new route (including its critical styles?).
Wait, the non-critical CSS does not contain the critical styles for the initial route (because we removed them). But it does contain the non-critical styles for the entire app, including the new route. But the new route might have critical styles that are not in the inlined critical CSS of the initial route? And those critical styles are not in the non-critical CSS either?
Because we removed the critical rules from the non-critical CSS. So the new route's critical styles are missing.
So we have a problem: the non-critical CSS does not contain the critical rules for any route. And we only inlined the critical rules for the initial route.
Therefore, for the new route, we don't have its critical rules in the CSS at all?
This is a flaw.
So we must have the entire app's CSS (both critical and non-critical) in the monolithic CSS file? Then we cannot remove the critical rules from the monolithic CSS.
Then we have duplication: inlined critical CSS and the same rules in the monolithic CSS.
But duplication is not the end of the world. The browser will apply the inlined critical CSS first, and then when the monolithic CSS loads, it will apply again (but same rules, so no change). It's a waste of bandwidth.
Alternatively, we can have the monolithic CSS without the critical rules? Then we must inline the critical rules for every route? But for SPA navigation, we don't inline again.
So we need to load the critical rules for the new route somehow. We could load them via JavaScript? That would be another request.
This is getting complicated.
Maybe we should reconsider:
In an SPA, we usually want to load the entire CSS (all rules) once. So we have one CSS file for the entire app. Then, for the initial route, we inline the critical CSS to speed up first paint. For subsequent routes, we don't need to inline because the CSS is already loaded.
But then the critical CSS for the initial route is inlined and also in the CSS file? Yes, duplication.
We can avoid duplication by:
- Having the monolithic CSS file without the critical rules for the initial route? But then the initial route would be missing critical styles until the CSS loads? We inlined the critical rules, so that's okay. But then the CSS file does not have the critical rules for the initial route? That's okay because we inlined them.
But then for other routes, their critical rules are in the CSS file? Yes, because we didn't remove them. So when we navigate to a new route, the critical rules for that route are in the CSS file (which is already loaded) so they are applied.
So:
- For the initial route, we inline its critical rules and load the monolithic CSS that does not contain the initial route's critical rules? But the monolithic CSS contains the critical rules for other routes.
How do we generate the monolithic CSS without the critical rules for the initial route? We would have to generate a different monolithic CSS for each initial route? That breaks the monolithic idea.
Alternatively, we can have:
- `app.css` (monolithic) that contains all rules (critical and non-critical) for the entire app.
- For the initial route, we inline the critical rules (which are also in `app.css`). Then, when `app.css` loads, the inlined rules are overridden? Actually, they are the same, so it doesn't matter.
But we have duplication.
Given the complexity, maybe we accept the duplication for the initial route? The critical CSS is usually small, so the duplication is acceptable.
And for SPA navigation, we don't inline again, so there's no duplication for other routes.
So:
- We have one `app.css` that contains all CSS for the entire app.
- For each route, we have a critical CSS string (subset of `app.css`).
- For the initial route (SSR), we inline the critical CSS and then preload `app.css`.
Then, when the user navigates to another route (SPA), the `app.css` is already loaded (and it contains the critical rules for the new route) so we don't need to do anything.
This seems the simplest.
So we accept the duplication for the initial route.
But note: the critical CSS for the initial route is inlined and then again in `app.css`. That's two times the same rules. We can avoid this by:
- Not inlining the critical CSS? But then we lose the benefit of inlining.
- Or, we can remove the critical rules from `app.css` for the initial route? But then `app.css` would be different for each initial route? We don't want that because we want one `app.css` for the entire app.
So we accept the duplication.
Alternatively, we can have two CSS files:
- `critical.css` (inlined) that contains the critical rules for the initial route.
- `app.css` (monolithic) that contains all rules (including the critical rules for the initial route and for other routes).
Then we have duplication only for the initial route's critical rules.
This is acceptable because the critical CSS is small.
So we go with:
- Build:
- Generate `app.css` (all CSS for the entire app).
- For each route, generate critical CSS (subset of `app.css`).
- SSR for a route:
- Inline the critical CSS for that route.
- Preload `app.css`.
Then, when `app.css` loads, it will have the same critical rules again, but that's okay.
We can try to avoid the duplication by using `@import`? No.
Or we can use `media` attributes? We can set the inlined critical CSS to be only for the initial render and then when `app.css` loads, it overrides? But they are the same rules, so it doesn't matter.
So we accept the duplication.
g. Summary:
1. Build:
- Bundle all CSS into `app.css`.
- For each route (or route pattern), generate critical CSS by:
- Rendering the route to static HTML (with sample data for dynamic routes).
- Using `penthouse` (or similar) to extract critical CSS from the HTML and `app.css`.
- Save the critical CSS for that route pattern in a JSON map.
2. Server:
- For each request, match the URL to a route pattern and get the critical CSS string from the map.
- Write the HTML response:
- Head with inlined critical CSS and preload link for `app.css`.
- Then, stream the body using `renderToPipeableStream` (React 18) for the App component.
- After the React stream ends, write the script tag for the bundle and close the body and html.
3. Client:
- The browser will render with the inlined critical CSS.
- It will preload `app.css` and then apply it when loaded.
- The client will hydrate the React app when the bundle.js loads and the HTML is fully received? Actually, with streaming, the client can start hydrating as soon as the root div is available? But we are using `hydrate`?
We need to adjust the client-side code to use `hydrateRoot` (React 18) and wait for the entire HTML? Actually, with streaming, the client can start hydrating incrementally?
But note: we are inlining critical CSS, so the initial paint is fast, but the hydration might wait for the entire HTML?
Actually, the React 18 streaming on the client uses `hydrateRoot` and it will wait for the entire HTML? Not necessarily, it can hydrate as the HTML streams in?
We are sending the entire HTML in chunks, but the client will receive it as a stream. The `hydrateRoot` will start when the root div is available?
This is getting into the details of React 18 streaming hydration, which is a separate topic.
We assume that the client-side code is set up to hydrate from the streamed HTML.
h. Implementation Details:
- We need a way to match the request URL to a route pattern. We can use the same router configuration as the client (e.g., React Router). So we export the route patterns from the client and use them on the server.
- For dynamic routes, we generate critical CSS for a sample set of params.
- We store the critical CSS map in a JSON file that is generated at build time and read by the server at startup.
- The server code:
```javascript
const criticalCSSMap = require('./critical-css-map.json');
app.get('*', (req, res) => {
const routePattern = matchRoute(req.url); // function that matches the URL to a route pattern
const criticalCSS = criticalCSSMap[routePattern] || criticalCSSMap['/']; // fallback to home
res.write(`<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style id="critical-css">${criticalCSS}</style>
<link rel="preload" href="/app.css" as="style" onload="this.rel='stylesheet'">
<noscript><link rel="stylesheet" href="/app.css"></noscript>
</head>
<body>
`);
const { pipe } = renderToPipeableStream(
<App location={req.url} />,
{
onShellReady() {
pipe(res);
},
onError(error) {
console.error(error);
res.end();
}
}
);
// Wait for the React stream to end? Actually, we are piping to res, so when the React stream ends, the res will not end automatically?
// We need to write the script and close the body after the React stream.
// But note: the React stream will write the entire App (the children of the body). Then we want to write the script and close the body.
// How do we know when the React stream is done? We can listen to the 'end' event on the React stream? Actually, the object returned by `renderToPipeableStream` is a stream? It has a `pipe` method and also emits events?
// According to the React 18 docs, `renderToPipeableStream` returns an object with `pipe` and `abort` methods. It does not return a stream. So we cannot listen to 'end'.
// Instead, we can use `onAllReady`? That is called when the entire tree is ready, but the stream might have already been piped?
// Alternatively, we can write the script and close the body in the `onAllReady` callback? But note: `onAllReady` is called when the entire tree is ready to be streamed, but the streaming might not be finished?
// Actually, `onAllReady` is called when the initial shell is ready (the static parts). But we are streaming, so the dynamic parts might come later.
// We want to write the script after the entire React tree has been streamed? That might be too late because we want the script to be as early as possible? But we want it at the end of the body.
// Actually, we can write the script immediately after we pipe? But then the React stream might not have finished? We want the script to be after the React content.
// So we need to wait until the React stream is done.
// How about:
let reactStreamFinished = false;
const { pipe, abort } = renderToPipeableStream(
<App location={req.url} />,
{
onShellReady() {
pipe(res);
},
onAllReady() {
// This is called when the entire tree is ready? But the streaming might not have finished?
// Actually, the stream is being piped and we don't know when it ends.
}
}
);
// We can wrap the res to detect when the React stream ends? Because we are piping, the res will be written to by the React stream. We can count the bytes? Not reliable.
// Alternatively, we can not use `pipe` and instead read from the React stream and write to res, and then when the React stream ends, we write the script.
// But `renderToPipeableStream` returns an object with a `pipe` method, but it also has an event emitter? Actually, it returns a `ShellStream` which is a writable stream?
// Let's check the type: in React 18, `renderToPipeableStream` returns `{ pipe: (destination: Stream) => void, abort: () => void }`. So we cannot listen to events.
// So we cannot know when the stream ends?
// Then we have to write the script immediately after we call `pipe`? But that would write the script before the React content? Because `pipe` is asynchronous? Actually, `pipe` starts the streaming and returns immediately?
// We can try:
res.write(`<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style id="critical-css">${criticalCSS}</style>
<link rel="preload" href="/app.css" as="style" onload="this.rel='stylesheet'">
<noscript><link rel="stylesheet" href="/app.css"></noscript>
</head>
<body>
`);
const { pipe } = renderToPipeableStream(
<App location={req.url} />,
{
onShellReady() {
pipe(res);
},
onError(error) {
console.error(error);
res.end();
}
}
);
// We cannot know when the React stream ends, so we write the script immediately? That would be:
res.write(`
<script src="/bundle.js"></script>
</body>
</html>
`);
res.end();
// But then the script is written while the React stream is still being piped? That would interleave?
// Actually, the `pipe` method starts streaming and returns immediately. The streaming happens asynchronously. So if we write the script right after, it will be written before the React stream content?
// We need to write the script after the React stream. So we have to wait.
// How about we use `renderToString`? Then we get the entire HTML string for the App and then we can write it and then the script. But that doesn't stream.
// Alternatively, we can use `renderToPipeableStream` and then collect the entire stream into a string and then write? That doesn't stream.
// This is a problem.
// Maybe we don't need to stream the entire React app? We are inlining critical CSS, so the initial paint is fast, but the React app might be large and we want to stream it.
// But we also need to write the script at the end.
// Another idea: we can include the script in the React app? That is, the App component returns the script tag at the end? But that would be part of the React tree and then we don't have to write it separately.
// We can do:
// In the App component, we return:
// <>
// ... the page content ...
// <script src="/bundle.js"></script>
// </>
// Then, the script will be streamed as part of the React tree. But then the script will be loaded after the entire React tree? That's okay.
// But note: we want the script to be at the end of the body, so if the App component returns a fragment that includes the script at the end, then it will be at the end.
// So we can do:
// In the server, we don't write the script separately. We let the React app include the script.
// Then, we don't have the problem of when to write the script.
// But then the script is part of the React tree and will be streamed with the rest.
// However, the script tag is not part of the React app usually? We can have a component that renders the script.
// But then the script will be hydrated? We don't want to hydrate the script tag. We can have a component that only renders the script on the server? But then on the client, we don't want to render it again?
// Actually, the script tag is not interactive, so it's okay to have it in the React tree? But React will try to manage it? We don't want that.
// We can use `dangerouslySetInnerHTML`? Or we can have a component that only renders on the server?
// Alternatively, we can have the script tag outside the React root? That's what we were doing.
// Given the complexity, maybe we should not stream the React app? We can use `renderToString` and then write the entire HTML at once? But then we lose streaming.
// But note: we are inlining critical CSS, so the initial paint is fast. The rest of the HTML (the React app) might be large, but we are sending it as a string? That blocks the event loop?
// With `renderToString`, the server will block until the entire string is generated. That might be slow for large apps.
// So we want streaming.
// How about we use `renderToPipeableStream` and then we write the script after we get the 'end' event from the res? But we are piping to res, so when the React stream ends, the res will not end? Actually, when the source stream (React) ends, the destination stream (res) will not end automatically?
// We can do:
const reactStream = renderToPipeableStream(...); // This returns an object with a pipe method? Actually, it returns a ShellStream which is a writable stream?
// Wait, the return value of `renderToPipeableStream` is an object with `pipe` and `abort`. The `pipe` method takes a writable stream. So we can do:
reactStream.pipe(res);
// Then, we can listen to the 'finish' event on res? But the res might not finish because we are going to write more?
// Actually, when the reactStream ends, it will end the res? No, because we are piping, the res will be ended when the reactStream ends?
// According to Node.js stream.pipe, by default, the destination stream is ended when the source stream ends. So when the reactStream ends, the res will be ended? Then we cannot write the script after.
// So we cannot use pipe? We have to manually write the chunks from the reactStream to res and then when the reactStream ends, we write the script.
// But how do we get the chunks from the reactStream? The return value of `renderToPipeableStream` is not a readable stream? It's an object with a `pipe` method.
// Actually, the `renderToPipeableStream` returns a `ShellStream` which is a writable stream? No, it's a readable stream?
// Let's check the type definitions:
// In React 18, `renderToPipeableStream` returns:
// interface PipeableStream {
// pipe<T extends WritableStream>(destination: T): T;
// abort(error?: Error | null): void;
// }
// So it's not a readable stream. It's an object that can pipe to a writable stream.
// So we cannot get the chunks.
// Therefore, we cannot interleave our own writing after the React stream if we use `pipe`.
// So we have to write the script as part of the React tree?
// Let's do that:
// In the App component, we have:
// function App() {
// return (
// <>
// ... the page content ...
// <script src="/bundle.js"></script>
// </>
// );
// }
// Then, when we stream the App, the script will be at the end.
// But then the script will be inside the root div? Actually, the App returns a fragment, so the root div is one of the children?
// Wait, the App component is the entire page? Then we don't have a root div? Actually, in the server we render the entire App, which should return the entire page content (including the root div for the client to hydrate).
// Typically, the App component returns a div with id="root" and then the content?
// Actually, the server renders:
// <div id="root">
// ... the app ...
// </div>
// And then the client hydrates that div.
// So the App component returns the content of the root div? Then the script should be outside the root div?
// We want:
// <body>
// <div id="root">... app ...</div>
// <script src="/bundle.js"></script>
// </body>
// So the script is after the root div.
// If the App component returns the root div and then the script, then the script would be inside the root div? That's not what we want.
// So we need to structure the App component to return:
// <div id="root">
// ... the actual app ...
// </div>
// <script src="/bundle.js"></script>
// But then the root div is inside the App? And the script is outside? That's not typical.
// Actually, the App component is the entire page? Then we don't have a separate root div?
// In a typical React app, we have:
// index.html:
// <div id="root"></div>
// <script src="/bundle.js"></script>
// And then ReactDOM.hydrate(<App />, document.getElementById('root'));
// So the server renders the App into the root div. The script is separate.
// So the server HTML should be:
// <body>
// <div id="root"><!-- App content --></div>
// <script src="/bundle.js"></script>
// </body>
// So the script is outside the root div.
// Therefore, we cannot include the script in the App component because then it would be inside the root div.
// So we are back to the problem: we need to write the script after the React stream.
// Given the limitations of `renderToPipeableStream`, we might have to use `renderToString` and not stream the React app?
// But we want streaming for the React app.
// Alternatively, we can use `renderToPipeableStream` and then write the script after the entire stream? But we don't know when it ends.
// Another idea: we can write the script in the `onAllReady` callback? But that might be too early.
// Actually, `onAllReady` is called when the entire tree is ready to be streamed, but the streaming might not have finished?
// We can try:
const { pipe, abort } = renderToPipeableStream(
<App location={req.url} />,
{
onShellReady() {
pipe(res);
},
onAllReady() {
// This is called when the entire tree is ready, but the stream might have already been piped?
// We can write the script here? But note: the stream might still be writing?
// Actually, `onAllReady` is called when the entire tree is ready to be streamed, but the streaming might have already started?
// We can try to write the script after a delay? Not reliable.
// Alternatively, we can write the script after we know that the React stream has written the closing div for the root? We don't know.
// This is tricky.
// Given the time, maybe we should use `renderToString` for now and accept the blocking?
// But the requirement says streaming hydration, so we need streaming.
});
// After reading the React 18 docs more carefully, I see that `renderToPipeableStream` does not provide a way to know when the stream is done. So we cannot write after the stream.
// Therefore, we must include the script in the React tree? But that would put it inside the root div.
// We can change the structure: we can have the root div and then the script as siblings? But the App component returns a single root? We can return a fragment?
// If the App component returns a fragment with two children: the root div and the script, then the root div is the first child and the script is the second. Then the script is outside the root div?
// Actually, the App component is rendered into the root div? Wait, no: the server renders the App into the root div?
// Let me clarify:
// We are doing:
// res.write(`<!DOCTYPE html>
// <html>
// <head>...</head>
// <body>
// <div id="root">`);
// Then we pipe the React stream for the App? But the App is the entire page? Then the App should return the content of the root div?
// Actually, we are writing the opening div for the root, and then we want the React stream to write the content of that div?
// So the App component should return the content of the root div, not the div itself.
// So:
// We write: <div id="root">
// Then we pipe the React stream for the App (which returns the content of the root div).
// Then we write: </div>
// Then we write the script.
// But how? We are writing the opening div and then we pipe the React stream (which will write the content of the root div) and then we write the closing div and the script.
// So:
res.write(`<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style id="critical-css">${criticalCSS}</style>
<link rel="preload" href="/app.css" as="style" onload="this.rel='stylesheet'">
<noscript><link rel="stylesheet" href="/app.css"></noscript>
</head>
<body>
<div id="root">
`);
const { pipe } = renderToPipeableStream(
<App location={req.url} />,
{
onShellReady() {
pipe(res);
},
onError(error) {
console.error(error);
res.end();
}
}
);
// Now, we need to write the closing div and the script after the React stream.
// But we don't know when the React stream ends.
// We can try to write the closing div and script in the `onAllReady`? But that might be too early.
// Alternatively, we can write the closing div and script after a timeout? Not reliable.
// This is a known issue with `renderToPipeableStream`: it doesn't tell you when the stream is done.
// Actually, the `pipe` method returns the destination stream? But we are piping to res, so we can listen to the 'finish' event on res? But the res might finish when the React stream ends?
// Let's try:
res.write(`<!DOCTYPE html>
<html>
<head>...</head>
<body>
<div id="root">
`);
const { pipe } = renderToPipeableStream(
<App location={req.url} />,
{
onShellReady() {
const destination = pipe(res);
destination.on('finish', () => {
res.write(`
</div>
<script src="/bundle.js"></script>
</body>
</html>
`);
res.end();
});
}
}
);
// But note: the `pipe` method returns the destination stream (res). And we listen to the 'finish' event on res? But the res finish event will be emitted when the React stream ends?
// Actually, when we pipe, the res will be ended when the source stream (React) ends? By default, `pipe` will call `res.end()` when the source ends?
// If that happens, then we cannot write after because the res is ended.
// So we need to prevent the automatic ending? We can set `{ end: false }` in the pipe options?
// Let's check Node.js stream.pipe: it takes an options object with `end` (default true). So we can set `end: false` and then we write the closing div and script and then end the res ourselves.
// So:
res.write(`<!DOCTYPE html>
<html>
<head>...</head>
<body>
<div id="root">
`);
const { pipe } = renderToPipeableStream(
<App location={req.url} />,
{
onShellReady() {
const destination = pipe(res, { end: false });
destination.on('finish', () => {
res.write(`
</div>
<script src="/bundle.js"></script>
</body>
</html>
`);
res.end();
});
}
}
);
// This might work.
// But note: the React stream might write the closing div for the root? No, because we are writing the opening div and then the React stream writes the content of the root div? Then we write the closing div.
// So the App component should not return the root div? It should return the content of the root div.
// So the App component returns the children of the root div.
// Then we have:
// <div id="root">
// ... App content ...
// </div>
// And then the script.
// This should work.
- So we change the App component to return the content of the root div (without the div itself). Then we write the div in the server.
- But then the client will hydrate into the root div? Yes, because the root div is already there.
- The client code:
```javascript
import { hydrateRoot } from 'react-dom/client';
import App from './App';
hydrateRoot(document.getElementById('root'), <App location={window.location} />);
```
- This should work.
i. Conclusion:
We have a plan:
1. Build:
- Bundle all CSS into `app.css`.
- For each route pattern, generate critical CSS by rendering the route with sample data and using `penthouse` (or similar) to extract critical CSS from the HTML and `app.css`.
- Save the critical CSS in a JSON map: `{ "/": "critical-css-for-home", "/about": "critical-css-for-about", ... }`.
2. Server:
- For each request, match the URL to a route pattern and get the critical CSS.
- Write the HTML response:
- Head with inlined critical CSS and preload link for `app.css`.
- Body with opening `div id="root"`.
- Stream the App component (which returns the content of the root div) using `renderToPipeableStream` with `pipe(res, { end: false })`.
- When the React stream finishes (res 'finish' event), write the closing `</div>`, the script tag, and close the body and html.
3. Client:
- The browser renders with the inlined critical CSS and preloads `app.css`.
- When the bundle.js loads, it hydrates the React app.
This plan supports streaming hydration and per-route critical CSS inlining, with a monolithic CSS file for the entire app.
Note: We accept the duplication of critical CSS (inlined and in `app.css`) for the initial route.
We also assume that the App component does not include the root div, and that the server writes the root div.
This is a complex plan and requires careful implementation.
Let me know if you have any questions.</think>