Introduction
Before we begin
Sapper has been deprecated in favor of SvelteKit. We recommend using SvelteKit for all projects moving forward. Sapper will no be receiving security fixes, bug fixes, or any type of improvements.
See the migration guide for help migrating from Sapper to SvelteKit. If you get stuck, reach out for help in the Discord chatroom.
What is Sapper?
Sapper is a framework for building extremely high-performance web apps. You're looking at one right now! There are two basic concepts:
- Each page of your app is a Svelte component
- You create pages by adding files to the
src/routes
directory of your project. These will be server-rendered so that a user's first visit to your app is as fast as possible, then a client-side app takes over
Building an app with all the modern best practices — code-splitting, offline support, server-rendered views with client-side hydration — is fiendishly complicated. Sapper does all the boring stuff for you so that you can get on with the creative part.
You don't need to know Svelte to understand the rest of this guide, but it will help. In short, it's a UI framework that compiles your components to highly optimized vanilla JavaScript. Read the introductory blog post and the tutorial to learn more.
Why the name?
In war, the soldiers who build bridges, repair roads, clear minefields and conduct demolitions — all under combat conditions — are known as sappers.
For web developers, the stakes are generally lower than for combat engineers. But we face our own hostile environment: underpowered devices, poor network connections, and the complexity inherent in front-end engineering. Sapper, which is short for Svelte app maker, is your courageous and dutiful ally.
Comparison with Next.js
Next.js is a React framework from Vercel (formerly ZEIT), and is the inspiration for Sapper. There are a few notable differences, however:
- Sapper is powered by Svelte instead of React, so it's faster and your apps are smaller
- As well as pages, you can create server routes in your
src/routes
directory. This makes it very easy to, for example, add a JSON API such as the one powering this very page (try visiting /docs.json) - Links are just
<a>
elements, rather than framework-specific<Link>
components. That means, for example, that this link right here, despite being inside a blob of markdown, works with the router as you'd expect
Getting started
The easiest way to start building a Sapper app is to clone the sapper-template repo with degit:
npx degit "sveltejs/sapper-template#rollup" my-app
# or: npx degit "sveltejs/sapper-template#webpack" my-app
cd my-app
npm install
npm run dev
This will scaffold a new project in the my-app
directory, install its dependencies, and start a server on localhost:3000. Try editing the files to get a feel for how everything works – you may not need to bother reading the rest of this guide!
TypeScript support
Sapper supports TypeScript. If you are using the template with Rollup as described in "Getting started" you can convert your project to TypeScript simply by running:
node scripts/setupTypeScript.js
Sapper app structure
If you take a look inside the sapper-template repo, you'll see some files that Sapper expects to find:
├ package.json
├ src
│ ├ routes
│ │ ├ # your routes here
│ │ ├ _error.svelte
│ │ └ index.svelte
│ ├ client.js
│ ├ server.js
│ ├ service-worker.js
│ └ template.html
├ static
│ ├ # your files here
└ rollup.config.js / webpack.config.js
When you first run Sapper, it will create an additional __sapper__
directory containing generated files.
You'll notice a few extra files — we don't need to worry about those right now.
You can create these files from scratch, but it's much better to use the template. See getting started for instructions on how to easily clone it
package.json
Your package.json contains your app's dependencies and defines a number of scripts:
npm run dev
— start the app in development mode, and watch source files for changesnpm run build
— build the app in production modenpm run export
— bake out a static version, if applicable (see exporting)npm start
— start the app in production mode after you've built it
src
This contains the three entry points for your app — src/client.js
, src/server.js
and (optionally) src/service-worker.js
— along with a src/template.html
file.
src/client.js
This must import, and call, the start
function from the generated @sapper/app
module:
import * as sapper from '@sapper/app';
sapper.start({
target: document.querySelector('#sapper')
});
In many cases, that's the entirety of your entry module, though you can do as much or as little here as you wish. See the client API section for more information on functions you can import.
src/server.js
This is a normal Express (or Polka, etc) app, with three requirements:
- it should serve the contents of the
static
folder, using for example sirv - it should call
app.use(sapper.middleware())
at the end, wheresapper
is imported from@sapper/server
- it must listen on
process.env.PORT
Beyond that, you can write the server however you like.
src/service-worker.js
Service workers act as proxy servers that give you fine-grained control over how to respond to network requests. For example, when the browser requests /goats.jpg
, the service worker can respond with a file it previously cached, or it can pass the request on to the server, or it could even respond with something completely different, such as a picture of llamas.
Among other things, this makes it possible to build applications that work offline.
Because every app needs a slightly different service worker (sometimes it's appropriate to always serve from the cache, sometimes that should only be a last resort in case of no connectivity), Sapper doesn't attempt to control the service worker. Instead, you write the logic in service-worker.js
. You can import any of the following from @sapper/service-worker
:
files
— an array of files found in thestatic
directoryshell
— the client-side JavaScript generated by the bundler (Rollup or webpack)routes
— an array of{ pattern: RegExp }
objects you can use to determine whether a Sapper-controlled page is being requestedtimestamp
— the time the service worker was generated (useful for generating unique cache names)
src/template.html
This file is a template for responses from the server. Sapper will inject content that replaces the following tags:
%sapper.base%
— a<base>
element (see base URLs)%sapper.styles%
— critical CSS for the page being requested%sapper.head%
— HTML representing page-specific<head>
contents, like<title>
%sapper.html%
— HTML representing the body of the page being rendered%sapper.scripts%
— script tags for the client-side app— CSP nonce taken from
res.locals.nonce
(see Content Security Policy (CSP))
src/routes
This is the meat of your app — the pages and server routes. See the section on routing for the juicy details.
static
This is a place to put any files that your app uses — fonts, images and so on. For example static/favicon.png
will be served as /favicon.png
.
Sapper doesn't serve these files — you'd typically use sirv or serve-static for that — but it will read the contents of the static
folder so that you can easily generate a cache manifest for offline support (see service-worker.js).
Note that the default behaviour of the service worker is to cache all assets from the static directory, so if you have more than 50mb of files here, you will start to exceed the cache limit for service-workers in some browsers, which can cause the service worker to stop loading. In this instance, it is advisable to customise what files are cached by editing the service-worker yourself.
rollup.config.js / webpack.config.js
Sapper can use Rollup or webpack to bundle your app. You probably won't need to change the config, but if you want to (for example to add new loaders or plugins), you can.
Routing
As we've seen, there are two types of route in Sapper — pages, and server routes.
Pages
Pages are Svelte components written in .svelte
files. When a user first visits the application, they will be served a server-rendered version of the route in question, plus some JavaScript that 'hydrates' the page and initialises a client-side router. From that point forward, navigating to other pages is handled entirely on the client for a fast, app-like feel.
The filename determines the route. For example, src/routes/index.svelte
is the root of your site:
<!-- src/routes/index.svelte -->
<svelte:head>
<title>Welcome</title>
</svelte:head>
<h1>Hello and welcome to my site!</h1>
A file called either src/routes/about.svelte
or src/routes/about/index.svelte
would correspond to the /about
route:
<!-- src/routes/about.svelte -->
<svelte:head>
<title>About</title>
</svelte:head>
<h1>About this site</h1>
<p>TODO...</p>
Dynamic parameters are encoded using [brackets]
. For example, here's how you could create a page that renders a blog post:
<!-- src/routes/blog/[slug].svelte -->
<script context="module">
// the (optional) preload function takes a
// `{ path, params, query }` object and turns it into
// the data we need to render the page
export async function preload(page, session) {
// the `slug` parameter is available because this file
// is called [slug].svelte
const { slug } = page.params;
// `this.fetch` is a wrapper around `fetch` that allows
// you to make credentialled requests on both
// server and client
const res = await this.fetch(`blog/${slug}.json`);
const article = await res.json();
return { article };
}
</script>
<script>
export let article;
</script>
<svelte:head>
<title>{article.title}</title>
</svelte:head>
<h1>{article.title}</h1>
<div class='content'>
{@html article.html}
</div>
If you want to capture more params, you can create nested folders using the same naming convention: [slug]/[language]
.
If you don't want to create several folders to capture more than one parameter like [year]/[month]/...
, or if the number of parameters is dynamic, you can use a spread route parameter. For example, instead of individually capturing /blog/[slug]/[year]/[month]/[day]
, you can create a file for /blog/[...slug].svelte
and extract the params like so:
<!-- src/routes/blog/[...slug].svelte -->
<script context="module">
export async function preload({ params }) {
let [slug, year, month, day] = params.slug;
return { slug, year, month, day };
}
</script>
See the section on preloading for more info about
preload
andthis.fetch
Server routes
Server routes are modules written in .js
files that export functions corresponding to HTTP methods. Each function receives HTTP request
and response
objects as arguments, plus a next
function. This is useful for creating a JSON API. For example, here's how you could create an endpoint that served the blog page above:
// routes/blog/[slug].json.js
import db from './_database.js'; // the underscore tells Sapper this isn't a route
export async function get(req, res, next) {
// the `slug` parameter is available because this file
// is called [slug].json.js
const { slug } = req.params;
const article = await db.get(slug);
if (article !== null) {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(article));
} else {
next();
}
}
delete
is a reserved word in JavaScript. To handle DELETE requests, export a function calleddel
instead.
If you are using TypeScript, use the following types:
import { SapperRequest, SapperResponse } from '@sapper/server';
function get(req: SapperRequest, res: SapperResponse, next: () => void) { ... }
SapperRequest
and SapperResponse
will work with both Polka and Express. You can replace them with the types specific to your server, which are polka.Request
/ http.ServerResponse
and express.Request
/ express.Response
, respectively.
File naming rules
There are three simple rules for naming the files that define your routes:
- A file called
src/routes/about.svelte
corresponds to the/about
route. A file calledsrc/routes/blog/[slug].svelte
corresponds to the/blog/:slug
route, in which caseparams.slug
is available topreload
- The file
src/routes/index.svelte
corresponds to the root of your app.src/routes/about/index.svelte
is treated the same assrc/routes/about.svelte
. - Files and directories with a leading underscore do not create routes. This allows you to colocate helper modules and components with the routes that depend on them — for example you could have a file called
src/routes/_helpers/datetime.js
and it would not create a/_helpers/datetime
route
Error page
In addition to regular pages, there is a 'special' page that Sapper expects to find — src/routes/_error.svelte
. This will be shown when an error occurs while rendering a page.
The error
object is made available to the template along with the HTTP status
code. error
is also available in the page
store.
Regexes in routes
You can use a subset of regular expressions to qualify route parameters, by placing them in parentheses after the parameter name.
For example, src/routes/items/[id([0-9]+)].svelte
would only match numeric IDs — /items/123
would match and make the value 123
available in page.params.id
, but /items/xyz
would not match.
Because of technical limitations, the following characters cannot be used: /
, \
, ?
, :
, (
and )
.
Client API
The @sapper/app
module, which is generated by Sapper based on the shape of your app, contains functions for controlling Sapper programmatically and responding to events.
start({ target })
target
— an element to render pages to
This configures the router and starts the application — listens for clicks on <a>
elements, interacts with the history
API, and renders and updates your Svelte components.
Returns a Promise
that resolves when the initial page has been hydrated.
import * as sapper from '@sapper/app';
sapper.start({
target: document.querySelector('#sapper')
}).then(() => {
console.log('client-side app has started');
});
goto(href, options?)
href
— the page to go tooptions
— not requiredreplaceState
(boolean
, defaultfalse
) — determines whether to usehistory.pushState
(the default) orhistory.replaceState
.noscroll
(boolean
, defaultfalse
) — prevent scroll to top after navigation.
Programmatically navigates to the given href
. If the destination is a Sapper route, Sapper will handle the navigation, otherwise the page will be reloaded with the new href
. In other words, the behaviour is as though the user clicked on a link with this href
.
Returns a Promise
that resolves when the navigation is complete. This can be used to perform actions once the navigation has completed, such as updating a database, store, etc.
import { goto } from '@sapper/app';
const navigateAndSave = async () => {
await goto('/');
saveItem();
}
const saveItem = () => {
// do something with the database
}
prefetch(href)
href
— the page to prefetch
Programmatically prefetches the given page, which means a) ensuring that the code for the page is loaded, and b) calling the page's preload
method with the appropriate options. This is the same behaviour that Sapper triggers when the user taps or mouses over an <a>
element with sapper:prefetch.
Returns a Promise
that resolves when the prefetch is complete.
prefetchRoutes(routes?)
routes
— an optional array of strings representing routes to prefetch
Programmatically prefetches the code for routes that haven't yet been fetched. Typically, you might call this after sapper.start()
is complete, to speed up subsequent navigation (this is the 'L' of the PRPL pattern). Omitting arguments will cause all routes to be fetched, or you can specify routes by any matching pathname such as /about
(to match src/routes/about.svelte
) or /blog/*
(to match src/routes/blog/[slug].svelte
). Unlike prefetch
, this won't call preload
for individual pages.
Returns a Promise
that resolves when the routes have been prefetched.
Preloading
Page components can define a preload
function that runs before the component is created. The values it returns are passed as props to the page.
preload
functions are called when a page is loaded and are typically used to load data that the page depends on - hence its name. This avoids the user seeing the page update as it loads, as is typically the case with client-side loading.
preload
is the Sapper equivalent to getInitialProps
in Next.js or asyncData
in Nuxt.js.
Note that preload
will run both on the server side and on the client side. It may therefore not reference any APIs only present in the browser.
The following code shows how to load a blog post and pass it to the page in the article
prop:
<script context="module">
export async function preload(page, session) {
const { slug } = page.params;
const res = await this.fetch(`blog/${slug}.json`);
const article = await res.json();
return { article };
}
</script>
<script>
export let article;
</script>
<h1>{article.title}</h1>
The routing section describes how the dynamic parameter slug
works.
It should be defined in a context="module"
script since it is not part of the component instance itself – it runs before the component has been created. See the tutorial for more on the module context.
Arguments
The preload
function receives two arguments — page
and session
.
page
is a { host, path, params, query }
object where host
is the URL's host, path
is its pathname, params
is derived from path
and the route filename, and query
is an object of values in the query string.
So if the example above was src/routes/blog/[slug].svelte
and the URL was /blog/some-post?foo=bar&baz
, the following would be true:
page.path === '/blog/some-post'
page.params.slug === 'some-post'
page.query.foo === 'bar'
page.query.baz === true
session
can be used to pass data from the server related to the current request, e.g. the current user. By default it is undefined
. Seeding session data describes how to add data to it.
Return value
If you return a Promise from preload
, the page will delay rendering until the promise resolves. You can also return a plain object. In both cases, the values in the object will be passed into the components as props.
When Sapper renders a page on the server, it will attempt to serialize the resolved value (using devalue) and include it on the page, so that the client doesn't also need to call preload
upon initialization. Serialization will fail if the value includes functions or custom classes (cyclical and repeated references are fine, as are built-ins like Date
, Map
, Set
and RegExp
).
Context
Inside preload
, you have access to three methods:
this.fetch(url, options)
this.error(statusCode, error)
this.redirect(statusCode, location)
this.fetch
In browsers, you can use fetch
to make AJAX requests, for getting data from your server routes (among other things). On the server it's a little trickier — you can make HTTP requests, but you must specify an origin, and you don't have access to cookies. This means that it's impossible to request data based on the user's session, such as data that requires you to be logged in.
To fix this, Sapper provides this.fetch
, which works on the server as well as in the client:
<script context="module">
export async function preload() {
const res = await this.fetch(`server-route.json`);
// ...
}
</script>
It is important to note that preload
may run on either the server or in the client browser. Code called inside preload
blocks:
- should run on the same domain as any upstream API servers requiring credentials
- should not reference
window
,document
or any browser-specific objects - should not reference any API keys or secrets, which will be exposed to the client
If you are using Sapper as an authentication/authorization server, you can use session middleware such as express-session in your app/server.js
in order to maintain user sessions.
this.error
If the user navigated to /blog/some-invalid-slug
, we would want to render a 404 Not Found page. We can do that with this.error
:
<script context="module">
export async function preload({ params, query }) {
const { slug } = params;
const res = await this.fetch(`blog/${slug}.json`);
if (res.status === 200) {
const article = await res.json();
return { article };
}
this.error(404, 'Not found');
}
</script>
The same applies to other error codes you might encounter.
this.redirect
You can abort rendering and redirect to a different location with this.redirect
:
<script context="module">
export async function preload(page, session) {
const { user } = session;
if (!user) {
return this.redirect(302, 'login');
}
return { user };
}
</script>
Typing the function
If you use TypeScript and want to access the above context methods, TypeScript will throw an error and tell you that it does not know the type of this
. To fix it, you need to specify the type of this
(see the official TypeScript documentation). We provide you with helper interfaces so you can type the function like this:
<script context="module" lang="ts">
import type { Preload } from "@sapper/common";
export const preload: Preload = async function(this, page, session) {
const { user } = session;
if (!user) {
return this.redirect(302, 'login'); // TypeScript will know the type of `this` now
}
return { user };
}
</script>
Layouts
So far, we've treated pages as entirely standalone components — upon navigation, the existing component will be destroyed, and a new one will take its place.
But in many apps, there are elements that should be visible on every page, such as top-level navigation or a footer. Instead of repeating them in every page, we can use layout components.
To create a layout component that applies to every page, make a file called src/routes/_layout.svelte
. The default layout component (the one that Sapper uses if you don't bring your own) looks like this...
<slot></slot>
...but we can add whatever markup, styles and behaviour we want. For example, let's add a nav bar:
<!-- src/routes/_layout.svelte -->
<nav>
<a href=".">Home</a>
<a href="about">About</a>
<a href="settings">Settings</a>
</nav>
<slot></slot>
If we create pages for /
, /about
and /settings
...
<!-- src/routes/index.svelte -->
<h1>Home</h1>
<!-- src/routes/about.svelte -->
<h1>About</h1>
<!-- src/routes/settings.svelte -->
<h1>Settings</h1>
...the nav will always be visible, and clicking between the three pages will only result in the <h1>
being replaced.
Nested routes
Suppose we don't just have a single /settings
page, but instead have nested pages like /settings/profile
and /settings/notifications
with a shared submenu (for a real-life example, see github.com/settings).
We can create a layout that only applies to pages below /settings
(while inheriting the root layout with the top-level nav):
<!-- src/routes/settings/_layout.svelte -->
<h1>Settings</h1>
<div class="submenu">
<a href="settings/profile">Profile</a>
<a href="settings/notifications">Notifications</a>
</div>
<slot></slot>
Layout components receive a segment
property which is useful for things like styling:
+<script>
+ export let segment;
+</script>
+
<div class="submenu">
- <a href="settings/profile">Profile</a>
- <a href="settings/notifications">Notifications</a>
+ <a
+ class:selected={segment === "profile"}
+ href="settings/profile"
+ >Profile</a>
+
+ <a
+ class:selected={segment === "notifications"}
+ href="settings/notifications"
+ >Notifications</a>
</div>
Server-side rendering
Sapper will render any component first on the server side and send it to the client as HTML. It will then run the component again on the client side to allow it to update based on dynamic data. This means you need to ensure that components can run both on the client and server side.
If, for example, your components try to access the global variables document
or window
, this will result in an error when the page is pre-rendered on the server side.
If you need access to these variables, you can run code exclusively on the client side by wrapping it in
if (typeof window !== 'undefined') {
// client-only code here
}
Alternatively, you can run it onMount
(see below).
window
Third-party libraries that depend on Sapper works well with most third-party libraries you are likely to come across. However, sometimes libraries have implicit dependencies on window
.
A third-party library might come bundled in a way which allows it to work with multiple different module loaders. This code might check for the existence of window.global
and therefore depend on window
.
Since Sapper will try to execute your component on the server side – where there is no window
– importing such a module will cause the component to fail. You will get an error message saying Server-side code is attempting to access the global variable "window"
.
To solve this, you can load the library by importing it in the onMount
function, which is only called on the client. Since this is a dynamic import you need to use await import
.
<script>
import { onMount } from 'svelte';
let MyComponent;
onMount(async () => {
const module = await import('my-non-ssr-component');
MyComponent = module.default;
});
</script>
<svelte:component this={MyComponent} foo="bar"/>
Stores
The page
and session
values passed to preload
functions are available to components as stores, along with preloading
.
A component can retrieve the stores using the stores
function:
<script>
import { stores } from '@sapper/app';
const { preloading, page, session } = stores();
</script>
preloading
contains a read-only boolean value, indicating whether or not a navigation is pendingpage
contains read-only information about the current route. See preloading for details.session
can be used to pass data from the server related to the current request. It is a writable store, meaning you can update it with new data. If, for example, you populate the session with the current user on the server, you can update the store when the user logs in. Your components will refresh to reflect the new state
Seeding session data
session
is undefined
by default. To populate it with data, implement a function that returns session data given an HTTP request. Pass it as an option to sapper.middleware
when the server is started.
As an example, let's look at how to populate the session with the current user. First, add the session
parameter to the Sapper middleware:
// src/server.js
polka()
.use(
// ...
sapper.middleware({
// customize the session
session: (req, res) => ({
user: req.user
})
})
)
req
is an http.ClientRequest
and res
an http.ServerResponse
.
The session data must be serializable. This means it must not contain functions or custom classes, just built-in JavaScript data types.
The session
function may return a Promise
(or, equivalently, be async
).
Note that if
session
returns aPromise
(or isasync
), it will be re-awaited for on every server-rendered page route.
Link options
sapper:prefetch
Sapper uses code splitting to break your app into small chunks (one per route), ensuring fast startup times.
For dynamic routes, such as our src/routes/blog/[slug].svelte
example, that's not enough. In order to render the blog post, we need to fetch the data for it, and we can't do that until we know what slug
is. In the worst case, that could cause lag as the browser waits for the data to come back from the server.
We can mitigate that by prefetching the data. Adding a sapper:prefetch
attribute to a link...
<a sapper:prefetch href='blog/what-is-sapper'>What is Sapper?</a>
...will cause Sapper to run the page's preload
function as soon as the user hovers over the link (on a desktop) or touches it (on mobile), rather than waiting for the click
event to trigger navigation. Typically, this buys us an extra couple of hundred milliseconds, which is the difference between a user interface that feels laggy, and one that feels snappy.
rel=external
By default, the Sapper runtime intercepts clicks on <a>
elements and bypasses the normal browser navigation for relative (same-origin) URLs that match one of your page routes. We sometimes need to tell Sapper that certain links need to be be handled by normal browser navigation.
Adding a rel=external
attribute to a link...
<a rel=external href='path'>Path</a>
...will trigger a browser navigation when the link is clicked.
sapper:noscroll
When navigating to internal links, Sapper will change the scroll position to 0,0 so that the user is at the very top left of the page. When a hash is defined, it will scroll to the element with a matching ID.
In certain cases, you may wish to disable this behaviour. Adding a sapper:noscroll
attribute to a link...
<a href='path' sapper:noscroll>Path</a>
...will prevent scrolling after the link is clicked.
Building
Up until now we've been using sapper dev
to build our application and run a development server. But when it comes to production, we want to create a self-contained optimized build.
sapper build
This command packages up your application into the __sapper__/build
directory. (You can change this to a custom directory, as well as controlling various other options — do sapper build --help
for more information.)
The output is a Node app that you can run from the project root:
node __sapper__/build
Browser support
Your site is built only for the latest versions of modern evergreen browsers by default. If you are using Rollup, you can use the --legacy
1 flag to build a second bundle that can be used to support legacy browsers like Internet Explorer. Sapper will then serve up the correct bundle at runtime2.
When using --legacy
, Sapper will pass an environment variable SAPPER_LEGACY_BUILD
to your Rollup config. Sapper will then build your client-side bundle twice: once with SAPPER_LEGACY_BUILD
set to true
and once with it set to false
. sapper-template-rollup provides an example of utilizing this configuration.3
You may wish to add this flag to a script in your package.json
:
"scripts": {
"build": "sapper build --legacy",
},
- This option is unrelated to Svelte's
legacy
option - Browsers which do not support
async/await
syntax will be served the legacy bundle - You will also need to polyfill APIs that are not present in older browsers.
Exporting
Many sites are effectively static, which is to say they don't actually need an Express server backing them. Instead, they can be hosted and served as static files, which allows them to be deployed to more hosting environments (such as Netlify or GitHub Pages). Static sites are generally cheaper to operate and have better performance characteristics.
Sapper allows you to export a static site with a single zero-config sapper export
command. In fact, you're looking at an exported site right now!
Static doesn't mean non-interactive — your Svelte components work exactly as they do normally, and you still get all the benefits of client-side routing and prefetching.
sapper export
Inside your Sapper project, try this:
# npx allows you to use locally-installed dependencies
npx sapper export
This will create a __sapper__/export
folder with a production-ready build of your site. You can launch it like so:
npx serve __sapper__/export
Navigate to localhost:5000 (or whatever port serve
picked), and verify that your site works as expected.
You can also add a script to your package.json...
{
"scripts": {
...
"export": "sapper export"
}
}
...allowing you to npm run export
your app.
How it works
When you run sapper export
, Sapper first builds a production version of your app, as though you had run sapper build
, and copies the contents of your static
folder to the destination. It then starts the server, and navigates to the root of your app. From there, it follows any <a>
, <img>
, <link>
and <source>
elements it finds pointing to local URLs, and captures any data served by the app.
Because of this, any pages you want to be included in the exported site must either be reachable by <a>
elements or added to the --entry
option of the sapper export
command.
The --entry
option expects a string of space-separated values. Examples:
sapper export --entry "some-page some-other-page"
Setting --entry
overwrites any defaults. If you wish to add export entrypoints in addition to /
then make sure to add /
as well or sapper export
will not visit the index route.
When not to export
The basic rule is this: for an app to be exportable, any two users hitting the same page of your app must get the same content from the server. In other words, any app that involves user sessions or authentication is not a candidate for sapper export
.
Note that you can still export apps with dynamic routes, like our src/routes/blog/[slug].svelte
example from earlier. sapper export
will intercept fetch
requests made inside preload
, so the data served from src/routes/blog/[slug].json.js
will also be captured.
Route conflicts
Because sapper export
writes to the filesystem, it isn't possible to have two server routes that would cause a directory and a file to have the same name. For example, src/routes/foo/index.js
and src/routes/foo/bar.js
would try to create export/foo
and export/foo/bar
, which is impossible.
The solution is to rename one of the routes to avoid conflict — for example, src/routes/foo-bar.js
. (Note that you would also need to update any code that fetches data from /foo/bar
to reference /foo-bar
instead.)
For pages, we skirt around this problem by writing export/foo/index.html
instead of export/foo
.
Deployment
Sapper apps run anywhere that supports Node 10 or higher.
Deploying from sapper build
You will need the __sapper__/build
and static
directories as well as the production dependencies in node_modules
to run the application. Node production dependencies can be generated with npm ci --prod
, you can then start your app with:
node __sapper__/build
Deploying to Vercel
We can use a third-party library like the vercel-sapper
builder to deploy our projects to Vercel (formerly ZEIT Now). See that project's readme for more details regarding Vercel deployments.
Deploying service workers
Sapper makes the Service Worker file (service-worker.js
) unique by including a timestamp in the source code (calculated using Date.now()
).
In environments where the app is deployed to multiple servers (such as Vercel), it is advisable to use a consistent timestamp for all deployments. Otherwise, users may run into issues where the Service Worker updates unexpectedly because the app hits server 1, then server 2, and they have slightly different timestamps.
To override Sapper's timestamp, you can use an environment variable (e.g. SAPPER_TIMESTAMP
) and then modify the service-worker.js
:
const timestamp = process.env.SAPPER_TIMESTAMP; // instead of `import { timestamp }`
const ASSETS = `cache${timestamp}`;
export default {
/* ... */
plugins: [
/* ... */
replace({
/* ... */
'process.env.SAPPER_TIMESTAMP': process.env.SAPPER_TIMESTAMP || Date.now()
})
]
}
Then you can set it using the environment variable, e.g.:
SAPPER_TIMESTAMP=$(date +%s%3N) npm run build
When deploying to Vercel, you can pass the environment variable into the Vercel CLI tool itself:
vercel -e SAPPER_TIMESTAMP=$(date +%s%3N)
Security
By default, Sapper does not add security headers to your app, but you may add them yourself using middleware such as Helmet.
Content Security Policy (CSP)
Sapper generates inline <script>
s and <style>
s, which can fail to execute if Content Security Policy (CSP) headers do not allow javascript or stylesheets sourced from inline resources.
To work around this, Sapper can inject a nonce which can be configured with middleware to emit the proper CSP headers. The nonce will be applied to the inline <script>
s and <style>
s. Here is an example using Express and Helmet:
// server.js
import uuidv4 from 'uuid/v4';
import helmet from 'helmet';
app.use((req, res, next) => {
res.locals.nonce = uuidv4();
next();
});
app.use(helmet({
contentSecurityPolicy: {
directives: {
scriptSrc: [
"'self'",
(req, res) => `'nonce-${res.locals.nonce}'`
]
}
}
}));
app.use(sapper.middleware());
Using res.locals.nonce
in this way follows the convention set by Helmet's CSP docs.
If a CSP nonce is set via res.locals.nonce
, you can refer to that value via tag in
src/template.html
. For instance:
<script nonce="" src="..."></script>
Base URLs
Ordinarily, the root of your Sapper app is served at /
. But in some cases, your app may need to be served from a different base path — for example, if Sapper only controls part of your domain, or if you have multiple Sapper apps living side-by-side.
This can be done like so:
// app/server.js
express() // or Polka, or a similar framework
.use(
'/my-base-path', // <!-- add this line
compression({ threshold: 0 }),
serve('static'),
sapper.middleware()
)
.listen(process.env.PORT);
Sapper will detect the base path and configure both the server-side and client-side routers accordingly.
If you're exporting your app, you will need to tell the exporter where to begin crawling:
sapper export --basepath my-base-path
Debugging
Debugging your server code is particularly easy with ndb. Install it globally...
npm install -g ndb
...then run Sapper:
ndb npm run dev
This assumes that
npm run dev
runssapper dev
. You can also run Sapper via npx, as inndb npx sapper dev
.
Note that you may not see any terminal output for a few seconds while ndb starts up.