Configuration
Edit this page on GitHubYour project's configuration lives in a svelte.config.js
file. All values are optional. The complete list of options, with defaults, is shown here:
svelte.config.js
ts
constconfig = {// options passed to svelte.compile (https://svelte.dev/docs#compile-time-svelte-compile)compilerOptions : {},// an array of file extensions that should be treated as Svelte componentsextensions : ['.svelte'],kit : {adapter :undefined ,alias : {},appDir : '_app',csp : {mode : 'auto',directives : {'default-src':undefined // ...}},csrf : {checkOrigin : true},env : {dir :process .cwd (),publicPrefix : 'PUBLIC_'},files : {assets : 'static',hooks : {client : 'src/hooks.client',server : 'src/hooks.server'},lib : 'src/lib',params : 'src/params',routes : 'src/routes',serviceWorker : 'src/service-worker',appTemplate : 'src/app.html',errorTemplate : 'src/error.html'},inlineStyleThreshold : 0,moduleExtensions : ['.js', '.ts'],outDir : '.svelte-kit',paths : {assets : '',base : ''},prerender : {concurrency : 1,crawl : true,entries : ['*'],handleHttpError : 'fail',handleMissingId : 'fail',origin : 'http://sveltekit-prerender'},serviceWorker : {register : true,files : (filepath ) => !/\.DS_Store/.test (filepath )},version : {name :Date .now ().toString (),pollInterval : 0}},// options passed to @sveltejs/packagepackage : {source : 'value of kit.files.lib, if available, else src/lib',dir : 'package',emitTypes : true,// excludes all .d.ts and files starting with _ as the nameexports : (filepath ) => !/^_|\/_|\.d\.ts$/.test (filepath ),files : () => true},// options passed to svelte.preprocess (https://svelte.dev/docs#compile-time-svelte-preprocess)preprocess : null};export defaultconfig ;
adapterpermalink
Run when executing vite build
and determines how the output is converted for different platforms. See Adapters.
aliaspermalink
An object containing zero or more aliases used to replace values in import
statements. These aliases are automatically passed to Vite and TypeScript.
svelte.config.js
ts
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
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
An object containing zero or more of the following values:
mode
— 'hash', 'nonce' or 'auto'directives
— an object of[directive]: value[]
pairsreportOnly
— an object of[directive]: value[]
pairs for CSP report-only mode
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...
svelte.config.js
ts
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 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
.
csrfpermalink
Protection against cross-site request forgery attacks:
checkOrigin
— iftrue
, SvelteKit will check the incomingorigin
header forPOST
form submissions and verify that it matches the server's origin
To allow people to make POST
form submissions to your app from other origins, you will need to disable this option. Be careful!
envpermalink
Environment variable configuration:
dir
— the directory to search for.env
files.publicPrefix
— 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'senvPrefix
must be set separately if you are using Vite's environment variable handling - though use of that feature should generally be unnecessary.
filespermalink
An object containing zero or more of the following string
values:
assets
— a place to put static files that should have stable URLs and undergo no processing, such asfavicon.ico
ormanifest.json
hooks
— the location of your client and server hooks (see Hooks)lib
— your app's internal library, accessible throughout the codebase as$lib
params
— a directory containing parameter matchersroutes
— the files that define the structure of your app (see Routing)serviceWorker
— the location of your service worker's entry point (see Service workers)template
— the location of the template for HTML responses
inlineStyleThresholdpermalink
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 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
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
The directory that SvelteKit writes files to during dev
and build
. You should exclude this directory from version control.
packagepermalink
Options related to creating a package.
source
- library directorydir
- output directoryemitTypes
- by default,svelte-package
will automatically generate types for your package in the form of.d.ts
files. While generating types is configurable, we believe it is best for the ecosystem quality to generate types, always. Please make sure you have a good reason when setting it tofalse
(for example when you want to provide handwritten type definitions instead)exports
- a function with the type of(filepath: string) => boolean
. Whentrue
, the filepath will be included in theexports
field of thepackage.json
. Any existing values in thepackage.json
source will be merged with values from the originalexports
field taking precedencefiles
- a function with the type of(filepath: string) => boolean
. Whentrue
, the file will be processed and copied over to the final output folder, specified indir
For advanced filepath
matching, you can use exports
and files
options in conjunction with a globbing library:
svelte.config.js
ts
importmm from 'micromatch';constconfig = {package : {exports : (filepath ) => {if (filepath .endsWith ('.d.ts')) return false;returnmm .isMatch (filepath , ['!**/_*', '!**/internal/**']);},files :mm .matcher ('!**/build.*')}};export defaultconfig ;
pathspermalink
An object containing zero or more of the following string
values:
assets
— 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 kindbase
— 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 yourbase
(this is how the browser works). You can usebase
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.
prerenderpermalink
See Prerendering. An object containing zero or more of the following:
concurrency
— 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 responsecrawl
— determines whether SvelteKit should find pages to prerender by following links from the seed page(s)entries
— an array of pages to prerender, or start crawling from (ifcrawl: 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)handleHttpError
'fail'
— (default) fails the build when a routing error is encountered when following a link'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 failtsconstconfig = {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 build}}}};
handleMissingId
'fail'
— (default) fails the build when a prerendered page links to another prerendered page with a#
fragment that doesn't correspond to anid
'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
origin
— the value ofurl.origin
during prerendering; useful if it is included in rendered content
serviceWorkerpermalink
An object containing zero or more of the following values:
register
- if set tofalse
, will disable automatic service worker registrationfiles
- a function with the type of(filepath: string) => boolean
. Whentrue
, the given file will be available in$service-worker.files
, otherwise it will be excluded.
versionpermalink
An object containing zero or more of the following values:
name
- current app version stringpollInterval
- interval in milliseconds to poll for version changes
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 solves this problem by falling back to traditional full-page navigation if it detects that a new version has been deployed, using the name
specified here (which defaults to a timestamp of the build).
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.