Emotion on the server #16
Closed
georgekaran
started this conversation in
General
Replies: 1 comment
-
I was able to inject the Emotion styles using the following technique: onServerCreated: (app): void => {
app.use(CookieParser());
app.use('*', (req, res, next) => {
const oldEnd = res.end;
const oldWrite = res.write;
const chunks: Buffer[] = [];
// eslint-disable-next-line @typescript-eslint/ban-ts-comment -- Need to override write
// @ts-ignore
res.write = function write(chunk: any, encoding: BufferEncoding): boolean {
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding));
return true;
};
// eslint-disable-next-line @typescript-eslint/ban-ts-comment -- Need to override end
// @ts-ignore
res.end = function end(chunk: Buffer | string, encoding: BufferEncoding, cb?: () => void): void {
if (chunk != null) {
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding));
}
const body = Buffer.concat(chunks).toString('utf8');
const emotionChunks = extractCriticalToChunks(body);
const styles = constructStyleTagsFromChunks(emotionChunks);
oldWrite.call(res, body.replace('</head>', `${styles}</head>`), encoding);
oldEnd.call(this, chunk, encoding, cb);
};
next();
});
}, Is definitely not pretty but it does the job. 😆 |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Heyy,
I'm trying to use the
vite-ssr-boost
with Emotion, but I'm not doing things right.As far as I understood, under the hood,
vite-ssr-boost
usesrenderToPipeableStream,
which sends chunks of HTML for the user as things get loaded.I've tried using this approach below, but as you can imagine, things didn't work very well.
Since the HTML on the response API is just a chunk I'm getting the following error with some glitches on the screen.
Is there an API or any way to access the final HTML so I can extract the CSS to send the user?
Beta Was this translation helpful? Give feedback.
All reactions