DEV Community

Cover image for How to do SSR with SvelteKit and @emotion/css
qaynam
qaynam

Posted on

How to do SSR with SvelteKit and @emotion/css

I’m developing a product using svelteKit and wanted to use css-in-js, so I adopted @emotion/css. Unlike React, there wasn’t much information on how to use it with Sveltekit, so I wanted to write down the method I found while reading the source code. If anyone knows a smarter way, please let me know🙇‍♂️

Flow

Use the extractCritical method from the @emotion/server package 👇 to generate static CSS and inject it into the head tag of the HTML response string generated from the server.

Implementation

In the case of React, you can use renderToString from react-dom/server to convert jsx to an HTML string, but the concept is quite different for Svelte, so the method is very different.

However, hooks are provided in the case of Sveltekit.

“Hooks” are app-wide functions you declare that SvelteKit will call in response to specific events, giving you fine-grained control over the framework’s behaviour.

It may be similar to entry.server.tsx in remix.

server.hooks.ts

import type { Handle } from '@sveltejs/kit';
import { extractCritical } from '@emotion/server';

export const handle: Handle = async ({ event, resolve }) => {
 const response = await resolve(event, {
  transformPageChunk({ html, done }) {
   const { html: emotionHtml, css, ids } = extractCritical(html);
   if (done) {
    return emotionHtml.replace(
     '</head>',
     `<style data-emotion-css="${ids.join(' ')}">${css}</style></head>`
    );
   }
  }
 });
 return response;
};

Enter fullscreen mode Exit fullscreen mode

That’s it.

Top comments (0)