Prerender all SvelteKit pages with Prismic as the CMS

Reece May • April 4, 2021 • 3 min read

prismic tips headless

Originally trying SvelteJS Sapper to build a site with Prismic was a bit tricky, mainly trying to get the systems to work together and also finding out that the hot module reloading was bust...

When testing SvelteKit out (I had read about it on Sapper docs somewhere 🤷‍♂️) but then there was the beta release so I tried it out and also read the Prismic blog post on setting it up and it worked a lot better, the experience was similar to Next and the result was a really really fast build. (Like stupid quick compared to other things)

Yet there was a problem, dynamic static routes weren't built without the svelte:prefetch...

Building a route list before pre-rendering.

I tested different ways to get the site to fetch data and basically 'hydrate' stuff at build time. Because interestingly even with the static-adapter it didn't render pages that were dynamic [uid].svelte. P.S. use npm i -D @sveltejs/adapter-static@next is the working one.

So you can imagine the confusion when Netlify a) doesn't build the site properly and b) the static site has 404 pages where there should be pages.

The solution I decided to use, as it has the best support at present is to use a Node script to fetch the list of pages that you want, map them through a linkResolver function to build the appropriate routes for Svelte to render and make it available before Svelte builds.

Building the dynamic routes 🗺

The first file is called utils/routelist.js, this is called before running Svelte's build process and generates your routes. It is only needed at build time. So when you put it on the server for production.

1import Prismic from '@prismicio/client';
2import path from 'path';
3import fs from 'fs';
4import { cwd } from 'process';
5 
6const repository = process.env.PRISMIC_REPOSITORY
7 ? process.env.PRISMIC_REPOSITORY
8 : 'CHANGE_THIS_PLEASE';
9 
10const apiEndpoint = `https://${repository}.cdn.prismic.io/api/v2`;
11const Client = Prismic.client(apiEndpoint);
12 
13// Our link resolver that will be used to map the routes 🗺
14const linkResolver = (doc) => {
15 if (doc.type === 'blog') {
16 return `/blog/${doc.uid}`
17 }
18 
19 if (doc.type === 'categories') {
20 return `/category/${doc.uid}`
21 }
22 
23 return `/${uid}`;
24}
25 
26/**
27 * This is our build function. It contains the query.
28 * It uses the link resolver to build the routes.
29 * It then writes it to disk in the same dir.
30 */
31const build = async () => {
32 let query = await Client.query([
33 Prismic.Predicates.at('document.type', 'blog'),
34 Prismic.Predicates.at('document.type', 'categories'),
35 Prismic.Predicates.at('document.type', 'homepage'),
36 ]);
37 
38 /**
39 * Svelte uses the `*` to render the other pages that aren't dynamic
40 */
41 let pages = ['*']
42 
43 /**
44 * Convert the docs into the related link for Svelte to render.
45 */
46 let result = query.results.map(linkResolver);
47 
48 pages.push(...result)
49 
50 /**
51 * We create a JSON file that is used to build the site.
52 */
53 fs.writeFileSync(
54 path.join(cwd(), './utils/routelist.json'),
55 JSON.stringify(pages)
56 )
57 
58 console.log('written: ', pages);
59}
60 
61build();

A quick summary of what that all does is basically uses the API to get the docs we want and their UID, map them, then write them to disk as an array in a JSON file.

This has two benefits, we don't have to commit the JSON to git and we don't have to parse the JSON file when importing it.

Updating the Svelte config file

To make use of the built pages, you can edit your svelte.config.js file like so:

1+ const static = require('@sveltejs/adapter-static');
2- const prismic = require('./adapter-prismic');
3const pkg = require('./package.json');
4+ const pages = require('./utils/routelist.json');
5 
6/** @type {import('@sveltejs/kit').Config} */
7module.exports = {
8 kit: {
9 // By default, `npm run build` will create a standard Node app.
10 // You can create optimized builds for different platforms by
11 // specifying a different adapter
12+ adapter: static(),
13 
14 // hydrate the <div id="svelte"> element in src/app.html
15 target: '#svelte',
16 
17 prerender: {
18+ crawl: true,
19+ enabled: true,
20+ force: true,
21+ pages: [...pages],
22 },
23 
24 vite: {
25 ssr: {
26 noExternal: Object.keys(pkg.dependencies || {})
27 }
28 }
29 }
30};

This will import the json file that is basically an array of strings, this is then destructured into the pages key for the prerender.

Updating package.json

To make sure the files are triggered correctly, you can add the following to the package.json scripts key:

1"scripts": {
2 "dev": "svelte-kit dev",
3 "build": "npm run routes && svelte-kit build", /* Updated */
4 "routes": "node ./utils/routelist", /* NEW */
5 "start": "svelte-kit start"
6},

This will make it possible that now your dynamic pages in Svelte are prerendered when exporting to a static version using Prismic or another headless CMS I guess.

Cleaning it up

I added the exported file to my gitignore, as it really isn't needed as it is once off during the build process. So for this specific example add the following to the root .gitignore for your project: /utils/routelist.json

That should be about all to make a clean, fast, and non-404 static site with SvelteKit

0_o

Syntax highlighting by Torchlight.