-
-
Notifications
You must be signed in to change notification settings - Fork 32.4k
/
Copy pathentry.server.tsx
59 lines (50 loc) · 1.98 KB
/
entry.server.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import * as React from 'react';
import * as ReactDOMServer from 'react-dom/server';
import { RemixServer } from '@remix-run/react';
import type { EntryContext } from '@remix-run/node';
import createEmotionCache from './src/createEmotionCache';
import theme from './src/theme';
import CssBaseline from '@mui/material/CssBaseline';
import { ThemeProvider } from '@mui/material/styles';
import { CacheProvider } from '@emotion/react';
import createEmotionServer from '@emotion/server/create-instance';
export default function handleRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
remixContext: EntryContext,
) {
const cache = createEmotionCache();
const { extractCriticalToChunks } = createEmotionServer(cache);
function MuiRemixServer() {
return (
<CacheProvider value={cache}>
<ThemeProvider theme={theme}>
{/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */}
<CssBaseline />
<RemixServer context={remixContext} url={request.url} />
</ThemeProvider>
</CacheProvider>
);
}
// Render the component to a string.
const html = ReactDOMServer.renderToString(<MuiRemixServer />);
// Grab the CSS from emotion
const { styles } = extractCriticalToChunks(html);
let stylesHTML = '';
styles.forEach(({ key, ids, css }) => {
const emotionKey = `${key} ${ids.join(' ')}`;
const newStyleTag = `<style data-emotion="${emotionKey}">${css}</style>`;
stylesHTML = `${stylesHTML}${newStyleTag}`;
});
// Add the Emotion style tags after the insertion point meta tag
const markup = html.replace(
/<meta(\s)*name="emotion-insertion-point"(\s)*content="emotion-insertion-point"(\s)*\/>/,
`<meta name="emotion-insertion-point" content="emotion-insertion-point"/>${stylesHTML}`,
);
responseHeaders.set('Content-Type', 'text/html');
return new Response(`<!DOCTYPE html>${markup}`, {
status: responseStatusCode,
headers: responseHeaders,
});
}