As well as SvelteKit, the plugin options are used by other tooling that integrates with Svelte such as editor extensions.
Any options that don't belong to SvelteKit are passed through to vite-plugin-svelte, so you can set options like inspector here too. The experimental namespace is shared — SvelteKit reads its own flags and forwards the rest.
[!LEGACY]
Prior to SvelteKit 3, config lived in a svelte.config.js file, which is no longer supported. The ability to configure SvelteKit via vite.config.js was added in version 2.62.
Type helper to make it easier to use vite.config.ts
accepts a direct
{@link
UserConfig
}
object, or a function that returns it.
The function receives a
{@link
ConfigEnv
}
object.
Type helper to make it easier to use vite.config.ts
accepts a direct
{@link
UserConfig
}
object, or a function that returns it.
The function receives a
{@link
ConfigEnv
}
object.
As well as SvelteKit, the plugin options are used by other tooling that integrates with Svelte such as editor extensions.
Any options that don't belong to SvelteKit are passed through to vite-plugin-svelte, so you can set options like inspector here too. The experimental namespace is shared — SvelteKit reads its own flags and forwards the rest.
[!LEGACY]
Prior to SvelteKit 3, config lived in a svelte.config.js file, which is no longer supported. The ability to configure SvelteKit via vite.config.js was added in version 2.62.
Your adapter is run when executing vite build. It determines how the output is converted for different platforms.
undefined
:adapterimportadapter()})]});
Deploying
First, build your app with npm run build. This will create the production server in the output directory specified in the adapter options, defaulting to build.
You will need the output directory, the project’s package.json, and the production dependencies in node_modules to run the application. Production dependencies can be generated by copying the package.json and package-lock.json and then running npm ci --omit dev (you can skip this step if your app doesn’t have any dependencies). You can then start your app with this command:
nodebuild
Development dependencies will be bundled into your app using Rolldown. To control whether a given package is bundled or externalised, place it in devDependencies or dependencies respectively in your package.json.
Client assets and prerendered output are served from a list of files recorded during the build.
Compressing responses
You will typically want to compress responses coming from the server. If you’re already deploying your server behind a reverse proxy for SSL or load balancing, it typically results in better performance to also handle compression at that layer since Node.js is single-threaded.
However, if you’re building a custom server and do want to add a compression middleware there, note that we would recommend using @polka/compression since SvelteKit streams responses and the more popular compression package does not support streaming and may cause errors when used.
Environment variables
In dev and preview, SvelteKit will read environment variables from your .env file (or .env.local, or .env.[mode], as determined by Vite.)
In production, .env files are not automatically loaded. To do so, use the --env-file flag when running the built app:
node--env-file=.envbuild
PORT, HOST and SOCKET_PATH
By default, the server will accept connections on 0.0.0.0 using port 3000. These can be customised with the PORT and HOST environment variables:
HOST=127.0.0.1PORT=4000nodebuild
Alternatively, the server can be configured to accept connections on a specified socket path. When this is done using the SOCKET_PATH environment variable, the HOST and PORT environment variables will be disregarded.
SOCKET_PATH=/tmp/socketnodebuild
PROTOCOL_HEADER, HOST_HEADER, and PORT_HEADER
HTTP doesn’t give SvelteKit a reliable way to know the URL that is currently being requested. By default, SvelteKit will derive the origin from the request’s host header (and the https protocol, if no PROTOCOL_HEADER is set).
If your app is served from an origin that isn’t known at request time — for example because it’s behind a reverse proxy that doesn’t pass the host header, or because you want to use a canonical origin for CSRF checks that differs from the request’s host — you can set the paths.origin option in your vite.config.js:
As well as SvelteKit, the plugin options are used by other tooling that integrates with Svelte such as editor extensions.
Any options that don't belong to SvelteKit are passed through to vite-plugin-svelte, so you can set options like inspector here too. The experimental namespace is shared — SvelteKit reads its own flags and forwards the rest.
[!LEGACY]
Prior to SvelteKit 3, config lived in a svelte.config.js file, which is no longer supported. The ability to configure SvelteKit via vite.config.js was added in version 2.62.
Type helper to make it easier to use vite.config.ts
accepts a direct
{@link
UserConfig
}
object, or a function that returns it.
The function receives a
{@link
ConfigEnv
}
object.
Type helper to make it easier to use vite.config.ts
accepts a direct
{@link
UserConfig
}
object, or a function that returns it.
The function receives a
{@link
ConfigEnv
}
object.
As well as SvelteKit, the plugin options are used by other tooling that integrates with Svelte such as editor extensions.
Any options that don't belong to SvelteKit are passed through to vite-plugin-svelte, so you can set options like inspector here too. The experimental namespace is shared — SvelteKit reads its own flags and forwards the rest.
[!LEGACY]
Prior to SvelteKit 3, config lived in a svelte.config.js file, which is no longer supported. The ability to configure SvelteKit via vite.config.js was added in version 2.62.
The origin of your app, used for CSRF protection and prerendering.
By default, this is undefined, meaning SvelteKit will derive the origin from request.url (which is set by the adapter, and ultimately by the platform).
If your app is served from an origin that isn't known at request time — for example because it's deployed to a preview deployment whose URL isn't known at build time, or because it's behind a reverse proxy that doesn't pass the host header — you can set this to a string like https://my-site.com.
This is also used as the value of url.origin during prerendering (when unset, it defaults to http://sveltekit-prerender), and as the trusted origin for CSRF checks on form submissions and remote function calls.
It is possible to modify this object, but such modifications will not be
reflected outside the Node.js process, or (unless explicitly requested)
to other Worker threads.
In other words, the following example would not work:
Assigning a property on process.env will implicitly convert the value
to a string. This behavior is deprecated. Future versions of Node.js may
throw an error when the value is not a string, number, or boolean.
Unless explicitly specified when creating a Worker instance,
each Worker thread has its own copy of process.env, based on its
parent thread's process.env, or whatever was specified as the env option
to the Worker constructor. Changes to process.env will not be visible
across Worker threads, and only the main thread can make changes that
are visible to the operating system or to native add-ons. On Windows, a copy of process.env on a Worker instance operates in a case-sensitive manner
unlike the main thread.
v0.1.27
.ORIGINstring|undefined}})]});
When paths.origin is not set (the default), adapter-node derives the origin from the request — using the host header (and PROTOCOL_HEADER / PORT_HEADER if set) — and sets request.url accordingly. Otherwise, the configured value is used as the trusted self-origin for CSRF checks on form submissions and remote function calls, and as the value of url.origin during prerendering.
Alternatively, you can specify headers that tell SvelteKit about the request protocol and host, from which it can construct the origin URL:
x-forwarded-proto and x-forwarded-host are de facto standard headers that forward the original protocol and host if you’re using a reverse proxy (think load balancers and CDNs). You should only set these variables if your server is behind a trusted reverse proxy; otherwise, it’d be possible for clients to spoof these headers.
If you’re hosting your proxy on a non-standard port and your reverse proxy supports x-forwarded-port, you can also set PORT_HEADER=x-forwarded-port.
If adapter-node can’t correctly determine the URL of your deployment, you may experience this error when using form actions:
Cross-site POST form submissions are forbidden
ADDRESS_HEADER and XFF_DEPTH
The RequestEvent object passed to hooks and endpoints includes an event.getClientAddress() function that returns the client’s IP address. By default this is the connecting remoteAddress. If your server is behind one or more proxies (such as a load balancer), this value will contain the innermost proxy’s IP address rather than the client’s, so we need to specify an ADDRESS_HEADER to read the address from:
ADDRESS_HEADER=True-Client-IPnodebuild
Headers can easily be spoofed. As with PROTOCOL_HEADER and HOST_HEADER, you should know what you’re doing before setting these.
If the ADDRESS_HEADER is X-Forwarded-For, the header value will contain a comma-separated list of IP addresses. The XFF_DEPTH environment variable should specify how many trusted proxies sit in front of your server. E.g. if there are three trusted proxies, proxy 3 will forward the addresses of the original connection and the first two proxies:
We instead read from the right, accounting for the number of trusted proxies. In this case, we would use XFF_DEPTH=3.
If you need to read the left-most address instead (and don’t care about spoofing) — for example, to offer a geolocation service, where it’s more important for the IP address to be real than trusted, you can do so by inspecting the x-forwarded-for header within your app.
BODY_SIZE_LIMIT
The maximum request body size to accept in bytes including while streaming. The body size can also be specified with a unit suffix for kilobytes (K), megabytes (M), or gigabytes (G). For example, 512K or 1M. Defaults to 512kb. You can disable this option with a value of Infinity (0 in older versions of the adapter) and implement a custom check in handle if you need something more advanced.
SHUTDOWN_TIMEOUT
The number of seconds to wait before forcefully closing any remaining connections after receiving a SIGTERM or SIGINT signal. Defaults to 30. Internally the adapter calls closeAllConnections. See Graceful shutdown for more details.
IDLE_TIMEOUT
When using systemd socket activation, IDLE_TIMEOUT specifies the number of seconds after which the app is automatically put to sleep when receiving no requests. If not set, the app runs continuously. See Socket activation for more details.
As well as SvelteKit, the plugin options are used by other tooling that integrates with Svelte such as editor extensions.
Any options that don't belong to SvelteKit are passed through to vite-plugin-svelte, so you can set options like inspector here too. The experimental namespace is shared — SvelteKit reads its own flags and forwards the rest.
[!LEGACY]
Prior to SvelteKit 3, config lived in a svelte.config.js file, which is no longer supported. The ability to configure SvelteKit via vite.config.js was added in version 2.62.
Type helper to make it easier to use vite.config.ts
accepts a direct
{@link
UserConfig
}
object, or a function that returns it.
The function receives a
{@link
ConfigEnv
}
object.
Type helper to make it easier to use vite.config.ts
accepts a direct
{@link
UserConfig
}
object, or a function that returns it.
The function receives a
{@link
ConfigEnv
}
object.
As well as SvelteKit, the plugin options are used by other tooling that integrates with Svelte such as editor extensions.
Any options that don't belong to SvelteKit are passed through to vite-plugin-svelte, so you can set options like inspector here too. The experimental namespace is shared — SvelteKit reads its own flags and forwards the rest.
[!LEGACY]
Prior to SvelteKit 3, config lived in a svelte.config.js file, which is no longer supported. The ability to configure SvelteKit via vite.config.js was added in version 2.62.
Your adapter is run when executing vite build. It determines how the output is converted for different platforms.
undefined
:adapterimportadapter({ // default options are shownout(property)out:string:'build',precompress(property)precompress:boolean:true,envPrefix(property)envPrefix:string:''})})]});
out
The directory to build the server to. It defaults to build — i.e. node build would start the server locally after it has been created.
precompress
Generates .br and .gz variants of client and prerendered assets during the build. The server negotiates Accept-Encoding per request, preferring brotli over gzip, and each variant carries its own ETag. It defaults to true.
envPrefix
If you need to change the name of the environment variables used to configure the deployment (for example, to deconflict with environment variables you don’t control), you can specify a prefix:
wait for requests that have already been made but not received a response yet to finish and close connections once they become idle (server.closeIdleConnections)
If you want to customize this behaviour you can use a custom server.
You can listen to the sveltekit:shutdown event which is emitted after the HTTP server has closed all connections. Unlike Node’s exit event, the sveltekit:shutdown event supports asynchronous operations and is always emitted when all connections are closed even if the server has dangling work such as open database connections.
Adds the listener function to the end of the listeners array for the event
named eventName. No checks are made to see if the listener has already
been added. Multiple calls passing the same combination of eventName and
listener will result in the listener being added, and called, multiple times.
Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. The emitter.prependListener() method can be used as an alternative to add the
event listener to the beginning of the listeners array.
import{EventEmitter}from'node:events';constmyEE=newEventEmitter();myEE.on('foo',()=>console.log('a'));myEE.prependListener('foo',()=>console.log('b'));myEE.emit('foo');// Prints:// b// a
Most Linux operating systems today use a modern process manager called systemd to start the server and run and manage services. You can configure your server to allocate a socket and start and scale your app on demand. This is called socket activation. In this case, the OS will pass two environment variables to your app — LISTEN_PID and LISTEN_FDS. The adapter will then listen on file descriptor 3 which refers to a systemd socket unit that you will have to create.
You can still use envPrefix with systemd socket activation. LISTEN_PID and LISTEN_FDS are always read without a prefix.
To take advantage of socket activation follow these steps.
Run your app as a systemd service. It can either run directly on the host system or inside a container (using Docker or a systemd portable service for example). If you additionally pass an IDLE_TIMEOUT environment variable to your app it will gracefully shutdown if there are no requests for IDLE_TIMEOUT seconds. systemd will automatically start your app again when new requests are coming in.
Make sure systemd has recognised both units by running sudo systemctl daemon-reload. Then enable the socket on boot and start it immediately using sudo systemctl enable --now myapp.socket. The app will then automatically start once the first request is made to localhost:3000.
Custom server
The build directory contains two entry points, index.js and handler.js. Running index.js — e.g. node build, if you use the default build directory — will start a server on the configured port.
Alternatively, you can import the handler.js file, which exports a handler suitable for use with Express, Connect or Polka (or even just the built-in http.createServer) and set up your own server:
my-server
import{handlerimporthandler}from'./build/handler.js';importexpressimportexpressfrom'express';constappconstapp:any=expressimportexpress();// add a route that lives separately from the SvelteKit appappconstapp:any.getany('/healthcheck',(req(parameter)req:any,res(parameter)res:any)=>{res(parameter)res:any.endany('ok');});// let SvelteKit handle everything else, including serving prerendered pages and static assetsappconstapp:any.useany(handlerimporthandler);appconstapp:any.listenany(3000,()=>{consolenamespaceconsolevarconsole:Console
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
When you use handler.js in a custom server, only the environment variables read by the handler itself take effect: PROTOCOL_HEADER, HOST_HEADER, PORT_HEADER, ADDRESS_HEADER, XFF_DEPTH, and BODY_SIZE_LIMIT.
The server-lifecycle variables (PORT, HOST, SOCKET_PATH, SHUTDOWN_TIMEOUT, IDLE_TIMEOUT, KEEP_ALIVE_TIMEOUT, HEADERS_TIMEOUT, LISTEN_PID, LISTEN_FDS) are only honored by the default node build server. Implement them yourself in a custom server if you need the same behavior — for example, the snippet above listens on a hardcoded 3000 regardless of PORT.