Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add docs about SSR with SvelteKit #3055

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
55 changes: 55 additions & 0 deletions docs/ssr.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -294,3 +294,58 @@ if (!document.getElementById('root').hasChildNodes()) {
> Note:
>
> The `sheet.speedy` call has to be run before anything that inserts styles so it has to be put into it's own file that's imported before anything else.

## SvelteKit

To use emotion's SSR with SvelteKit you need server hooks in `src/hooks.server.ts` that replace `%sveltekit.style%` in `src/app.html` with styles.

src/lib/server/renderer.js
```js
import createEmotionServer from '@emotion/server/create-instance'
import { cache } from '@emotion/css'

export const renderStatic = async (html) => {
if (html === undefined) {
throw new Error('did you forget to return html from renderToString?')
}
const { extractCritical } = createEmotionServer(cache)
const { ids, css } = extractCritical(html)

return { html, ids, css }
}
```

src/hooks.server.js
```js
import { renderStatic } from '$lib/server/renderer'

export const handle = (async ({ event, resolve }) => {
const response = await resolve(event, {
transformPageChunk: async ({ html }) => {
const { css, ids } = await renderStatic(html)
const style = `<style data-emotion-css="${ids.join(' ')}">${css}</style>`

return html.replace('%sveltekit.style%', style)
}
})

return response
})
```

src/app.html
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<meta name="viewport" content="width=device-width" />
%sveltekit.head%
%sveltekit.style%
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>
```