Server-side-rendering a Svelte 5 app (without Sveltekit or Vite)

Sveltekit comes with everything you need to build full-stack apps, but there are situations where you might need to 'manually' server-side render svelte components (or even a full svelte app). My use case was that I needed to render a Svelte component inside a Vercel serverless function, and upload the result to S3. And frankly, it's just plain fun to tinker and figure out how things work under the hood...

To server-render a Svelte component, you first need to run it through the svelte compiler:

import { compile } from 'svelte/compiler';
const { js } = compile(source, {
	filename: path.basename(svelteFilePath),
	generate: 'ssr', // Generate server-side rendering code
	css: 'injected' // inject any css into the head
});

This converts the Svelte component to optimized ‘vanilla’ javascript and makes them compatible with Node.js

After that, save the file as a .js file, so we can import it in the next step.

const { default: App } = await import(path.resolve(`${mycomponent}.js`));
const { body } = render(App, { props: { name: 'World' } });

The body variable now contains our Svelte component as a string.

Check out the full code in the Github repo:

View the repo