Vercel にデプロイする場合は、[`adapter-vercel`](https://github.com/sveltejs/kit/tree/main/packages/adapter-vercel) を使用します。 [`adapter-auto`](adapter-auto) を使用している場合、この adapter は自動でインストールされますが、この adapter 自体をプロジェクトに追加すれば Vercel 固有のオプションを指定できるようになります。 ## 使い方 `npm i -D @sveltejs/adapter-vercel` を実行してインストールし、`svelte.config.js` にこの adapter を追加します: ```js /// file: svelte.config.js import adapter from '@sveltejs/adapter-vercel'; /** @type {import('@sveltejs/kit').Config} */ const config = { kit: { adapter: adapter({ // ここで設定できるオプションについては以下を参照 }) } }; export default config; ``` ## デプロイメントの設定 Vercel にルート(routes)を function としてデプロイする方法をコントロールするには、デプロイメントの設定を、上記に示すオプションか、`+server.js`、`+page(.server).js`、`+layout(.server).js` ファイルの中の [`export const config`](page-options#config) を使用して、行うことができます。 例えば、アプリの一部を分割して、特定のルート(route)を個別の serverless function としてデプロイすることができます: ```js /// file: about/+page.js /** @type {import('@sveltejs/adapter-vercel').Config} */ export const config = { split: true }; ``` 以下のオプションはすべての function に適用されます: - `runtime`: `'edge'`、`'nodejs18.x'`、`'nodejs20.x'`、`'nodejs22.x'`。デフォルトでは、adapter はプロジェクトの Node のバージョンに対応した `'nodejs.x'` を選択します。プロジェクトの Node バージョンは Vercel のダッシュボードから設定することができます。 > [!NOTE] このオプションは非推奨で、将来のバージョンで削除される予定です。その後は、すべての関数は Vercel のプロジェクトの設定で指定された Node バージョンを使用するようになります - `regions`: [edge network regions](https://vercel.com/docs/concepts/edge-network/regions) の配列 (serverless functions のデフォルトは `["iad1"]`) か、`runtime` が `edge` (デフォルト) の場合は `'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 まで[増やす](https://vercel.com/docs/concepts/limits/overview#serverless-function-memory)ことができます。間隔は 64Mb 単位です。 - `maxDuration`: function の [最大実行時間(maximum execution duration)](https://vercel.com/docs/functions/runtimes#max-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](https://vercel.com/docs/build-output-api/v3/configuration#images) for full details. As an example, you may set: ```js /// file: svelte.config.js import adapter from '@sveltejs/adapter-vercel'; /** @type {import('@sveltejs/kit').Config} */ const config = { kit: { adapter: adapter({ images: { sizes: [640, 828, 1200, 1920, 3840], formats: ['image/avif', 'image/webp'], minimumCacheTTL: 300, domains: ['example-app.vercel.app'], } }) } }; export default config; ``` ## Incremental Static Regeneration Vercel は [Incremental Static Regeneration](https://vercel.com/docs/incremental-static-regeneration) (ISR) をサポートしており、これにより、プリレンダリングコンテンツが持つパフォーマンスとコストの利点と、ダイナミックレンダリングコンテンツが持つ柔軟性の両方を提供することができます。 > [!NOTE] 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` プロパティを含めます: ```js import { BYPASS_TOKEN } from '$env/static/private'; /** @type {import('@sveltejs/adapter-vercel').Config} */ export const config = { isr: { expiration: 60, bypassToken: BYPASS_TOKEN, allowQuery: ['search'] } }; ``` > [!NOTE] 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=` cookie. Making a `GET` or `HEAD` request with `x-prerender-revalidate: ` 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: ```js crypto.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](https://vercel.com/docs/cli/env) by running the `vercel env pull` command locally like so: ```sh 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. > [!NOTE] Pages that are [prerendered](page-options#prerender) will ignore ISR configuration. ## 環境変数 Vercel では[デプロイメント固有の環境変数](https://vercel.com/docs/concepts/projects/environment-variables#system-environment-variables)一式を使用できます。他の環境変数と同様、`$env/static/private` と `$env/dynamic/private` からアクセスでき (詳細は後述)、public のほうからはアクセスできません。クライアントからこれらの変数にアクセスするには: ```js /// file: +layout.server.js import { VERCEL_COMMIT_REF } from '$env/static/private'; /** @type {import('./$types').LayoutServerLoad} */ export function load() { return { deploymentGitBranch: VERCEL_COMMIT_REF }; } ``` ```svelte

This staging environment was deployed from {data.deploymentGitBranch}.

``` 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`]($app-state#updated) from `$app/state`, which tells clients when a new version has been deployed.) [Skew protection](https://vercel.com/docs/deployments/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)](routing#server) として実装すると良いでしょう。逆に Vercel functions に JavaScript 以外の言語を使用する必要がある場合は、SvelteKit アプリに `/api/*` ルート(routes)を含めないようにしてください。 ### Node version ある時期より前に作成されたプロジェクトは、SvelteKit に必要な Node バージョンより古い Node バージョンを使用しているかもしれません。[プロジェクトの設定で Node のバージョンを変更する](https://vercel.com/docs/concepts/functions/serverless-functions/runtimes/node-js#node.js-version)ことができます。 ## トラブルシューティング ### ファイルシステムにアクセスする edge functions では `fs` を使用することはできません。 serverless functions では `fs` を使用できますが、ファイルがプロジェクトからデプロイメントにコピーされないため、期待通りには動作しないでしょう。代わりに `$app/server` の [`read`]($app-server#read) 関数を使用してファイルにアクセスしてください。この関数は、edge functions としてデプロイされたルート(route)の内側でも、デプロイされたパブリックアセットのロケーションからファイルを読み込むことで動作します。 あるいは、対象のルート(route)を[プリレンダリング](page-options#prerender)することもできます。 ### Deployment protection If using [`read`]($app-server#read) in an edge function, SvelteKit will `fetch` the file in question from your deployment. If you are using [Deployment Protection](https://vercel.com/docs/deployment-protection), you must also enable [Protection Bypass for Automation](https://vercel.com/docs/deployment-protection/methods-to-bypass-deployment-protection/protection-bypass-automation) so that the request does not result in a [401 Unauthorized](https://http.dog/401) response.