Skip to main content

Vercel

Vercel にデプロイする場合は、adapter-vercel を使用します。

adapter-auto を使用している場合、この adapter は自動でインストールされますが、この adapter 自体をプロジェクトに追加すれば Vercel 固有のオプションを指定できるようになります。

使い方

npm i -D @sveltejs/adapter-vercel を実行してインストールし、svelte.config.js にこの adapter を追加します:

svelte.config
import function adapter(config?: Config): Adapteradapter from '@sveltejs/adapter-vercel';

/** @type {import('@sveltejs/kit').Config} */
const 
const config: {
    kit: {
        adapter: Adapter;
    };
}
@type{import('@sveltejs/kit').Config}
config
= {
kit: {
    adapter: Adapter;
}
kit
: {
adapter: Adapteradapter: function adapter(config?: Config): Adapteradapter({ // ここで設定できるオプションについては以下を参照 }) } }; export default
const config: {
    kit: {
        adapter: Adapter;
    };
}
@type{import('@sveltejs/kit').Config}
config
;

デプロイメントの設定

Vercel にルート(routes)を function としてデプロイする方法をコントロールするには、デプロイメントの設定を、上記に示すオプションか、+server.js+page(.server).js+layout(.server).js ファイルの中の export const config を使用して、行うことができます。

例えば、アプリの一部を分割して、特定のルート(route)を個別の serverless function としてデプロイすることができます:

about/+page
/** @type {import('@sveltejs/adapter-vercel').Config} */
export const 
const config: {
    split: boolean;
}
@type{import('@sveltejs/adapter-vercel').Config}
config
= {
split: booleansplit: true };
import type { 
type Config = (EdgeConfig | ServerlessConfig) & {
    images?: ImagesConfig;
}
Config
} from '@sveltejs/adapter-vercel';
export const const config: Configconfig:
type Config = (EdgeConfig | ServerlessConfig) & {
    images?: ImagesConfig;
}
Config
= {
split: truesplit: true };

以下のオプションはすべての function に適用されます:

  • runtime: 'edge''nodejs18.x''nodejs20.x''nodejs22.x'。デフォルトでは、adapter はプロジェクトの Node のバージョンに対応した 'nodejs<version>.x' を選択します。プロジェクトの Node バージョンは Vercel のダッシュボードから設定することができます。

    このオプションは非推奨で、将来のバージョンで削除される予定です。その後は、すべての関数は Vercel のプロジェクトの設定で指定された Node バージョンを使用するようになります

  • regions: edge network regions の配列 (serverless functions のデフォルトは ["iad1"]) か、runtimeedge (デフォルト) の場合は 'all' です。serverless functions の場合の複数の regions のサポートは Enterprise Plan のみです。
  • split: true の場合、ルート(route)は個別の function としてデプロイされます。split を adapter レベルで true にする場合、すべてのルート(route)が個別の function としてデプロイされます。

加えて、以下のオプションは edge function に適用されます:

  • external: esbuild が function をバンドルする際に外部(external)として扱う依存関係(dependencies)の配列です。Node の外側で実行されないオプションの依存関係(optional dependencies)を除外したいときにのみ使用してください

そして以下のオプションは serverless function に適用されます:

  • memory: function で利用できるメモリ量です。デフォルトは 1024 Mb で、128 Mb まで減らすことができます。また、Pro または Enterprise アカウントの場合は、3008 Mb まで増やすことができます。間隔は 64Mb 単位です。
  • maxDuration: function の 最大実行時間(maximum execution duration)。デフォルトで、Hobby アカウントの場合は 10 秒、Pro の場合は 15、Enterprise の場合は 900 です。
  • isr: Incremental Static Regeneration の設定、詳細は後述

レイアウトでセットされた設定は、より細かいレベルで上書きされない限り、そのレイアウトの下にあるすべてのルート(route)に適用されます。

function から特定の region のデータにアクセスする必要がある場合は、パフォーマンスを最適化するためそれと同じ region (またはその近く) にデプロイすることをおすすめします。

Image Optimization

You may set the images config to control how Vercel builds your images. See the image configuration reference for full details. As an example, you may set:

svelte.config
import function adapter(config?: Config): Adapteradapter from '@sveltejs/adapter-vercel';

/** @type {import('@sveltejs/kit').Config} */
const 
const config: {
    kit: {
        adapter: Adapter;
    };
}
@type{import('@sveltejs/kit').Config}
config
= {
kit: {
    adapter: Adapter;
}
kit
: {
adapter: Adapteradapter: function adapter(config?: Config): Adapteradapter({ images?: ImagesConfig | undefinedimages: { sizes: number[]sizes: [640, 828, 1200, 1920, 3840], formats?: ImageFormat[] | undefinedformats: ['image/avif', 'image/webp'], minimumCacheTTL?: number | undefinedminimumCacheTTL: 300, domains: string[]domains: ['example-app.vercel.app'], } }) } }; export default
const config: {
    kit: {
        adapter: Adapter;
    };
}
@type{import('@sveltejs/kit').Config}
config
;

Incremental Static Regeneration

Vercel は Incremental Static Regeneration (ISR) をサポートしており、これにより、プリレンダリングコンテンツが持つパフォーマンスとコストの利点と、ダイナミックレンダリングコンテンツが持つ柔軟性の両方を提供することができます。

Use ISR only on routes where every visitor should see the same content (much like when you prerender). If there’s anything user-specific happening (like session cookies), they should happen on the client via JavaScript only to not leak sensitive information across visits

ISR をルート(route)に追加するには、config オブジェクトに isr プロパティを含めます:

import { import BYPASS_TOKENBYPASS_TOKEN } from '$env/static/private';

/** @type {import('@sveltejs/adapter-vercel').Config} */
export const 
const config: {
    isr: {
        expiration: number;
        bypassToken: any;
        allowQuery: string[];
    };
}
@type{import('@sveltejs/adapter-vercel').Config}
config
= {
isr: {
    expiration: number;
    bypassToken: any;
    allowQuery: string[];
}
isr
: {
expiration: numberexpiration: 60, bypassToken: anybypassToken: import BYPASS_TOKENBYPASS_TOKEN, allowQuery: string[]allowQuery: ['search'] } };

Using ISR on a route with export const prerender = true will have no effect, since the route is prerendered at build time

The expiration property is required; all others are optional. The properties are discussed in more detail below.

expiration

The expiration time (in seconds) before the cached asset will be re-generated by invoking the Serverless Function. Setting the value to false means it will never expire. In that case, you likely want to define a bypass token to re-generate on demand.

bypassToken

A random token that can be provided in the URL to bypass the cached version of the asset, by requesting the asset with a __prerender_bypass=<token> cookie.

Making a GET or HEAD request with x-prerender-revalidate: <token> will force the asset to be re-validated.

Note that the BYPASS_TOKEN string must be at least 32 characters long. You could generate one using the JavaScript console like so:

var crypto: Cryptocrypto.Crypto.randomUUID(): `${string}-${string}-${string}-${string}-${string}`

Available only in secure contexts.

MDN Reference

randomUUID
();

Set this string as an environment variable on Vercel by logging in and going to your project then Settings > Environment Variables. For “Key” put BYPASS_TOKEN and for “value” use the string generated above, then hit “Save”.

To get this key known about for local development, you can use the Vercel CLI by running the vercel env pull command locally like so:

vercel env pull .env.development.local

allowQuery

A list of valid query parameters that contribute to the cache key. Other parameters (such as utm tracking codes) will be ignored, ensuring that they do not result in content being re-generated unnecessarily. By default, query parameters are ignored.

Pages that are prerendered will ignore ISR configuration.

環境変数

Vercel ではデプロイメント固有の環境変数一式を使用できます。他の環境変数と同様、$env/static/private$env/dynamic/private からアクセスでき (詳細は後述)、public のほうからはアクセスできません。クライアントからこれらの変数にアクセスするには:

+layout.server
import { import VERCEL_COMMIT_REFVERCEL_COMMIT_REF } from '$env/static/private';

/** @type {import('./$types').LayoutServerLoad} */
export function 
function load(): {
    deploymentGitBranch: any;
}
@type{import('./$types').LayoutServerLoad}
load
() {
return { deploymentGitBranch: anydeploymentGitBranch: import VERCEL_COMMIT_REFVERCEL_COMMIT_REF }; }
import { import VERCEL_COMMIT_REFVERCEL_COMMIT_REF } from '$env/static/private';
import type { 
type LayoutServerLoad = (event: Kit.ServerLoadEvent<Record<string, any>, Record<string, any>, string | null>) => MaybePromise<void | Record<string, any>>
type LayoutServerLoad = (event: Kit.ServerLoadEvent<Record<string, any>, Record<string, any>, string | null>) => MaybePromise<void | Record<string, any>>
LayoutServerLoad
} from './$types';
export const const load: LayoutServerLoadload:
type LayoutServerLoad = (event: Kit.ServerLoadEvent<Record<string, any>, Record<string, any>, string | null>) => MaybePromise<void | Record<string, any>>
type LayoutServerLoad = (event: Kit.ServerLoadEvent<Record<string, any>, Record<string, any>, string | null>) => MaybePromise<void | Record<string, any>>
LayoutServerLoad
= () => {
return { deploymentGitBranch: anydeploymentGitBranch: import VERCEL_COMMIT_REFVERCEL_COMMIT_REF }; };
+layout
<script>
	/** @type {import('./$types').LayoutProps} */
	let { data } = $props();
</script>

<p>This staging environment was deployed from {data.deploymentGitBranch}.</p>
<script lang="ts">
	import type { LayoutProps } from './$types';

	let { data }: LayoutProps = $props();
</script>

<p>This staging environment was deployed from {data.deploymentGitBranch}.</p>

Vercel でビルドする場合、これらの変数は全てビルド時と実行時で変わらないため、$env/dynamic/private ではなく、変数を静的に置換しデッドコードの削除などの最適化ができる $env/static/private の使用をおすすめします。

Skew protection

When a new version of your app is deployed, assets belonging to the previous version may no longer be accessible. If a user is actively using your app when this happens, it can cause errors when they navigate — this is known as version skew. SvelteKit mitigates this by detecting errors resulting from version skew and causing a hard reload to get the latest version of the app, but this will cause any client-side state to be lost. (You can also proactively mitigate it by observing updated.current from $app/state, which tells clients when a new version has been deployed.)

Skew protection is a Vercel feature that routes client requests to their original deployment. When a user visits your app, a cookie is set with the deployment ID, and any subsequent requests will be routed to that deployment for as long as skew protection is active. When they reload the page, they will get the newest deployment. (updated.current is exempted from this behaviour, and so will continue to report new deployments.) To enable it, visit the Advanced section of your project settings on Vercel.

Cookie-based skew protection comes with one caveat: if a user has multiple versions of your app open in multiple tabs, requests from older versions will be routed to the newer one, meaning they will fall back to SvelteKit’s built-in skew protection.

Notes

Vercel functions

プロジェクトの root の api ディレクトリに Vercel functions がある場合、/api/* に対するリクエストは SvelteKit で処理されません。Vercel functions に JavaScript 以外の言語を使用する必要が無いのであれば、SvelteKit アプリの API ルート(routes) として実装すると良いでしょう。逆に Vercel functions に JavaScript 以外の言語を使用する必要がある場合は、SvelteKit アプリに /api/* ルート(routes)を含めないようにしてください。

Node version

ある時期より前に作成されたプロジェクトは、SvelteKit に必要な Node バージョンより古い Node バージョンを使用しているかもしれません。プロジェクトの設定で Node のバージョンを変更することができます。

トラブルシューティング

ファイルシステムにアクセスする

edge functions では fs を使用することはできません。

serverless functions では fs を使用できますが、ファイルがプロジェクトからデプロイメントにコピーされないため、期待通りには動作しないでしょう。代わりに $app/serverread 関数を使用してファイルにアクセスしてください。この関数は、edge functions としてデプロイされたルート(route)の内側でも、デプロイされたパブリックアセットのロケーションからファイルを読み込むことで動作します。

あるいは、対象のルート(route)をプリレンダリングすることもできます。

Deployment protection

If using read in an edge function, SvelteKit will fetch the file in question from your deployment. If you are using Deployment Protection, you must also enable Protection Bypass for Automation so that the request does not result in a 401 Unauthorized response.

Edit this page on GitHub llms.txt