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.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay