File this under “it took me a whole 10 minutes to figure out so I thought I’d save you 9 of those”.

Svelte is a front-end framework with a number of advantages, not least of which is that it compiles down to vanilla JS on the server-side and so is quite zippy for the user. One problem that I had getting started with it, though, is that the Svelte docs mostly assume you’re using Node1 on the back-end. But what if you’re a Python person and want to use Flask?

It turns out not to be so bad:

  1. Put your Svelte files in a directory in the root of your Flask project.
  2. Set src/main.js to target something other than the <body> — for example:
import App from './App.svelte';

const app = new App({
	target: document.querySelector('#svelte-app')
});
  1. Over in your Flask routes.py file, add a catch-all route like the following:2
# Serve Svelte apps
@app.route("/<path:path>")
def svelte_client(path):
    return send_from_directory('../svelte/public/', path)
  1. Finally, add your app target (e.g. <div id='svelte-app'> to whatever Jinja template is appropriate, along with <link> and <script> tags pointing to your Svelte files:
<link rel='stylesheet' href='/build/bundle.css'>
<script defer src='/build/bundle.js'></script>

And you’re done! Now you can server Svelte from a Flask back-end.


  1. Or Sapper, Svelte’s own server. ↩︎

  2. You can optionally make this more specific — your Svelte files will generally be under build/<path>↩︎