How do I fix the error I’m getting trying to include a package?
Most issues related to including a library are due to incorrect packaging. You can check if a library’s packaging is compatible with Node.js by entering it into the publint website.
Here are a few things to keep in mind when checking if a library is packaged correctly:
exports takes precedence over the other entry point fields such as main and module. Adding an exports field may not be backwards-compatible as it prevents deep imports.
ESM files should end with .mjs unless "type": "module" is set in which any case CommonJS files should end with .cjs.
main should be defined if exports is not. It should be either a CommonJS or ESM file and adhere to the previous bullet. If a module field is defined, it should refer to an ESM file.
Svelte components should be distributed as uncompiled .svelte files with any JS in the package written as ESM only. Custom script and style languages, like TypeScript and SCSS, should be preprocessed as vanilla JS and CSS respectively. We recommend using svelte-package for packaging Svelte libraries, which will do this for you.
Libraries work best in the browser with Vite when they distribute an ESM version, especially if they are dependencies of a Svelte component library. You may wish to suggest to library authors that they provide an ESM version. However, CommonJS (CJS) dependencies should work as well since, by default, vite-plugin-svelte will ask Vite to pre-bundle them using esbuild to convert them to ESM.
If you are still encountering issues we recommend searching both the Vite issue tracker and the issue tracker of the library in question. Sometimes issues can be worked around by fiddling with the optimizeDeps or ssr config values though we recommend this as only a short-term workaround in favor of fixing the library in question.
How do I use the view transitions API?
While SvelteKit does not have any specific integration with view transitions, you can call document.startViewTransition in onNavigate to trigger a view transition on every client-side navigation.
A lifecycle function that runs the supplied callback immediately before we navigate to a new URL except during full-page navigations.
If you return a Promise, SvelteKit will wait for it to resolve before completing the navigation. This allows you to — for example — use document.startViewTransition. Avoid promises that are slow to resolve, since navigation will appear stalled to the user.
If a function (or a Promise that resolves to a function) is returned from the callback, it will be called once the DOM has updated.
onNavigate must be called during a component initialization. It remains active as long as the component is mounted.
A lifecycle function that runs the supplied callback immediately before we navigate to a new URL except during full-page navigations.
If you return a Promise, SvelteKit will wait for it to resolve before completing the navigation. This allows you to — for example — use document.startViewTransition. Avoid promises that are slow to resolve, since navigation will appear stalled to the user.
If a function (or a Promise that resolves to a function) is returned from the callback, it will be called once the DOM has updated.
onNavigate must be called during a component initialization. It remains active as long as the component is mounted.
The startViewTransition() method of the Document interface starts a new same-document (SPA) view transition and returns a ViewTransition object to represent it.
A callback used to initialize the promise. This callback is passed two arguments:
a resolve callback used to resolve the promise with a value or the result of another promise,
and a reject callback used to reject the promise with a provided reason or error.
The startViewTransition() method of the Document interface starts a new same-document (SPA) view transition and returns a ViewTransition object to represent it.
A promise that resolves once the navigation is complete, and rejects if the navigation
fails or is aborted. In the case of a willUnload navigation, the promise will never resolve
Put the code to query your database in a server route - don’t query the database in .svelte files. You can create a db.js or similar that sets up a connection immediately and makes the client accessible throughout the app as a singleton. You can execute any one-time setup code in hooks.server.js and import your database helpers into any endpoint that needs them.
You can use the Svelte CLI to automatically set up database integrations.
How do I use a client-side library accessing document or window?
If you need access to the document or window variables or otherwise need code to run only on the client-side you can wrap it in a browser check:
onMount, like $effect, schedules a function to run as soon as the component has been mounted to the DOM.
Unlike $effect, the provided function only runs once.
It must be called during the component's initialisation (but doesn't need to live inside the component;
it can be called from an external module). If a function is returned synchronously from onMount,
it will be called when the component is unmounted.
onMount, like $effect, schedules a function to run as soon as the component has been mounted to the DOM.
Unlike $effect, the provided function only runs once.
It must be called during the component's initialisation (but doesn't need to live inside the component;
it can be called from an external module). If a function is returned synchronously from onMount,
it will be called when the component is unmounted.
If the library you’d like to use is side-effect free you can also statically import it and it will be tree-shaken out in the server-side build where onMount will be automatically replaced with a no-op:
onMount, like $effect, schedules a function to run as soon as the component has been mounted to the DOM.
Unlike $effect, the provided function only runs once.
It must be called during the component's initialisation (but doesn't need to live inside the component;
it can be called from an external module). If a function is returned synchronously from onMount,
it will be called when the component is unmounted.
onMount, like $effect, schedules a function to run as soon as the component has been mounted to the DOM.
Unlike $effect, the provided function only runs once.
It must be called during the component's initialisation (but doesn't need to live inside the component;
it can be called from an external module). If a function is returned synchronously from onMount,
it will be called when the component is unmounted.
Finally, you may also consider using an {#await} block:
index
<script>import{browser}from'$app/environment';constpromise=browser?import('./BrowserComponent.svelte'):import('./ServerComponent.svelte');</script>{#awaitpromise}<p>Loading...</p>{:thenmodule}<module.default/>{:catcherror}<p>Something went wrong: {error.message}</p>{/await}
<scriptlang="ts">import{browser}from'$app/environment';constpromise=browser?import('./BrowserComponent.svelte'):import('./ServerComponent.svelte');</script>{#awaitpromise}<p>Loading...</p>{:thenmodule}<module.default/>{:catcherror}<p>Something went wrong: {error.message}</p>{/await}
How do I use a different backend API server?
You can use event.fetch to request data from an external API server, but be aware that you would need to deal with CORS, which will result in complications such as generally requiring requests to be preflighted resulting in higher latency. Requests to a separate subdomain may also increase latency due to an additional DNS lookup, TLS setup, etc. If you wish to use this method, you may find handleFetch helpful.
Another approach is to set up a proxy to bypass CORS headaches. In production, you would rewrite a path like /api to the API server; for local development, use Vite’s server.proxy option.
How to set up rewrites in production will depend on your deployment platform. If rewrites aren’t an option, you could alternatively add an API route:
The parameters of the current route - e.g. for a route like /blog/[slug], a { slug: string } object.
In the context of a remote function request initiated by the client, this relates to the page the remote function
was called from, not the URL of the endpoint SvelteKit creates for the remote function. Never use this to determine
whether or not a user is authorized to access certain data, as these values are part of the request which could be manipulated.
,url(parameter)url:URL
The requested URL.
In the context of a remote function request initiated by the client, this relates to the page the remote function
was called from, not the URL of the endpoint SvelteKit creates for the remote function. Never use this to determine
whether or not a user is authorized to access certain data, as these values are part of the request which could be manipulated.
The parameters of the current route - e.g. for a route like /blog/[slug], a { slug: string } object.
In the context of a remote function request initiated by the client, this relates to the page the remote function
was called from, not the URL of the endpoint SvelteKit creates for the remote function. Never use this to determine
whether or not a user is authorized to access certain data, as these values are part of the request which could be manipulated.
.pathany+url(parameter)url:URL
The requested URL.
In the context of a remote function request initiated by the client, this relates to the page the remote function
was called from, not the URL of the endpoint SvelteKit creates for the remote function. Never use this to determine
whether or not a user is authorized to access certain data, as these values are part of the request which could be manipulated.
.search(property)URL.search:string
The search property of the URL interface is a search string, also called a query string, that is a string containing a "?" followed by the parameters of the URL. If the URL does not have a search query, this property contains an empty string, "".
The parameters of the current route - e.g. for a route like /blog/[slug], a { slug: string } object.
In the context of a remote function request initiated by the client, this relates to the page the remote function
was called from, not the URL of the endpoint SvelteKit creates for the remote function. Never use this to determine
whether or not a user is authorized to access certain data, as these values are part of the request which could be manipulated.
,url(parameter)url:URL
The requested URL.
In the context of a remote function request initiated by the client, this relates to the page the remote function
was called from, not the URL of the endpoint SvelteKit creates for the remote function. Never use this to determine
whether or not a user is authorized to access certain data, as these values are part of the request which could be manipulated.
The parameters of the current route - e.g. for a route like /blog/[slug], a { slug: string } object.
In the context of a remote function request initiated by the client, this relates to the page the remote function
was called from, not the URL of the endpoint SvelteKit creates for the remote function. Never use this to determine
whether or not a user is authorized to access certain data, as these values are part of the request which could be manipulated.
.pathany+url(parameter)url:URL
The requested URL.
In the context of a remote function request initiated by the client, this relates to the page the remote function
was called from, not the URL of the endpoint SvelteKit creates for the remote function. Never use this to determine
whether or not a user is authorized to access certain data, as these values are part of the request which could be manipulated.
.search(property)URL.search:string
The search property of the URL interface is a search string, also called a query string, that is a string containing a "?" followed by the parameters of the URL. If the URL does not have a search query, this property contains an empty string, "".
(Note that you may also need to proxy POST / PATCH etc requests, and forward request.headers, depending on your needs.)
How do I use middleware?
adapter-node builds a middleware that you can use with your own server for production mode. In dev, you can add middleware to Vite by using a Vite plugin. For example:
Returns the SvelteKit Vite plugins.
Since version 2.62.0 you can pass configuration directly, in which case svelte.config.js is ignored.
Any options that don't belong to SvelteKit are passed through to vite-plugin-svelte.
Configure the vite server. The hook receives the
{@link
ViteDevServer
}
instance. This can also be used to store a reference to the server
for use in other hooks.
The hooks will be called before internal middlewares are applied. A hook
can return a post hook that will be called after internal middlewares
are applied. Hook can be async functions and will be called in series.
Utilize the given middleware handle to the given route,
defaulting to /. This "route" is the mount-point for the
middleware, when given a value other than / the middleware
is only effective when that segment is present in the request's
pathname.
For example if we were to mount a function at /admin, it would
be invoked on /admin, and /admin/settings, however it would
not be invoked for /, or /posts.
The console module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
A global console instance configured to write to process.stdout and
process.stderr. The global console can be used without importing the node:console module.
Warning: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the note on process I/O for
more information.
Example using the global console:
console.log('hello world');// Prints: hello world, to stdoutconsole.log('hello %s','world');// Prints: hello world, to stdoutconsole.error(newError('Whoops, something bad happened'));// Prints error message and stack trace to stderr:// Error: Whoops, something bad happened// at [eval]:5:15// at Script.runInThisContext (node:vm:132:18)// at Object.runInThisContext (node:vm:309:38)// at node:internal/process/execution:77:19// at [eval]-wrapper:6:22// at evalScript (node:internal/process/execution:76:60)// at node:internal/main/eval_string:23:3constname='Will Robinson';console.warn(`Danger${name}! Danger!`);// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();consterr=getStreamSomehow();constmyConsole=newconsole.Console(out,err);myConsole.log('hello world');// Prints: hello world, to outmyConsole.log('hello %s','world');// Prints: hello world, to outmyConsole.error(newError('Whoops, something bad happened'));// Prints: [Error: Whoops, something bad happened], to errconstname='Will Robinson';myConsole.warn(`Danger${name}! Danger!`);// Prints: Danger Will Robinson! Danger!, to err
Prints to stdout with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to printf(3)
(the arguments are all passed to util.format()).
constcount=5;console.log('count: %d',count);// Prints: count: 5, to stdoutconsole.log('count:',count);// Prints: count: 5, to stdout
Ensure that you set process.env.HOST to the server's host name, or consider replacing this part entirely. If using req.headers.host, ensure proper
validation is used, as clients may specify a custom Host header.
Returns the SvelteKit Vite plugins.
Since version 2.62.0 you can pass configuration directly, in which case svelte.config.js is ignored.
Any options that don't belong to SvelteKit are passed through to vite-plugin-svelte.
Returns the SvelteKit Vite plugins.
Since version 2.62.0 you can pass configuration directly, in which case svelte.config.js is ignored.
Any options that don't belong to SvelteKit are passed through to vite-plugin-svelte.
There are two types of plugins in Vite. App plugins and environment plugins.
Environment Plugins are defined by a constructor function that will be called
once per each environment allowing users to have completely different plugins
for each of them. The constructor gets the resolved environment after the server
and builder has already been created simplifying config access and cache
management for environment specific plugins.
Environment Plugins are closer to regular rollup plugins. They can't define
app level hooks (like config, configResolved, configureServer, etc).
There are two types of plugins in Vite. App plugins and environment plugins.
Environment Plugins are defined by a constructor function that will be called
once per each environment allowing users to have completely different plugins
for each of them. The constructor gets the resolved environment after the server
and builder has already been created simplifying config access and cache
management for environment specific plugins.
Environment Plugins are closer to regular rollup plugins. They can't define
app level hooks (like config, configResolved, configureServer, etc).
={name(property)OutputPlugin.name:string
The name of the plugin, for use in error messages and logs.
Configure the vite server. The hook receives the
{@link
ViteDevServer
}
instance. This can also be used to store a reference to the server
for use in other hooks.
The hooks will be called before internal middlewares are applied. A hook
can return a post hook that will be called after internal middlewares
are applied. Hook can be async functions and will be called in series.
Utilize the given middleware handle to the given route,
defaulting to /. This "route" is the mount-point for the
middleware, when given a value other than / the middleware
is only effective when that segment is present in the request's
pathname.
For example if we were to mount a function at /admin, it would
be invoked on /admin, and /admin/settings, however it would
not be invoked for /, or /posts.
The console module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
A global console instance configured to write to process.stdout and
process.stderr. The global console can be used without importing the node:console module.
Warning: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the note on process I/O for
more information.
Example using the global console:
console.log('hello world');// Prints: hello world, to stdoutconsole.log('hello %s','world');// Prints: hello world, to stdoutconsole.error(newError('Whoops, something bad happened'));// Prints error message and stack trace to stderr:// Error: Whoops, something bad happened// at [eval]:5:15// at Script.runInThisContext (node:vm:132:18)// at Object.runInThisContext (node:vm:309:38)// at node:internal/process/execution:77:19// at [eval]-wrapper:6:22// at evalScript (node:internal/process/execution:76:60)// at node:internal/main/eval_string:23:3constname='Will Robinson';console.warn(`Danger${name}! Danger!`);// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();consterr=getStreamSomehow();constmyConsole=newconsole.Console(out,err);myConsole.log('hello world');// Prints: hello world, to outmyConsole.log('hello %s','world');// Prints: hello world, to outmyConsole.error(newError('Whoops, something bad happened'));// Prints: [Error: Whoops, something bad happened], to errconstname='Will Robinson';myConsole.warn(`Danger${name}! Danger!`);// Prints: Danger Will Robinson! Danger!, to err
Prints to stdout with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to printf(3)
(the arguments are all passed to util.format()).
constcount=5;console.log('count: %d',count);// Prints: count: 5, to stdoutconsole.log('count:',count);// Prints: count: 5, to stdout
Ensure that you set process.env.HOST to the server's host name, or consider replacing this part entirely. If using req.headers.host, ensure proper
validation is used, as clients may specify a custom Host header.
Returns the SvelteKit Vite plugins.
Since version 2.62.0 you can pass configuration directly, in which case svelte.config.js is ignored.
Any options that don't belong to SvelteKit are passed through to vite-plugin-svelte.
Sort of. The Plug’n’Play feature, aka ‘pnp’, is broken (it deviates from the Node module resolution algorithm, and doesn’t yet work with native JavaScript modules which SvelteKit — along with an increasing number of packages — uses). You can use nodeLinker: 'node-modules' in your .yarnrc.yml file to disable pnp, but it’s probably easier to just use npm or pnpm, which is similarly fast and efficient but without the compatibility headaches.
How do I use with Yarn 3?
Currently ESM Support within the latest Yarn (version 3) is considered experimental.
The below seems to work although your results may vary. First create a new application:
yarncreatesveltemyappcdmyapp
And enable Yarn Berry:
yarnsetversionberryyarninstall
One of the more interesting features of Yarn Berry is the ability to have a single global cache for packages, instead of having multiple copies for each project on the disk. However, setting enableGlobalCache to true causes building to fail, so it is recommended to add the following to the .yarnrc.yml file:
nodeLinker:node-modules
This will cause packages to be downloaded into a local node_modules directory but avoids the above problem and is your best bet for using version 3 of Yarn at this point in time.