Reference
Configuration
Edit this page on GitHubYour project's configuration lives in a svelte.config.js
file at the root of your project. As well as SvelteKit, this config object is used by other tooling that integrates with Svelte such as editor extensions.
ts
importadapter from '@sveltejs/adapter-auto';/** @type {import('@sveltejs/kit').Config} */constconfig = {kit : {adapter :adapter ()}};export defaultconfig ;
ts
interface Config {…}
ts
compilerOptions ?: CompileOptions ;
- default
{}
Options passed to svelte.compile
.
ts
extensions ?: string [];
- default
[".svelte"]
List of file extensions that should be treated as Svelte files.
ts
kit ?: KitConfig ;
SvelteKit options
ts
package ?: { source ?:string ;dir ?:string ;emitTypes ?:boolean ;exports ?(filepath : string): boolean;files ?(filepath : string): boolean;};
@sveltejs/package
options.
ts
preprocess ?: any ;
Preprocessor options, if any. Preprocessing can alternatively also be done through Vite's preprocessor capabilities.
ts
vitePlugin ?: PluginOptions ;
vite-plugin-svelte
plugin options.
ts
[key :string ]:any ;
Any additional options required by tooling that integrates with Svelte.
The kit
property configures SvelteKit, and can have the following properties:
adapterpermalink
- default
undefined
Your adapter is run when executing vite build
. It determines how the output is converted for different platforms.
aliaspermalink
- default
{}
An object containing zero or more aliases used to replace values in import
statements. These aliases are automatically passed to Vite and TypeScript.
ts
/** @type {import('@sveltejs/kit').Config} */constconfig = {kit : {alias : {// this will match a file'my-file': 'path/to/my-file.js',// this will match a directory and its contents// (`my-directory/x` resolves to `path/to/my-directory/x`)'my-directory': 'path/to/my-directory',// an alias ending /* will only match// the contents of a directory, not the directory itself'my-directory/*': 'path/to/my-directory/*'}}};
The built-in
$lib
alias is controlled byconfig.kit.files.lib
as it is used for packaging.
You will need to run
npm run dev
to have SvelteKit automatically generate the required alias configuration injsconfig.json
ortsconfig.json
.
appDirpermalink
- default
"_app"
The directory relative to paths.assets
where the built JS and CSS (and imported assets) are served from. (The filenames therein contain content-based hashes, meaning they can be cached indefinitely). Must not start or end with /
.
csppermalink
Content Security Policy configuration. CSP helps to protect your users against cross-site scripting (XSS) attacks, by limiting the places resources can be loaded from. For example, a configuration like this...
ts
/** @type {import('@sveltejs/kit').Config} */constconfig = {kit : {csp : {directives : {'script-src': ['self']},reportOnly : {'script-src': ['self']}}}};export defaultconfig ;
...would prevent scripts loading from external sites. SvelteKit will augment the specified directives with nonces or hashes (depending on mode
) for any inline styles and scripts it generates.
To add a nonce for scripts and links manually included in src/app.html
, you may use the placeholder %sveltekit.nonce%
(for example <script nonce="%sveltekit.nonce%">
).
When pages are prerendered, the CSP header is added via a <meta http-equiv>
tag (note that in this case, frame-ancestors
, report-uri
and sandbox
directives will be ignored).
When
mode
is'auto'
, SvelteKit will use nonces for dynamically rendered pages and hashes for prerendered pages. Using nonces with prerendered pages is insecure and therefore forbidden.
Note that most Svelte transitions work by creating an inline
<style>
element. If you use these in your app, you must either leave thestyle-src
directive unspecified or addunsafe-inline
.
If this level of configuration is insufficient and you have more dynamic requirements, you can use the handle
hook to roll your own CSP.
ts
mode ?: 'hash' | 'nonce' | 'auto';
Whether to use hashes or nonces to restrict <script>
and <style>
elements. 'auto'
will use hashes for prerendered pages, and nonces for dynamically rendered pages.
ts
directives ?: CspDirectives ;
Directives that will be added to Content-Security-Policy
headers.
ts
reportOnly ?: CspDirectives ;
Directives that will be added to Content-Security-Policy-Report-Only
headers.
csrfpermalink
Protection against cross-site request forgery (CSRF) attacks.
ts
checkOrigin ?: boolean ;
- default
true
Whether to check the incoming origin
header for POST
, PUT
, PATCH
, or DELETE
form submissions and verify that it matches the server's origin.
To allow people to make POST
, PUT
, PATCH
, or DELETE
requests with a Content-Type
of application/x-www-form-urlencoded
, multipart/form-data
, or text/plain
to your app from other origins, you will need to disable this option. Be careful!
dangerZonepermalink
Here be dragons. Enable at your peril.
ts
trackServerFetches ?: boolean ;
Automatically add server-side fetch
ed URLs to the dependencies
map of load
functions. This will expose secrets
to the client if your URL contains them.
embeddedpermalink
- default
false
Whether or not the app is embedded inside a larger app. If true
, SvelteKit will add its event listeners related to navigation etc on the parent of %sveltekit.body%
instead of window
, and will pass params
from the server rather than inferring them from location.pathname
.
envpermalink
Environment variable configuration
ts
dir ?: string ;
- default
"."
The directory to search for .env
files.
ts
publicPrefix ?: string ;
- default
"PUBLIC_"
A prefix that signals that an environment variable is safe to expose to client-side code. See $env/static/public
and $env/dynamic/public
. Note that Vite's envPrefix
must be set separately if you are using Vite's environment variable handling - though use of that feature should generally be unnecessary.
ts
privatePrefix ?: string ;
- default
""
A prefix that signals that an environment variable is unsafe to expose to client-side code. Environment variables matching neither the public nor the private prefix will be discarded completely. See $env/static/private
and $env/dynamic/private
.
filespermalink
Where to find various files within your project.
ts
assets ?: string ;
- default
"static"
a place to put static files that should have stable URLs and undergo no processing, such as favicon.ico
or manifest.json
ts
hooks ?: {…}
ts
lib ?: string ;
- default
"src/lib"
your app's internal library, accessible throughout the codebase as $lib
ts
params ?: string ;
- default
"src/params"
a directory containing parameter matchers
ts
routes ?: string ;
- default
"src/routes"
the files that define the structure of your app (see Routing)
ts
serviceWorker ?: string ;
- default
"src/service-worker"
the location of your service worker's entry point (see Service workers)
ts
appTemplate ?: string ;
- default
"src/app.html"
the location of the template for HTML responses
ts
errorTemplate ?: string ;
- default
"src/error.html"
the location of the template for fallback error responses
inlineStyleThresholdpermalink
- default
0
Inline CSS inside a <style>
block at the head of the HTML. This option is a number that specifies the maximum length of a CSS file in UTF-16 code units, as specified by the String.length property, to be inlined. All CSS files needed for the page and smaller than this value are merged and inlined in a <style>
block.
This results in fewer initial requests and can improve your First Contentful Paint score. However, it generates larger HTML output and reduces the effectiveness of browser caches. Use it advisedly.
moduleExtensionspermalink
- default
[".js", ".ts"]
An array of file extensions that SvelteKit will treat as modules. Files with extensions that match neither config.extensions
nor config.kit.moduleExtensions
will be ignored by the router.
outDirpermalink
- default
".svelte-kit"
The directory that SvelteKit writes files to during dev
and build
. You should exclude this directory from version control.
outputpermalink
Options related to the build output format
ts
preloadStrategy ?: 'modulepreload' | 'preload-js' | 'preload-mjs';
- default
"modulepreload"
SvelteKit will preload the JavaScript modules needed for the initial page to avoid import 'waterfalls', resulting in faster application startup. There are three strategies with different trade-offs:
modulepreload
- uses<link rel="modulepreload">
. This delivers the best results in Chromium-based browsers, in Firefox 115+, and Safari 17+. It is ignored in older browsers.preload-js
- uses<link rel="preload">
. Prevents waterfalls in Chromium and Safari, but Chromium will parse each module twice (once as a script, once as a module). Causes modules to be requested twice in Firefox. This is a good setting if you want to maximise performance for users on iOS devices at the cost of a very slight degradation for Chromium users.preload-mjs
- uses<link rel="preload">
but with the.mjs
extension which prevents double-parsing in Chromium. Some static webservers will fail to serve .mjs files with aContent-Type: application/javascript
header, which will cause your application to break. If that doesn't apply to you, this is the option that will deliver the best performance for the largest number of users, untilmodulepreload
is more widely supported.
pathspermalink
ts
assets ?: '' | `http://${ string }` | `https://${string }`;
- default
""
An absolute path that your app's files are served from. This is useful if your files are served from a storage bucket of some kind.
ts
base ?: '' | `/${ string }`;
- default
""
A root-relative path that must start, but not end with /
(e.g. /base-path
), unless it is the empty string. This specifies where your app is served from and allows the app to live on a non-root path. Note that you need to prepend all your root-relative links with the base value or they will point to the root of your domain, not your base
(this is how the browser works). You can use base
from $app/paths
for that: <a href="{base}/your-page">Link</a>
. If you find yourself writing this often, it may make sense to extract this into a reusable component.
ts
relative ?: boolean |undefined ;
- default
undefined
Whether to use relative asset paths. By default, if paths.assets
is not external, SvelteKit will replace %sveltekit.assets%
with a relative path and use relative paths to reference build artifacts, but base
and assets
imported from $app/paths
will be as specified in your config.
If true
, base
and assets
imported from $app/paths
will be replaced with relative asset paths during server-side rendering, resulting in portable HTML.
If false
, %sveltekit.assets%
and references to build artifacts will always be root-relative paths, unless paths.assets
is an external URL
If your app uses a <base>
element, you should set this to false
, otherwise asset URLs will incorrectly be resolved against the <base>
URL rather than the current page.
prerenderpermalink
See Prerendering.
ts
concurrency ?: number ;
- default
1
How many pages can be prerendered simultaneously. JS is single-threaded, but in cases where prerendering performance is network-bound (for example loading content from a remote CMS) this can speed things up by processing other tasks while waiting on the network response.
ts
crawl ?: boolean ;
- default
true
Whether SvelteKit should find pages to prerender by following links from entries
.
ts
entries ?: Array <'*' | `/${string}`>;
- default
["*"]
An array of pages to prerender, or start crawling from (if crawl: true
). The *
string includes all non-dynamic routes (i.e. pages with no [parameters]
, because SvelteKit doesn't know what value the parameters should have).
ts
handleHttpError ?: PrerenderHttpErrorHandlerValue ;
- default
"fail"
How to respond to HTTP errors encountered while prerendering the app.
'fail'
— fail the build'ignore'
- silently ignore the failure and continue'warn'
— continue, but print a warning(details) => void
— a custom error handler that takes adetails
object withstatus
,path
,referrer
,referenceType
andmessage
properties. If youthrow
from this function, the build will fail
ts
/** @type {import('@sveltejs/kit').Config} */constconfig = {kit : {prerender : {handleHttpError : ({path ,referrer ,message }) => {// ignore deliberate link to shiny 404 pageif (path === '/not-found' &&referrer === '/blog/how-we-built-our-404-page') {return;}// otherwise fail the buildthrow newError (message );}}}};
ts
handleMissingId ?: PrerenderMissingIdHandlerValue ;
- default
"fail"
How to respond when hash links from one prerendered page to another don't correspond to an id
on the destination page.
'fail'
— fail the build'ignore'
- silently ignore the failure and continue'warn'
— continue, but print a warning(details) => void
— a custom error handler that takes adetails
object withpath
,id
,referrers
andmessage
properties. If youthrow
from this function, the build will fail
ts
handleEntryGeneratorMismatch ?: PrerenderEntryGeneratorMismatchHandlerValue ;
- default
"fail"
How to respond when an entry generated by the entries
export doesn't match the route it was generated from.
'fail'
— fail the build'ignore'
- silently ignore the failure and continue'warn'
— continue, but print a warning(details) => void
— a custom error handler that takes adetails
object withgeneratedFromId
,entry
,matchedId
andmessage
properties. If youthrow
from this function, the build will fail
ts
origin ?: string ;
- default
"http://sveltekit-prerender"
The value of url.origin
during prerendering; useful if it is included in rendered content.
serviceWorkerpermalink
ts
register ?: boolean ;
- default
true
Whether to automatically register the service worker, if it exists.
ts
files ?(filepath : string): boolean;
- default
(filename) => !/\.DS_Store/.test(filename)
Determine which files in your static
directory will be available in $service-worker.files
.
typescriptpermalink
ts
config ?: ( config :Record <string, any>) => Record<string, any> | void;
- default
(config) => config
A function that allows you to edit the generated tsconfig.json
. You can mutate the config (recommended) or return a new one.
This is useful for extending a shared tsconfig.json
in a monorepo root, for example.
versionpermalink
Client-side navigation can be buggy if you deploy a new version of your app while people are using it. If the code for the new page is already loaded, it may have stale content; if it isn't, the app's route manifest may point to a JavaScript file that no longer exists.
SvelteKit helps you solve this problem through version management.
If SvelteKit encounters an error while loading the page and detects that a new version has been deployed (using the name
specified here, which defaults to a timestamp of the build) it will fall back to traditional full-page navigation.
Not all navigations will result in an error though, for example if the JavaScript for the next page is already loaded. If you still want to force a full-page navigation in these cases, use techniques such as setting the pollInterval
and then using beforeNavigate
:
<script>
import { beforeNavigate } from '$app/navigation';
import { updated } from '$app/stores';
beforeNavigate(({ willUnload, to }) => {
if ($updated && !willUnload && to?.url) {
location.href = to.url.href;
}
});
</script>
If you set pollInterval
to a non-zero value, SvelteKit will poll for new versions in the background and set the value of the updated
store to true
when it detects one.
ts
name ?: string ;
The current app version string. If specified, this must be deterministic (e.g. a commit ref rather than Math.random()
or Date.now().toString()
), otherwise defaults to a timestamp of the build.
For example, to use the current commit hash, you could do use git rev-parse HEAD
:
ts
import * aschild_process from 'node:child_process';export default {kit : {version : {name :child_process .execSync ('git rev-parse HEAD').toString ().trim ()}}};
ts
pollInterval ?: number ;
- default
0
The interval in milliseconds to poll for version changes. If this is 0
, no polling occurs.