Svelte.js + Flask — Combining Svelte with a Backend Server
TL;DR — You can use Flask to add a simple backend server to your Svelte app. Check out the example code here.
I recently discovered Svelte.js, a web application framework similar to React.js or Vue.js. While it has the same powerful features, like components and props, as the more established frameworks, I find it much more intuitive and straight-forward. A super simple Svelte component looks like this:
A Svelte component looks like a regular HTML file, but with the inclusion of a
<script>tag and a couple special syntax commands it becomes a fully functional reactive framework. The functionality ends up being similar to React.js, allowing you to pass props, import NPM libraries and components, and reactively update the HTML body. There is really a ton Svelte.js can do, and I highly recommend learning more with their fantastic interactive tutorial.
Combining Svelte and Flask
Svelte.js is powerful by itself, but I recently ran into a problem where I needed some sort of backend or API— I had a dataset of about 200,000 images I wanted to be able to filter and query.
While I could have created a standalone server to act as an API, it becomes a bit of a hassle to deal with CORS and eventually hosting two different applications. I found it much simpler to combine the two and serve the Svelte app from Flask.
In a new folder, we can create a tiny Flask server,
server.py, that returns a random number (you may have to run
pip install flaskfirst):
To test it out you can run
python server.py and open
localhost:5000/rand in your browser. You should see a random number between 0 and 100 each time you refresh.
We can now add Svelte into our Flask application. Inside your folder, run the following commands to create a new Svelte app:
npx degit sveltejs/template client
This will create a new Svelte template and install the required dependencies. You can run
npm run dev to check that the Svelte app works, and you should see a purple Hello World at
localhost:5000 in your browser.
Now we want Flask to serve our Svelte project. We can do that by adding the following to our server:
This tells our Flask server to serve all the static files that Svelte compiles into the public folder. Now if you run
python server.py you should see our Svelte app!
Sending Requests to Flask
Lastly, we can modify our Svelte file
App.svelte to send a request and get a random number from the Flask server:
This component now queries the
/rand path of our Flask server and shows the returned number.
This simple framework ends up being a simple and convenient way to quickly prototype ideas that need a server. In two terminal windows you can run the following:
python server.pyto run the flask server
npm run autobuildin the Svelte app folder to automatically build when you save a file
You can find the full code for this simple app here.