Using Fastify with Sapper
The Svelte library has been picking up steam lately so I gave it a try this week and found it quite enjoyable. The next questions for me were: how do I use Fastify server and get server-side rendering?
static
folder should be working as expected.
This tutorial assumes:
- you have used Svelte
- you have used or want to use Fastify
- you want server-side rendering in the easiest way possible (Sapper)
Setup Sapper
I don't want to reinvent the instruction wheel so it is best to follow the instructions on the Sapper site to setup a new project or review the Github repo and add Sapper to your project.
If you go the hard way (adding Sapper), the most important parts will be:
- creating a
static/
folder - creating a
src/template.html
- creating a
src/client.js
- creating a
src/server.js
- choosing Rollup or Webpack and setting up the
package.json
accordingly
Use Fastify
In the instructions for Sapper you might notice:
This is a normal Express (or Polka, etc) app, with three requirements
Source: https://sapper.svelte.dev/docs/#src_server_js
This means Fastify should be easy to drop in.
Install dependencies
npm install fastify fastify-static
Create a src/server.js file
Or clear the contents of the existing one if you used the Sapper template.
The new contents:
const fastify = require('fastify')({ logger: true });
const path = require('path');
// Register the static plugin and serve content from static folder
fastify.register(require('fastify-static'), {
root: path.join(__dirname, '..', 'static')
})
// Run the sapper middleware which will handle server-side rendering
fastify.use(require('@sapper/server').middleware());
fastify.listen(process.env.PORT, (err, address) => {
if (err) { throw err; }
fastify.log.info(`Server listening on ${address}`);
});
Test drive
npm run dev
Visit http://localhost:3000.