[{"html":"\n\t\t\t\t\t
\n\n\n\t\t\t\t\tSapper 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.
\nSee the migration guide for help migrating from Sapper to SvelteKit. If you get stuck, reach out for help in the Discord chatroom.
\n
Sapper is a framework for building extremely high-performance web apps. You're looking at one right now! There are two basic concepts:
\nsrc/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 overBuilding 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.
\nYou 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.
\n\n\t\t\t\t\tIn war, the soldiers who build bridges, repair roads, clear minefields and conduct demolitions — all under combat conditions — are known as sappers.
\nFor 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.
\n\n\t\t\t\t\tNext.js is a React framework from Vercel (formerly ZEIT), and is the inspiration for Sapper. There are a few notable differences, however:
\nsrc/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)<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 expectThe easiest way to start building a Sapper app is to clone the sapper-template repo with degit:
\nnpx degit "sveltejs/sapper-template#rollup" my-app\n# or: npx degit "sveltejs/sapper-template#webpack" my-app\ncd my-app\nnpm install\nnpm 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!
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:
\nnode scripts/setupTypeScript.js
If you take a look inside the sapper-template repo, you'll see some files that Sapper expects to find:
\n├ package.json\n├ src\n│ ├ routes\n│ │ ├ # your routes here\n│ │ ├ _error.svelte\n│ │ └ index.svelte\n│ ├ client.js\n│ ├ server.js\n│ ├ service-worker.js\n│ └ template.html\n├ static\n│ ├ # your files here\n└ 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.
\n\n\n\n\t\t\t\t\tYou 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
\n
Your package.json contains your app's dependencies and defines a number of scripts:
\nnpm 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 itThis 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.
This must import, and call, the start
function from the generated @sapper/app
module:
import * as sapper from '@sapper/app';\n\nsapper.start({\n\ttarget: document.querySelector('#sapper')\n});
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.
\n\n\t\t\t\t\tThis is a normal Express (or Polka, etc) app, with three requirements:
\nstatic
folder, using for example sirvapp.use(sapper.middleware())
at the end, where sapper
is imported from @sapper/server
process.env.PORT
Beyond that, you can write the server however you like.
\n\n\t\t\t\t\tService 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.
\nBecause 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 the static
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)This file is a template for responses from the server. Sapper will inject content that replaces the following tags:
\n%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%sapper.cspnonce%
— CSP nonce taken from res.locals.nonce
(see Content Security Policy (CSP))This is the meat of your app — the pages and server routes. See the section on routing for the juicy details.
\n\n\t\t\t\t\tThis 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).
\n\n\n\t\t\t\t\tNote 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.
\n
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.
\n","metadata":{"title":"Sapper app structure"},"subsections":[{"slug":"package_json","title":"package.json","level":3},{"slug":"src","title":"src","level":3},{"slug":"src_client_js","title":"src/client.js","level":4},{"slug":"src_server_js","title":"src/server.js","level":4},{"slug":"src_service-worker_js","title":"src/service-worker.js","level":4},{"slug":"src_template_html","title":"src/template.html","level":4},{"slug":"src_routes","title":"src/routes","level":3},{"slug":"static","title":"static","level":3},{"slug":"rollup_config_js_webpack_config_js","title":"rollup.config.js / webpack.config.js","level":3}],"slug":"Sapper_app_structure","file":"01-structure.md"},{"html":"As we've seen, there are two types of route in Sapper — pages, and server routes.
\n\n\t\t\t\t\tPages 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 -->\n<svelte:head>\n\t<title>Welcome</title>\n</svelte:head>\n\n<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 -->\n<svelte:head>\n\t<title>About</title>\n</svelte:head>\n\n<h1>About this site</h1>\n<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 -->\n<script context="module">\n\t// the (optional) preload function takes a\n\t// `{ path, params, query }` object and turns it into\n\t// the data we need to render the page\n\texport async function preload(page, session) {\n\t\t// the `slug` parameter is available because this file\n\t\t// is called [slug].svelte\n\t\tconst { slug } = page.params;\n\n\t\t// `this.fetch` is a wrapper around `fetch` that allows\n\t\t// you to make credentialled requests on both\n\t\t// server and client\n\t\tconst res = await this.fetch(`blog/${slug}.json`);\n\t\tconst article = await res.json();\n\n\t\treturn { article };\n\t}\n</script>\n\n<script>\n\texport let article;\n</script>\n\n<svelte:head>\n\t<title>{article.title}</title>\n</svelte:head>\n\n<h1>{article.title}</h1>\n\n<div class='content'>\n\t{@html article.html}\n</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 -->\n<script context="module">\n\texport async function preload({ params }) {\n\t\tlet [slug, year, month, day] = params.slug;\n\n\t\treturn { slug, year, month, day };\n\t}\n</script>
\n\n\n\t\t\t\t\tSee the section on preloading for more info about
\npreload
andthis.fetch
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\nimport db from './_database.js'; // the underscore tells Sapper this isn't a route\n\nexport async function get(req, res, next) {\n\t// the `slug` parameter is available because this file\n\t// is called [slug].json.js\n\tconst { slug } = req.params;\n\n\tconst article = await db.get(slug);\n\n\tif (article !== null) {\n\t\tres.setHeader('Content-Type', 'application/json');\n\t\tres.end(JSON.stringify(article));\n\t} else {\n\t\tnext();\n\t}\n}
\n\n\n
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:
\nimport { SapperRequest, SapperResponse } from '@sapper/server';\n\nfunction 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.
There are three simple rules for naming the files that define your routes:
\nsrc/routes/about.svelte
corresponds to the /about
route. A file called src/routes/blog/[slug].svelte
corresponds to the /blog/:slug
route, in which case params.slug
is available to preload
src/routes/index.svelte
corresponds to the root of your app. src/routes/about/index.svelte
is treated the same as src/routes/about.svelte
.src/routes/_helpers/datetime.js
and it would not create a /_helpers/datetime
routeIn 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.
You can use a subset of regular expressions to qualify route parameters, by placing them in parentheses after the parameter name.
\nFor 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 )
.
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.
target
— an element to render pages toThis 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';\n\nsapper.start({\n\ttarget: document.querySelector('#sapper')\n}).then(() => {\n\tconsole.log('client-side app has started');\n});
href
— the page to go tooptions
— not requiredreplaceState
(boolean
, default false
) — determines whether to use history.pushState
(the default) or history.replaceState
.noscroll
(boolean
, default false
) — 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';\n\nconst navigateAndSave = async () => {\n\tawait goto('/');\n\tsaveItem();\n}\n\nconst saveItem = () => {\n\t// do something with the database\n}
href
— the page to prefetchProgrammatically 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.
routes
— an optional array of strings representing routes to prefetchProgrammatically 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.
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">\n\texport async function preload(page, session) {\n\t\tconst { slug } = page.params;\n\n\t\tconst res = await this.fetch(`blog/${slug}.json`);\n\t\tconst article = await res.json();\n\n\t\treturn { article };\n\t}\n</script>\n\n<script>\n\texport let article;\n</script>\n\n<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.
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.
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
).
Inside preload
, you have access to three methods:
this.fetch(url, options)
this.error(statusCode, error)
this.redirect(statusCode, location)
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">\n\texport async function preload() {\n\t\tconst res = await this.fetch(`server-route.json`);\n\n\t\t// ...\n\t}\n</script>
It is important to note that preload
may run on either the server or in the client browser. Code called inside preload
blocks:
window
, document
or any browser-specific objectsIf 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.
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">\n\texport async function preload({ params, query }) {\n\t\tconst { slug } = params;\n\n\t\tconst res = await this.fetch(`blog/${slug}.json`);\n\n\t\tif (res.status === 200) {\n\t\t\tconst article = await res.json();\n\t\t\treturn { article };\n\t\t}\n\n\t\tthis.error(404, 'Not found');\n\t}\n</script>
The same applies to other error codes you might encounter.
\n\n\t\t\t\t\tYou can abort rendering and redirect to a different location with this.redirect
:
<script context="module">\n\texport async function preload(page, session) {\n\t\tconst { user } = session;\n\n\t\tif (!user) {\n\t\t\treturn this.redirect(302, 'login');\n\t\t}\n\n\t\treturn { user };\n\t}\n</script>
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">\n\timport type { Preload } from "@sapper/common";\n\n\texport const preload: Preload = async function(this, page, session) {\n\t\tconst { user } = session;\n\n\t\tif (!user) {\n\t\t\treturn this.redirect(302, 'login'); // TypeScript will know the type of `this` now\n\t\t}\n\n\t\treturn { user };\n\t}\n</script>
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.
\nBut 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.
\nTo 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:
\n<!-- src/routes/_layout.svelte -->\n<nav>\n\t<a href=".">Home</a>\n\t<a href="about">About</a>\n\t<a href="settings">Settings</a>\n</nav>\n\n<slot></slot>
If we create pages for /
, /about
and /settings
...
<!-- src/routes/index.svelte -->\n<h1>Home</h1>
<!-- src/routes/about.svelte -->\n<h1>About</h1>
<!-- src/routes/settings.svelte -->\n<h1>Settings</h1>
...the nav will always be visible, and clicking between the three pages will only result in the <h1>
being replaced.
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 -->\n<h1>Settings</h1>\n\n<div class="submenu">\n\t<a href="settings/profile">Profile</a>\n\t<a href="settings/notifications">Notifications</a>\n</div>\n\n<slot></slot>
Layout components receive a segment
property which is useful for things like styling:
+<script>\n+ export let segment;\n+</script>\n+\n<div class="submenu">\n- <a href="settings/profile">Profile</a>\n- <a href="settings/notifications">Notifications</a>\n+ <a\n+ class:selected={segment === "profile"}\n+ href="settings/profile"\n+ >Profile</a>\n+\n+ <a\n+ class:selected={segment === "notifications"}\n+ href="settings/notifications"\n+ >Notifications</a>\n</div>
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.
\nIf, 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
\nif (typeof window !== 'undefined') {\n\t// client-only code here\n}
Alternatively, you can run it onMount
(see below).
window
\n\t\t\t\t\tSapper 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>\n\timport { onMount } from 'svelte';\n\n\tlet MyComponent;\n\n\tonMount(async () => {\n\t\tconst module = await import('my-non-ssr-component');\n\t\tMyComponent = module.default;\n\t});\n</script>\n\n<svelte:component this={MyComponent} foo="bar"/>
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>\n\timport { stores } from '@sapper/app';\n\tconst { preloading, page, session } = stores();\n</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 statesession
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\npolka()\n\t.use(\n\t\t// ...\n\t\tsapper.middleware({\n\t\t\t// customize the session\n\t\t\tsession: (req, res) => ({\n\t\t\t\tuser: req.user\n\t\t\t})\n\t\t})\n\t)
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.
\nThe session
function may return a Promise
(or, equivalently, be async
).
\n\n","metadata":{"title":"Stores"},"subsections":[{"slug":"Seeding_session_data","title":"Seeding session data","level":3}],"slug":"Stores","file":"07-state-management.md"},{"html":"\n\t\t\t\t\tNote that if
\nsession
returns aPromise
(or isasync
), it will be re-awaited for on every server-rendered page route.
Sapper uses code splitting to break your app into small chunks (one per route), ensuring fast startup times.
\nFor 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.
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.
\n\n\t\t\t\t\tWhen 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.
\nIn 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.
\n","metadata":{"title":"Link options"},"subsections":[{"slug":"sapper_prefetch","title":"sapper:prefetch","level":3},{"slug":"rel_external","title":"rel=external","level":3},{"slug":"sapper_noscroll","title":"sapper:noscroll","level":3}],"slug":"Link_options","file":"08-link-options.md"},{"html":"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.
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:
\nnode __sapper__/build
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": {\n\t"build": "sapper build --legacy",\n },
legacy
optionasync/await
syntax will be served the legacy bundleMany 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.
\nSapper 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.
\n\n\t\t\t\t\tInside your Sapper project, try this:
\n# npx allows you to use locally-installed dependencies\nnpx 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...
\n{\n\t"scripts": {\n\t\t...\n\t\t"export": "sapper export"\n\t}\n}
...allowing you to npm run export
your app.
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.
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.
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
.
Sapper apps run anywhere that supports Node 10 or higher.
\n\n\t\t\t\t\tYou 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
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.
Sapper makes the Service Worker file (service-worker.js
) unique by including a timestamp in the source code\n(calculated using Date.now()
).
In environments where the app is deployed to multiple servers (such as Vercel), it is advisable to use a\nconsistent timestamp for all deployments. Otherwise, users may run into issues where the Service Worker\nupdates unexpectedly because the app hits server 1, then server 2, and they have slightly different timestamps.
\nTo override Sapper's timestamp, you can use an environment variable (e.g. SAPPER_TIMESTAMP
) and then modify\nthe service-worker.js
:
const timestamp = process.env.SAPPER_TIMESTAMP; // instead of `import { timestamp }`\n\nconst ASSETS = `cache${timestamp}`;\n\nexport default {\n\t/* ... */\n\tplugins: [\n\t\t/* ... */\n\t\treplace({\n\t\t\t/* ... */\n\t\t\t'process.env.SAPPER_TIMESTAMP': process.env.SAPPER_TIMESTAMP || Date.now()\n\t\t})\n\t]\n}
Then you can set it using the environment variable, e.g.:
\nSAPPER_TIMESTAMP=$(date +%s%3N) npm run build
When deploying to Vercel, you can pass the environment variable into the Vercel CLI tool itself:
\nvercel -e SAPPER_TIMESTAMP=$(date +%s%3N)
By default, Sapper does not add security headers to your app, but you may add them yourself using middleware such as Helmet.
\n\n\t\t\t\t\tSapper 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\nimport uuidv4 from 'uuid/v4';\nimport helmet from 'helmet';\n\napp.use((req, res, next) => {\n\tres.locals.nonce = uuidv4();\n\tnext();\n});\napp.use(helmet({\n\tcontentSecurityPolicy: {\n\t\tdirectives: {\n\t\t\tscriptSrc: [\n\t\t\t\t"'self'",\n\t\t\t\t(req, res) => `'nonce-${res.locals.nonce}'`\n\t\t\t]\n\t\t}\n\t}\n}));\napp.use(sapper.middleware());
Using res.locals.nonce
in this way follows the convention set by\nHelmet's CSP docs.
If a CSP nonce is set via res.locals.nonce
, you can refer to that value via tag %sapper.cspnonce%
in src/template.html
. For instance:
<script nonce="%sapper.cspnonce%" src="..."></script>
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:
\n// app/server.js\n\nexpress() // or Polka, or a similar framework\n\t.use(\n\t\t'/my-base-path', // <!-- add this line\n\t\tcompression({ threshold: 0 }),\n\t\tserve('static'),\n\t\tsapper.middleware()\n\t)\n\t.listen(process.env.PORT);
Sapper will detect the base path and configure both the server-side and client-side routers accordingly.
\nIf you're exporting your app, you will need to tell the exporter where to begin crawling:
\nsapper export --basepath my-base-path
Debugging your server code is particularly easy with ndb. Install it globally...
\nnpm install -g ndb
...then run Sapper:
\nndb npm run dev
\n\nThis assumes that
\nnpm 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.
\n","metadata":{"title":"Debugging"},"subsections":[],"slug":"Debugging","file":"14-debugging.md"}]