Skip to main content

Cloudflare

To deploy to Cloudflare Workers, use adapter-cloudflare.

This adapter will be installed by default when you use adapter-auto. If you plan on staying with Cloudflare Workers, you can switch from adapter-auto to using this adapter directly so that event.platform is emulated during local development, type declarations are automatically applied, and the ability to set Cloudflare-specific options is provided.

Comparisons

  • adapter-cloudflare – supports all SvelteKit features; builds for Cloudflare Workers Static Assets
  • adapter-cloudflare-workers – deprecated. Supports all SvelteKit features; builds for Cloudflare Workers Sites
  • adapter-static – only produces client-side static assets; compatible with Cloudflare Workers Static Assets and Cloudflare Pages

Usage

Install with npm i -D @sveltejs/adapter-cloudflare, then add the adapter to your svelte.config.js:

svelte.config
import import adapteradapter from '@sveltejs/adapter-cloudflare';

/** @type {import('@sveltejs/kit').Config} */
const 
const config: {
    kit: {
        adapter: any;
    };
}
@type
{import('@sveltejs/kit').Config}
config
= {
kit: {
    adapter: any;
}
kit
: {
adapter: anyadapter: import adapteradapter({ // See the next section for an explanations of these options vitePluginOptions: undefinedvitePluginOptions: var undefinedundefined, worker: booleanworker: true }) } }; export default
const config: {
    kit: {
        adapter: any;
    };
}
@type
{import('@sveltejs/kit').Config}
config
;

And to your vite.config.js:

vite.config
import const svelteConfig: Config
@type
{import('@sveltejs/kit').Config}
svelteConfig
from './svelte.config.js';
import {
function sveltekit(options?: {
    adapter?: import("@sveltejs/kit").Adapter;
} | undefined): Promise<PluginOption[]>

Returns the SvelteKit Vite plugins.

sveltekit
} from '@sveltejs/kit/vite';
import { function defineConfig(config: UserConfig): UserConfig (+5 overloads)

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.

defineConfig
} from 'vite';
export default function defineConfig(config: UserConfig): UserConfig (+5 overloads)

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.

defineConfig
({
UserConfig.plugins?: PluginOption[] | undefined

Array of vite plugins to use.

plugins
: [
function sveltekit(options?: {
    adapter?: import("@sveltejs/kit").Adapter;
} | undefined): Promise<PluginOption[]>

Returns the SvelteKit Vite plugins.

sveltekit
({
adapter?: Adapter | undefinedadapter: const svelteConfig: Config
@type
{import('@sveltejs/kit').Config}
svelteConfig
.Config.kit?: KitConfig | undefined

SvelteKit options.

kit
?.KitConfig.adapter?: Adapter | undefined

Your adapter is run when executing vite build. It determines how the output is converted for different platforms.

@default
undefined
adapter
}) ] });

Options

vitePluginOptions

Additional preferences for the Cloudflare Vite environment. See the Cloudflare Vite plugin API documentation for a full list of options.

worker

By default, a Cloudflare Worker is alongside your application. You can turn this off if you intend to only deploy static assets. You may also want to configure your routing to suit a Single Page Application (SPA) or Static Site Generation (SSG) architecture.

Customising your worker

You can customise your worker by creating a new file and specifying the path to it in your Wrangler configuration file.

wrangler
{
	"main": "src/worker.js",
}

Inside your worker file, you can reproduce the SvelteKit request handling behaviour by importing the fetch method from @sveltejs/adapter-cloudflare/worker.

src/worker
import { import fetchfetch } from '@sveltejs/adapter-cloudflare/worker';

export default {
	fetch: anyfetch
	// Add other types of handlers here
}

Deployment

You can use the Wrangler CLI to deploy your application by running npx wrangler deploy or use the Cloudflare Git integration to enable automatic builds and deployments on push.

Runtime APIs

The env object contains your project's bindings, which consist of KV/DO namespaces, etc. It is passed to SvelteKit via the platform property, along with ctx, caches, and cf meaning that you can access it in hooks and endpoints:

+server
/** @type {import('./$types').RequestHandler} */
export async function POST({ request: Request

The original request object.

request
, platform: Readonly<App.Platform> | undefined

Additional data made available through the adapter.

platform
}) {
const const x: DurableObjectId | undefinedx = platform: Readonly<App.Platform> | undefined

Additional data made available through the adapter.

platform
?.
env: {
    YOUR_DURABLE_OBJECT_NAMESPACE: DurableObjectNamespace;
}
env
.type YOUR_DURABLE_OBJECT_NAMESPACE: DurableObjectNamespace<undefined>YOUR_DURABLE_OBJECT_NAMESPACE.DurableObjectNamespace<undefined>.idFromName(name: string): DurableObjectIdidFromName('x');
}
import type { type RequestHandler = (event: RequestEvent<Record<string, any>, string | null>) => MaybePromise<Response>RequestHandler } from './$types';
export const POST: type RequestHandler = (event: RequestEvent<Record<string, any>, string | null>) => MaybePromise<Response>RequestHandler = async ({ request: Request

The original request object.

request
, platform: Readonly<App.Platform> | undefined

Additional data made available through the adapter.

platform
}) => {
const const x: DurableObjectId | undefinedx = platform: Readonly<App.Platform> | undefined

Additional data made available through the adapter.

platform
?.
env: {
    YOUR_DURABLE_OBJECT_NAMESPACE: DurableObjectNamespace;
}
env
.type YOUR_DURABLE_OBJECT_NAMESPACE: DurableObjectNamespace<undefined>YOUR_DURABLE_OBJECT_NAMESPACE.DurableObjectNamespace<undefined>.idFromName(name: string): DurableObjectIdidFromName('x');
};

SvelteKit's built-in $env module should be preferred for environment variables.

After configuring the bindings in your Wrangler configuration file, you can add type-safety by running npx wrangler types and adding the generated types to your tsconfig.json.

tsconfig
{
	"compilerOptions": {
		"types": ["worker-configuration.d.ts"]
	}
}

Finally, add Env to the platform.env property in src/app.d.ts:

src/app.d
declare global {
	namespace App {
		interface interface App.Platform

If your adapter provides platform-specific context via event.platform, you can specify it here.

Platform
{
App.Platform.env: Envenv: Env; } } } export {};

Testing locally

Cloudflare specific values in the platform property are emulated during dev and preview modes through Cloudflare's Vite plugin. Bindings are created based on your Wrangler configuration file and are used to populate platform.env.

Headers and redirects

The _headers and _redirects files, specific to Cloudflare, can be used for static asset responses (like images) by putting them into the project root folder.

However, they will have no effect on responses dynamically rendered by SvelteKit, which should return custom headers or redirect responses from server endpoints or with the handle hook.

Troubleshooting

Node.js compatibility

If you would like to enable Node.js compatibility, you can add the nodejs_compat compatibility flag to your Wrangler configuration file:

wrangler
{
	"compatibility_flags": ["nodejs_compat"]
}

Worker size limits

When deploying your application, the server generated by SvelteKit is bundled into a single file. Wrangler will fail to publish your worker if it exceeds the size limits after minification. You're unlikely to hit this limit usually, but some large libraries can cause this to happen. In that case, you can try to reduce the size of your worker by only importing such libraries on the client side. See the FAQ for more information.

Accessing the file system

You can't use fs in Cloudflare Workers.

Instead, use the read function from $app/server to access your files. It works by fetching the file from the deployed public assets location.

Alternatively, you can prerender the routes in question.

Migrating from Pages

Cloudflare Workers is now preferred over Pages because of its broader feature set. You should follow the official migration guide to redeploy your project to Workers before deleting your Pages project.

Migrating from Workers Sites

Cloudflare no longer recommends using Workers Sites and instead recommends using Workers Static Assets. To migrate, replace @sveltejs/adapter-cloudflare-workers with @sveltejs/adapter-cloudflare and remove all site configuration settings from your Wrangler configuration file, then add the assets.directory and assets.binding configuration settings:

svelte.config.js

svelte.config

import import adapteradapter from '@sveltejs/adapter-cloudflare';

/** @type {import('@sveltejs/kit').Config} */
const 
const config: {
    kit: {
        adapter: any;
    };
}
@type
{import('@sveltejs/kit').Config}
config
= {
kit: {
    adapter: any;
}
kit
: {
adapter: anyadapter: import adapteradapter() } }; export default
const config: {
    kit: {
        adapter: any;
    };
}
@type
{import('@sveltejs/kit').Config}
config
;

wrangler.toml

wrangler
site.bucket = ".cloudflare/public"
assets.directory = ".cloudflare/public"
assets.binding = "ASSETS" # Exclude this if you don't have a `main` key configured.

wrangler.jsonc

wrangler
{
	"site": {
		"bucket": ".cloudflare/public"
	},
	"assets": {
		"directory": ".cloudflare/public",
		"binding": "ASSETS" // Exclude this if you don't have a `main` key configured.
	}
}

Edit this page on GitHub llms.txt