` はもう必要ありません。
### src/node_modules
Sapper アプリでよくあるパターンとして、内部ライブラリを `src/node_modules` 内のディレクトリに配置する、というものがあります。これは Vite だと動作しないため、代わりに [`src/lib`]($lib) を使用します。
## ページとレイアウト
### 名前が変わったファイル
ルート(Routes)は曖昧さをなくすためフォルダ名のみで構成されるようになり、`+page.svelte` までのフォルダ名がルート(route)に対応するようになりました。概要は [ルーティングのドキュメント](routing) をご参照ください。以下は 新/旧 の比較です:
| Old | New |
| ------------------------- | ------------------------- |
| routes/about/index.svelte | routes/about/+page.svelte |
| routes/about.svelte | routes/about/+page.svelte |
カスタムのエラーページコンポーネントは `_error.svelte` から `+error.svelte` にリネームしてください。また、どの `_layout.svelte` ファイルも、同様に `+layout.svelte` にリネームしてください。[その他のファイルは無視されます](routing#Other-files).
### Imports
`@sapper/app` からインポートしていた `goto`、`prefetch`、`prefetchRoutes` は、[`$app/navigation`]($app-navigation) からインポートする `goto`、`preloadData`、`preloadCode` にそれぞれ置き換えてください。
`@sapper/app` からインポートしていた `stores` については置き換える必要があります — 以下の [Stores](migrating#Pages-and-layouts-Stores) をご覧ください。
`src/node_modules` にあるディレクトリからインポートしてたファイルは、[`$lib`]($lib) からのインポートに置き換えてください。
### Preload
以前と同様に、ページやレイアウトではレンダリングが行われる前にデータをロードできる関数をエクスポートすることができます。
This function has been renamed from `preload` to [`load`](load), it now lives in a `+page.js` (or `+layout.js`) next to its `+page.svelte` (or `+layout.svelte`), and its API has changed. Instead of two arguments — `page` and `session` — there is a single `event` argument.
There is no more `this` object, and consequently no `this.fetch`, `this.error` or `this.redirect`. Instead, you can get [`fetch`](load#Making-fetch-requests) from the input methods, and both [`error`](load#Errors) and [`redirect`](load#Redirects) are now thrown.
### Stores
Sapper では、提供されるストアをこのように参照していたかと思います:
```js
// @filename: ambient.d.ts
declare module '@sapper/app';
// @filename: index.js
// ---cut---
import { stores } from '@sapper/app';
const { preloading, page, session } = stores();
```
`page` と `session` ストアはまだ存在しています。`preloading` は、`from` プロパティと `to` プロパティを含む `navigating` ストアに置き換えられました。`page` は `url`、`params` を持つようになりましたが、`path` と `query` はありません。
SvelteKit では、それらにアクセスする方法が異なります。`stores` は `getStores` になりましたが、[`$app/stores`]($app-stores) から直接 `navigating`、`page`、`session` をインポートできるので、ほとんどの場合は必要ありません。もしあなたが Svelte 5 と SvelteKit 2.12 以上をお使いなら、代わりに [`$app/state`]($app-state) の使用を検討してみてください。
### ルーティング
ルート(routes) の正規表現はもうサポートされていません。代わりに、[advanced route matching](advanced-routing#Matching) をお使いください。
### Segments
以前までは、レイアウトコンポーネントは子のセグメントを表す `segment` プロパティを受け取っていましたが、この機能は削除されました。より柔軟な `$page.url.pathname` (や `page.url.pathname`) の値を使用し、お望みのセグメントを取得してください。
### URLs
Sapper では、相対 URL は、現在のページに対してではなく、base URL (`basepath` オプションが使用されていない限り、大抵の場合は `/`) に対して解決されていました。
これによって問題が発生していましたが、SvelteKit ではもうそのようなことはありません。相対 URL が現在のページ (または `load` 関数の `fetch` URL の場合は移動先のページ) に対して解決されるようになりました。多くの場合、(例えば、`/` 始まるような) ルート相対な URL を使用するほうが簡単です。なぜなら、それらの意図がコンテキストに依存しないからです。
### <a> attributes
- `sapper:prefetch` は `data-sveltekit-preload-data` になりました
- `sapper:noscroll` は `data-sveltekit-noscroll` になりました
## Endpoints
Sapper では、[サーバールート(server routes)](routing#server) は、Node の `http` モジュール によって公開される `req` と `res` オブジェクト(または Polka や Express などのフレームワークが提供するその拡張版) を受け取っていました。
SvelteKit は、アプリが動作する場所に依存しないように設計されています(Node サーバーで動作し、サーバーレスプラットフォームや Cloudflare Worker でも同様に動作します)。そのため、もう `req` と `res` を直接扱いません。エンドポイントを、新しいシグネチャに合わせて更新する必要があります。
環境非依存な動作をサポートするため、グローバルコンテキストで `fetch` が利用できるようになり、`node-fetch` や `cross-fetch` などのサーバーサイドの fetch 実装をインポートする必要がなくなりました。
## インテグレーション
インテグレーションに関する詳細情報については [インテグレーション](./integrations) をご参照ください。
### HTML minifier
Sapper はデフォルトで `html-minifier` を含んでいました。SvelteKit はこれを含まないのですが、本番環境向けの依存関係(prod dependency)としてこれを追加し、[hook](hooks#Server-hooks-handle) で使用することができます:
```js
// @filename: ambient.d.ts
///
declare module 'html-minifier';
// @filename: index.js
// ---cut---
import { minify } from 'html-minifier';
import { building } from '$app/environment';
const minification_options = {
collapseBooleanAttributes: true,
collapseWhitespace: true,
conservativeCollapse: true,
decodeEntities: true,
html5: true,
ignoreCustomComments: [/^#/],
minifyCSS: true,
minifyJS: false,
removeAttributeQuotes: true,
removeComments: false, // some hydration code needs comments, so leave them in
removeOptionalTags: true,
removeRedundantAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
sortAttributes: true,
sortClassName: true
};
/** @type {import('@sveltejs/kit').Handle} */
export async function handle({ event, resolve }) {
let page = '';
return resolve(event, {
transformPageChunk: ({ html, done }) => {
page += html;
if (done) {
return building ? minify(page, minification_options) : page;
}
}
});
}
```
サイトのプロダクションビルドをテストするのに `vite preview` を使用しているときは、`prerendering` が `false` となることにご注意ください。そのため、minify の結果を検証するには、ビルド済の HTML を直接確認する必要があります。
# Additional resources
## FAQs
よくある問題の解決方法や役に立つ tips や tricks については、[SvelteKit FAQ](faq) をご覧ください。
[Svelte FAQ](../svelte/faq) と [`vite-plugin-svelte` FAQ](https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/faq.md) も、これらのライブラリに起因する疑問点には役立つでしょう。
## Examples
例として、数種類 SvelteKit サイトを作成し、公開しています:
- [`sveltejs/realworld`](https://github.com/sveltejs/realworld) contains an example blog site
- [A HackerNews clone](https://github.com/sveltejs/sites/tree/master/sites/hn.svelte.dev)
- [`svelte.dev`](https://github.com/sveltejs/svelte.dev)
また、SvelteKit ユーザーが GitHub で [#sveltekit](https://github.com/topics/sveltekit) や [#sveltekit-template](https://github.com/topics/sveltekit-template) というトピックを付けて多くの例を公開しており、[Svelte Society のサイト](https://sveltesociety.dev/templates?category=sveltekit) にも例が公開されています。なお、これらはメンテナーによって検証されておらず、最新ではない可能性もありますのでご注意ください。
## サポート
[Discord](/chat) や [StackOverflow](https://stackoverflow.com/questions/tagged/sveltekit) でヘルプを求めることができます。他の方の時間を尊重するため、まずは FAQ、Googleまたは他の検索エンジン、issue tracker、Discord のチャット履歴などから、問題に関連する情報を検索してください。回答する方より質問する方のほうが多いので、こうすることでコミュニティをスケーラブルに発展させることができると思います。
> 日本語翻訳版 追記:上記のDiscordはSvelte本体のもので、英語でコミュニケーションが行われています。もし日本語で質問したり交流したいのであれば、[Svelte日本のDiscord](https://discord.com/invite/YTXq3ZtBbx)にどうぞ!
# Glossary
SvelteKitのコアは、高度に設定可能(configurable)なレンダリングエンジンを提供します。このセクションでは、レンダリングについてディスカッションする際に使用されるいくつかの用語を説明します。これらのオプションを設定するためのリファレンスは、上記のドキュメントで提供されています。
## CSR
クライアントサイドレンダリング(Client-side rendering (CSR))とは、JavaScriptを使用してWebブラウザ上でページコンテンツを生成することです。
SvelteKit では、デフォルトでクライアントサイドレンダリングが使用されますが、[`csr = false` ページオプション](page-options#csr)で JavaScript をオフにすることができます。
## Edge
Rendering on the edge refers to rendering an application in a content delivery network (CDN) near the user. Edge rendering allows the request and response for a page to travel a shorter distance thus improving latency.
## Hybrid app
SvelteKit uses a hybrid rendering mode by default where it loads the initial HTML from the server (SSR), and then updates the page contents on subsequent navigations via client-side rendering (CSR).
## ハイドレーション(Hydration)
Svelte コンポーネントは、何らかの状態を保存し、状態が更新されると DOM を更新します。SSR 中にデータをフェッチするとき、デフォルトでは SvelteKit はこのデータを保存し、サーバーレンダリングされた HTML と一緒にクライアントに送信します。それからコンポーネントは、同じ API エンドポイントを再度呼び出すことなく、クライアント側でそのデータを使用して初期化されます。そして Svelte はハイドレーション(Hydration)と呼ばれるプロセスで DOM が想定通りの状態にあることをチェックしてイベントリスナーをアタッチします。コンポーネントが完全にハイドレートされると、新しく作成された Svelte コンポーネントと同じように、プロパティの変更に反応(react)することができます。
SvelteKit では、デフォルトでページがハイドレーションされますが、[`csr = false` ページオプション](page-options#csr)で JavaScript をオフにすることができます。
## ISR
Incremental static regeneration (ISR) allows you to generate static pages on your site as visitors request those pages without redeploying. This may reduces build times compared to [SSG](#SSG) sites with a large number of pages. You can do [ISR with `adapter-vercel`](adapter-vercel#Incremental-Static-Regeneration).
## MPA
Traditional applications that render each page view on the server — such as those written in languages other than JavaScript — are often referred to as multi-page apps (MPA).
## プリレンダリング
プリレンダリング(Prerendering)とは、ビルド時にページのコンテンツを計算し、表示のために HTML を保存しておくことを意味します。このアプローチは旧来のサーバーレンダリングページと同じ利点を持ちつつ、訪問者ごとにページを再計算する必要がないため、訪問者数の増加に対してほぼ無償でスケールします。トレードオフとしては、ビルドプロセスのコストがより高くなり、プリレンダリングされたコンテンツはアプリケーションの新しいバージョンをデプロイすることでしか更新できなくなります。
全てのページがプリレンダリングできるわけではありません。基本的なルールは次の通りです: コンテンツがプリレンダリング可能であると言うためには、それを直接表示する2人のユーザーが、サーバーから同じコンテンツを取得できなけれならず、かつ、そのページには [actions](form-actions) が含まれていてはいけません。全てのユーザーが同じプリレンダリングコンテンツを見ることができるのであれば、ページのパラメータに基づいてロードされるコンテンツはプリレンダリングが可能である点にご注意ください。
プリレンダリングされるページは静的なコンテンツに限りません。クライアントサイドでユーザ固有のデータをフェッチしてレンダリングする場合は、パーソナライズされたページを構築することができます。ただし、前述の通り、そのコンテンツに対して SSR を行わないことによるデメリットが発生することにご注意ください。
SvelteKit では、[`prerender` ページオプション](page-options#prerender) と、`svelte.config.js` の [`prerender` コンフィグ](configuration#prerender) によってプリレンダリングをコントロールできます。
## PWA
A progressive web app (PWA) is an app that's built using web APIs and technologies, but functions like a mobile or desktop app. Sites served as [PWAs can be installed](https://web.dev/learn/pwa/installation), allowing you to add a shortcut to the application on your launcher, home screen, or start menu. Many PWAs will utilize [service workers](service-workers) to build offline capabilities.
## ルーティング
デフォルトでは、(リンクをクリックしたりブラウザの 進む または 戻る ボタンを使って)新しいページにナビゲートするとき、SvelteKit はナビゲーションをインターセプトし、ブラウザが移動先のページのリクエストをサーバーにリクエストする代わりに、それを処理します。それから SvelteKit は新しいページのコンポーネントをレンダリングし、そのときに順番に必要な API エンドポイントをコールし、クライアントの表示コンテンツを更新します。このような、ナビゲーションが行われる際にそれに応じてクライアント側でページを更新するプロセスのことを、クライアントサイドルーティングと呼びます。
SvelteKit では、デフォルトでクライアントサイドルーティングが使用されますが、[`data-sveltekit-reload`](link-options#data-sveltekit-reload) でこれをスキップすることができます。
## SPA
シングルページアプリ(single-page app (SPA))とは、サーバーへの全てのリクエストで単一のHTMLをロードし、クライアントサイドレンダリングをリクエストされたURLに基づいて行うアプリケーションのことです。全てのナビゲーションはクライアントサイドで(クライアントサイドルーティングと呼ばれるプロセスで)処理され、ページごとのコンテンツは更新されるが共通のレイアウト要素はほとんど更新されません。このサイト全体で、SPAを指すときは、初期リクエストの際に空のシェルを返すという定義を使用しています。初期リクエストで HTML を提供する[ハイブリッドアプリ](#Hybrid-app)と混同しないでください。SPA モードでは、レンダリングが開始される前に2つのネットワークラウンドトリップが必要になるため、パフォーマンスに大きな影響を与えます。SPA モードはパフォーマンスと SEO に大きな悪影響を与えるため、モバイルアプリにラップされる場合など、ごく限られた状況でのみ推奨されます。
SvelteKit では、[`adapter-static` を使って SPA を構築](single-page-apps) することができます。
## SSG
静的サイト生成(Static Site Generation (SSG))とは、全てのページがプリレンダリングされているサイトを指す用語です。サイトを完全にプリレンダリングすることの利点の1つは、SSRを実行するためのサーバーを維持したり費用を払ったりする必要がないことです。一度生成すれば、そのサイトは CDN から提供することができ、"time to first byte" の優れたパフォーマンスにつながります。このデリバリーモデルはしばしば JAMstack と呼ばれます。
SvelteKit では、[`adapter-static`](adapter-static) を使用したり、[`prerender` ページオプション](page-options#prerender) や `svelte.config.js` の [`prerender` コンフィグ](configuration#prerender) で全ページをプリレンダリングするようにしたりすることで SSG を行うことができます。
## SSR
サーバーサイドレンダリング(Server-side rendering (SSR))とは、サーバー上でページコンテンツを生成することです。SSR やプリレンダリングによってサーバーからページコンテンツを返すことは、パフォーマンスと SEO の観点で非常に望ましいです。SPA で必要となる余分なラウンドトリップを回避することでパフォーマンスが大幅に向上し、また、JavaScript が失敗したり無効にされている場合でも、ユーザーがアプリにアクセスできるようになります (実際、JavaScript が動作しない状況は[想像以上に頻繁に発生します](https://kryogenix.org/code/browser/everyonehasjs.html))。一部の検索エンジンはクライアントサイドで動的に生成されたコンテンツをインデックスできますが、その場合でも時間がかかる可能性があります。
SvelteKit では、デフォルトでページがサーバーサイドレンダリングされます。[`ssr` ページオプション](page-options#ssr) で SSR を無効化できます。
# @sveltejs/kit
```js
// @noErrors
import {
Server,
VERSION,
error,
fail,
isActionFailure,
isHttpError,
isRedirect,
json,
normalizeUrl,
redirect,
text
} from '@sveltejs/kit';
```
## Server
```dts
class Server {/*…*/}
```
```dts
constructor(manifest: SSRManifest);
```
```dts
init(options: ServerInitOptions): Promise
;
```
```dts
respond(request: Request, options: RequestOptions): Promise
;
```
## VERSION
```dts
const VERSION: string;
```
## error
Throws an error with a HTTP status code and an optional message.
When called during request handling, this will cause SvelteKit to
return an error response without invoking `handleError`.
Make sure you're not catching the thrown error, which would prevent SvelteKit from handling it.
```dts
function error(status: number, body: App.Error): never;
```
```dts
function error(
status: number,
body?: {
message: string;
} extends App.Error
? App.Error | string | undefined
: never
): never;
```
## fail
Create an `ActionFailure` object. Call when form submission fails.
```dts
function fail(status: number): ActionFailure;
```
```dts
function fail(
status: number,
data: T
): ActionFailure;
```
## isActionFailure
Checks whether this is an action failure thrown by `fail`.
```dts
function isActionFailure(e: unknown): e is ActionFailure;
```
## isHttpError
Checks whether this is an error thrown by `error`.
```dts
function isHttpError(
e: unknown,
status?: T
): e is HttpError_1 & {
status: T extends undefined ? never : T;
};
```
## isRedirect
Checks whether this is a redirect thrown by `redirect`.
```dts
function isRedirect(e: unknown): e is Redirect_1;
```
## json
Create a JSON `Response` object from the supplied data.
```dts
function json(data: any, init?: ResponseInit): Response;
```
## normalizeUrl
Available since 2.18.0
Strips possible SvelteKit-internal suffixes and trailing slashes from the URL pathname.
Returns the normalized URL as well as a method for adding the potential suffix back
based on a new pathname (possibly including search) or URL.
```js
// @errors: 7031
import { normalizeUrl } from '@sveltejs/kit';
const { url, denormalize } = normalizeUrl('/blog/post/__data.json');
console.log(url.pathname); // /blog/post
console.log(denormalize('/blog/post/a')); // /blog/post/a/__data.json
```
```dts
function normalizeUrl(url: URL | string): {
url: URL;
wasNormalized: boolean;
denormalize: (url?: string | URL) => URL;
};
```
## redirect
Redirect a request. When called during request handling, SvelteKit will return a redirect response.
Make sure you're not catching the thrown redirect, which would prevent SvelteKit from handling it.
Most common status codes:
* `303 See Other`: redirect as a GET request (often used after a form POST request)
* `307 Temporary Redirect`: redirect will keep the request method
* `308 Permanent Redirect`: redirect will keep the request method, SEO will be transferred to the new page
[See all redirect status codes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#redirection_messages)
```dts
function redirect(
status:
| 300
| 301
| 302
| 303
| 304
| 305
| 306
| 307
| 308
| ({} & number),
location: string | URL
): never;
```
## text
Create a `Response` object from the supplied body.
```dts
function text(body: string, init?: ResponseInit): Response;
```
## Action
Shape of a form action method that is part of `export const actions = {...}` in `+page.server.js`.
See [form actions](/docs/kit/form-actions) for more information.
```dts
type Action<
Params extends
AppLayoutParams<'/'> = AppLayoutParams<'/'>,
OutputData extends Record
| void = Record<
string,
any
> | void,
RouteId extends AppRouteId | null = AppRouteId | null
> = (
event: RequestEvent
) => MaybePromise;
```
## ActionFailure
```dts
interface ActionFailure
{/*…*/}
```
```dts
status: number;
```
```dts
[uniqueSymbol]: true;
```
## ActionResult
When calling a form action via fetch, the response will be one of these shapes.
```svelte
## Page
The shape of the [`page`](/docs/kit/$app-state#page) reactive object and the [`$page`](/docs/kit/$app-stores) store.
```dts
interface Page<
Params extends
AppLayoutParams<'/'> = AppLayoutParams<'/'>,
RouteId extends AppRouteId | null = AppRouteId | null
> {/*…*/}
```
```dts
url: URL & { pathname: ResolvedPathname };
```
The URL of the current page.
```dts
params: Params;
```
The parameters of the current page - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object.
```dts
route: {/*…*/}
```
Info about the current route.
```dts
id: RouteId;
```
The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]`. It is `null` when no route is matched.
```dts
status: number;
```
HTTP status code of the current page.
```dts
error: App.Error | null;
```
The error object of the current page, if any. Filled from the `handleError` hooks.
```dts
data: App.PageData & Record
;
```
The merged result of all data from all `load` functions on the current page. You can type a common denominator through `App.PageData`.
```dts
state: App.PageState;
```
The page state, which can be manipulated using the [`pushState`](/docs/kit/$app-navigation#pushState) and [`replaceState`](/docs/kit/$app-navigation#replaceState) functions from `$app/navigation`.
```dts
form: any;
```
Filled only after a form submission. See [form actions](/docs/kit/form-actions) for more info.
## ParamMatcher
The shape of a param matcher. See [matching](/docs/kit/advanced-routing#Matching) for more info.
```dts
type ParamMatcher = (param: string) => boolean;
```
## PrerenderOption
```dts
type PrerenderOption = boolean | 'auto';
```
## Redirect
The object returned by the [`redirect`](/docs/kit/@sveltejs-kit#redirect) function.
```dts
interface Redirect {/*…*/}
```
```dts
status: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308;
```
The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#redirection_messages), in the range 300-308.
```dts
location: string;
```
The location to redirect to.
## RemoteCommand
The return value of a remote `command` function. See [Remote functions](/docs/kit/remote-functions#command) for full documentation.
## RemoteForm
The return value of a remote `form` function. See [Remote functions](/docs/kit/remote-functions#form) for full documentation.
## RemoteFormField
Form field accessor type that provides name(), value(), and issues() methods
```dts
type RemoteFormField =
RemoteFormFieldMethods & {
/**
* Returns an object that can be spread onto an input element with the correct type attribute,
* aria-invalid attribute if the field is invalid, and appropriate value/checked property getters/setters.
* @example
* ```svelte
*
*
*
* ```
*/
as>(
...args: AsArgs
): InputElementProps;
};
```
## RemoteFormFieldType
```dts
type RemoteFormFieldType = {
[K in keyof InputTypeMap]: T extends InputTypeMap[K]
? K
: never;
}[keyof InputTypeMap];
```
## RemoteFormFieldValue
```dts
type RemoteFormFieldValue =
| string
| string[]
| number
| boolean
| File
| File[];
```
## RemoteFormInput
```dts
interface RemoteFormInput {/*…*/}
```
```dts
[key: string]: MaybeArray
;
```
## RemoteFormIssue
```dts
interface RemoteFormIssue {/*…*/}
```
```dts
message: string;
```
## RemotePrerenderFunction
The return value of a remote `prerender` function. See [Remote functions](/docs/kit/remote-functions#prerender) for full documentation.
```dts
type RemotePrerenderFunction = (
arg: Input
) => RemoteResource
## RemoteQuery
```dts
type RemoteQuery = RemoteResource & {
/**
* On the client, this function will update the value of the query without re-fetching it.
*
* On the server, this can be called in the context of a `command` or `form` and the specified data will accompany the action response back to the client.
* This prevents SvelteKit needing to refresh all queries on the page in a second server round-trip.
*/
set(value: T): void;
/**
* On the client, this function will re-fetch the query from the server.
*
* On the server, this can be called in the context of a `command` or `form` and the refreshed data will accompany the action response back to the client.
* This prevents SvelteKit needing to refresh all queries on the page in a second server round-trip.
*/
refresh(): Promise;
/**
* Temporarily override the value of a query. This is used with the `updates` method of a [command](https://svelte.dev/docs/kit/remote-functions#command-Updating-queries) or [enhanced form submission](https://svelte.dev/docs/kit/remote-functions#form-enhance) to provide optimistic updates.
*
* ```svelte
*
*
*
* ```
*/
withOverride(
update: (current: Awaited) => Awaited
): RemoteQueryOverride;
};
```
## RemoteQueryFunction
The return value of a remote `query` function. See [Remote functions](/docs/kit/remote-functions#query) for full documentation.
```dts
type RemoteQueryFunction = (
arg: Input
) => RemoteQuery
## RemoteQueryOverride
```dts
interface RemoteQueryOverride {/*…*/}
```
```dts
release(): void;
```
## RemoteResource
```dts
type RemoteResource
= Promise> & {
/** The error in case the query fails. Most often this is a [`HttpError`](https://svelte.dev/docs/kit/@sveltejs-kit#HttpError) but it isn't guaranteed to be. */
get error(): any;
/** `true` before the first result is available and during refreshes */
get loading(): boolean;
} & (
| {
/** The current value of the query. Undefined until `ready` is `true` */
get current(): undefined;
ready: false;
}
| {
/** The current value of the query. Undefined until `ready` is `true` */
get current(): Awaited;
ready: true;
}
);
```
## RequestEvent
```dts
interface RequestEvent<
Params extends
AppLayoutParams<'/'> = AppLayoutParams<'/'>,
RouteId extends AppRouteId | null = AppRouteId | null
> {/*…*/}
```
```dts
cookies: Cookies;
```
Get or set cookies related to the current request
```dts
fetch: typeof fetch;
```
`fetch` is equivalent to the [native `fetch` web API](https://developer.mozilla.org/en-US/docs/Web/API/fetch), with a few additional features:
- It can be used to make credentialed requests on the server, as it inherits the `cookie` and `authorization` headers for the page request.
- It can make relative requests on the server (ordinarily, `fetch` requires a URL with an origin when used in a server context).
- Internal requests (e.g. for `+server.js` routes) go directly to the handler function when running on the server, without the overhead of an HTTP call.
- During server-side rendering, the response will be captured and inlined into the rendered HTML by hooking into the `text` and `json` methods of the `Response` object. Note that headers will _not_ be serialized, unless explicitly included via [`filterSerializedResponseHeaders`](/docs/kit/hooks#Server-hooks-handle)
- During hydration, the response will be read from the HTML, guaranteeing consistency and preventing an additional network request.
You can learn more about making credentialed requests with cookies [here](/docs/kit/load#Cookies).
```dts
getClientAddress: () => string;
```
The client's IP address, set by the adapter.
```dts
locals: App.Locals;
```
Contains custom data that was added to the request within the [`server handle hook`](/docs/kit/hooks#Server-hooks-handle).
```dts
params: Params;
```
The parameters of the current route - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object.
```dts
platform: Readonly
| undefined;
```
Additional data made available through the adapter.
```dts
request: Request;
```
The original request object.
```dts
route: {/*…*/}
```
Info about the current route.
```dts
id: RouteId;
```
The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]`. It is `null` when no route is matched.
```dts
setHeaders: (headers: Record
) => void;
```
If you need to set headers for the response, you can do so using the this method. This is useful if you want the page to be cached, for example:
```js
// @errors: 7031
/// file: src/routes/blog/+page.js
export async function load({ fetch, setHeaders }) {
const url = `https://cms.example.com/articles.json`;
const response = await fetch(url);
setHeaders({
age: response.headers.get('age'),
'cache-control': response.headers.get('cache-control')
});
return response.json();
}
```
Setting the same header multiple times (even in separate `load` functions) is an error — you can only set a given header once.
You cannot add a `set-cookie` header with `setHeaders` — use the [`cookies`](/docs/kit/@sveltejs-kit#Cookies) API instead.
```dts
url: URL;
```
The requested URL.
```dts
isDataRequest: boolean;
```
`true` if the request comes from the client asking for `+page/layout.server.js` data. The `url` property will be stripped of the internal information
related to the data request in this case. Use this property instead if the distinction is important to you.
```dts
isSubRequest: boolean;
```
`true` for `+server.js` calls coming from SvelteKit without the overhead of actually making an HTTP request. This happens when you make same-origin `fetch` requests on the server.
```dts
tracing: {/*…*/}
```
- available since v2.31.0
Access to spans for tracing. If tracing is not enabled, these spans will do nothing.
```dts
enabled: boolean;
```
Whether tracing is enabled.
```dts
root: Span;
```
The root span for the request. This span is named `sveltekit.handle.root`.
```dts
current: Span;
```
The span associated with the current `handle` hook, `load` function, or form action.
```dts
isRemoteRequest: boolean;
```
`true` if the request comes from the client via a remote function. The `url` property will be stripped of the internal information
related to the data request in this case. Use this property instead if the distinction is important to you.
## RequestHandler
A `(event: RequestEvent) => Response` function exported from a `+server.js` file that corresponds to an HTTP verb (`GET`, `PUT`, `PATCH`, etc) and handles requests with that method.
It receives `Params` as the first generic argument, which you can skip by using [generated types](/docs/kit/types#Generated-types) instead.
```dts
type RequestHandler<
Params extends
AppLayoutParams<'/'> = AppLayoutParams<'/'>,
RouteId extends AppRouteId | null = AppRouteId | null
> = (
event: RequestEvent
) => MaybePromise;
```
## Reroute
Available since 2.3.0
The [`reroute`](/docs/kit/hooks#Universal-hooks-reroute) hook allows you to modify the URL before it is used to determine which route to render.
```dts
type Reroute = (event: {
url: URL;
fetch: typeof fetch;
}) => MaybePromise;
```
## ResolveOptions
```dts
interface ResolveOptions {/*…*/}
```
```dts
transformPageChunk?: (input: { html: string; done: boolean }) => MaybePromise
;
```
- `input` the html chunk and the info if this is the last chunk
Applies custom transforms to HTML. If `done` is true, it's the final chunk. Chunks are not guaranteed to be well-formed HTML
(they could include an element's opening tag but not its closing tag, for example)
but they will always be split at sensible boundaries such as `%sveltekit.head%` or layout/page components.
```dts
filterSerializedResponseHeaders?: (name: string, value: string) => boolean;
```
- `name` header name
- `value` header value
Determines which headers should be included in serialized responses when a `load` function loads a resource with `fetch`.
By default, none will be included.
```dts
preload?: (input: { type: 'font' | 'css' | 'js' | 'asset'; path: string }) => boolean;
```
- `input` the type of the file and its path
Determines what should be added to the `` tag to preload it.
By default, `js` and `css` files will be preloaded.
## RouteDefinition
```dts
interface RouteDefinition
{/*…*/}
```
```dts
api: {
methods: Array
;
};
```
```dts
page: {
methods: Array
>;
};
```
```dts
pattern: RegExp;
```
```dts
prerender: PrerenderOption;
```
```dts
segments: RouteSegment[];
```
```dts
methods: Array
;
```
```dts
config: Config;
```
## SSRManifest
```dts
interface SSRManifest {/*…*/}
```
```dts
appDir: string;
```
```dts
appPath: string;
```
```dts
assets: Set
;
```
Static files from `kit.config.files.assets` and the service worker (if any).
```dts
mimeTypes: Record
;
```
```dts
_: {/*…*/}
```
private fields
```dts
client: NonNullable
;
```
```dts
nodes: SSRNodeLoader[];
```
```dts
remotes: Record
Promise>;
```
hashed filename -> import to that file
```dts
routes: SSRRoute[];
```
```dts
prerendered_routes: Set
;
```
```dts
matchers: () => Promise
>;
```
```dts
server_assets: Record
;
```
A `[file]: size` map of all assets imported by server code.
## ServerInit
Available since 2.10.0
The [`init`](/docs/kit/hooks#Shared-hooks-init) will be invoked before the server responds to its first request
```dts
type ServerInit = () => MaybePromise;
```
## ServerInitOptions
```dts
interface ServerInitOptions {/*…*/}
```
```dts
env: Record
;
```
A map of environment variables.
```dts
read?: (file: string) => MaybePromise
;
```
A function that turns an asset filename into a `ReadableStream`. Required for the `read` export from `$app/server` to work.
## ServerLoad
The generic form of `PageServerLoad` and `LayoutServerLoad`. You should import those from `./$types` (see [generated types](/docs/kit/types#Generated-types))
rather than using `ServerLoad` directly.
```dts
type ServerLoad<
Params extends
AppLayoutParams<'/'> = AppLayoutParams<'/'>,
ParentData extends Record
= Record<
string,
any
>,
OutputData extends Record | void = Record<
string,
any
> | void,
RouteId extends AppRouteId | null = AppRouteId | null
> = (
event: ServerLoadEvent
) => MaybePromise;
```
## ServerLoadEvent
```dts
interface ServerLoadEvent<
Params extends
AppLayoutParams<'/'> = AppLayoutParams<'/'>,
ParentData extends Record
= Record<
string,
any
>,
RouteId extends AppRouteId | null = AppRouteId | null
> extends RequestEvent {/*…*/}
```
```dts
parent: () => Promise
;
```
`await parent()` returns data from parent `+layout.server.js` `load` functions.
Be careful not to introduce accidental waterfalls when using `await parent()`. If for example you only want to merge parent data into the returned output, call it _after_ fetching your other data.
```dts
depends: (...deps: string[]) => void;
```
This function declares that the `load` function has a _dependency_ on one or more URLs or custom identifiers, which can subsequently be used with [`invalidate()`](/docs/kit/$app-navigation#invalidate) to cause `load` to rerun.
Most of the time you won't need this, as `fetch` calls `depends` on your behalf — it's only necessary if you're using a custom API client that bypasses `fetch`.
URLs can be absolute or relative to the page being loaded, and must be [encoded](https://developer.mozilla.org/en-US/docs/Glossary/percent-encoding).
Custom identifiers have to be prefixed with one or more lowercase letters followed by a colon to conform to the [URI specification](https://www.rfc-editor.org/rfc/rfc3986.html).
The following example shows how to use `depends` to register a dependency on a custom identifier, which is `invalidate`d after a button click, making the `load` function rerun.
```js
// @errors: 7031
/// file: src/routes/+page.js
let count = 0;
export async function load({ depends }) {
depends('increase:count');
return { count: count++ };
}
```
```html
/// file: src/routes/+page.svelte
{data.count}
```
```dts
untrack:
(fn: () => T) => T;
```
Use this function to opt out of dependency tracking for everything that is synchronously called within the callback. Example:
```js
// @errors: 7031
/// file: src/routes/+page.js
export async function load({ untrack, url }) {
// Untrack url.pathname so that path changes don't trigger a rerun
if (untrack(() => url.pathname === '/')) {
return { message: 'Welcome!' };
}
}
```
```dts
tracing: {/*…*/}
```
- available since v2.31.0
Access to spans for tracing. If tracing is not enabled, these spans will do nothing.
```dts
enabled: boolean;
```
Whether tracing is enabled.
```dts
root: Span;
```
The root span for the request. This span is named `sveltekit.handle.root`.
```dts
current: Span;
```
The span associated with the current server `load` function.
## Snapshot
The type of `export const snapshot` exported from a page or layout component.
```dts
interface Snapshot
{/*…*/}
```
```dts
capture: () => T;
```
```dts
restore: (snapshot: T) => void;
```
## SubmitFunction
```dts
type SubmitFunction<
Success extends
| Record
| undefined = Record,
Failure extends
| Record
| undefined = Record
> = (input: {
action: URL;
formData: FormData;
formElement: HTMLFormElement;
controller: AbortController;
submitter: HTMLElement | null;
cancel: () => void;
}) => MaybePromise<
| void
| ((opts: {
formData: FormData;
formElement: HTMLFormElement;
action: URL;
result: ActionResult;
/**
* Call this to get the default behavior of a form submission response.
* @param options Set `reset: false` if you don't want the `
## Transport
Available since 2.11.0
The [`transport`](/docs/kit/hooks#Universal-hooks-transport) hook allows you to transport custom types across the server/client boundary.
Each transporter has a pair of `encode` and `decode` functions. On the server, `encode` determines whether a value is an instance of the custom type and, if so, returns a non-falsy encoding of the value which can be an object or an array (or `false` otherwise).
In the browser, `decode` turns the encoding back into an instance of the custom type.
```ts
import type { Transport } from '@sveltejs/kit';
declare class MyCustomType {
data: any
}
// hooks.js
export const transport: Transport = {
MyCustomType: {
encode: (value) => value instanceof MyCustomType && [value.data],
decode: ([data]) => new MyCustomType(data)
}
};
```
```dts
type Transport = Record;
```
## Transporter
A member of the [`transport`](/docs/kit/hooks#Universal-hooks-transport) hook.
```dts
interface Transporter<
T = any,
U = Exclude<
any,
false | 0 | '' | null | undefined | typeof NaN
>
> {/*…*/}
```
```dts
encode: (value: T) => false | U;
```
```dts
decode: (data: U) => T;
```
## Private types
The following are referenced by the public types documented above, but cannot be imported directly:
## AdapterEntry
```dts
interface AdapterEntry {/*…*/}
```
```dts
id: string;
```
A string that uniquely identifies an HTTP service (e.g. serverless function) and is used for deduplication.
For example, `/foo/a-[b]` and `/foo/[c]` are different routes, but would both
be represented in a Netlify _redirects file as `/foo/:param`, so they share an ID
```dts
filter(route: RouteDefinition): boolean;
```
A function that compares the candidate route with the current route to determine
if it should be grouped with the current route.
Use cases:
- Fallback pages: `/foo/[c]` is a fallback for `/foo/a-[b]`, and `/[...catchall]` is a fallback for all routes
- Grouping routes that share a common `config`: `/foo` should be deployed to the edge, `/bar` and `/baz` should be deployed to a serverless function
```dts
complete(entry: { generateManifest(opts: { relativePath: string }): string }): MaybePromise
;
```
A function that is invoked once the entry has been created. This is where you
should write the function to the filesystem and generate redirect manifests.
## Csp
```dts
namespace Csp {
type ActionSource = 'strict-dynamic' | 'report-sample';
type BaseSource =
| 'self'
| 'unsafe-eval'
| 'unsafe-hashes'
| 'unsafe-inline'
| 'wasm-unsafe-eval'
| 'none';
type CryptoSource =
`${'nonce' | 'sha256' | 'sha384' | 'sha512'}-${string}`;
type FrameSource =
| HostSource
| SchemeSource
| 'self'
| 'none';
type HostNameScheme = `${string}.${string}` | 'localhost';
type HostSource =
`${HostProtocolSchemes}${HostNameScheme}${PortScheme}`;
type HostProtocolSchemes = `${string}://` | '';
type HttpDelineator = '/' | '?' | '#' | '\\';
type PortScheme = `:${number}` | '' | ':*';
type SchemeSource =
| 'http:'
| 'https:'
| 'data:'
| 'mediastream:'
| 'blob:'
| 'filesystem:';
type Source =
| HostSource
| SchemeSource
| CryptoSource
| BaseSource;
type Sources = Source[];
}
```
## CspDirectives
```dts
interface CspDirectives {/*…*/}
```
```dts
'child-src'?: Csp.Sources;
```
```dts
'default-src'?: Array
;
```
```dts
'frame-src'?: Csp.Sources;
```
```dts
'worker-src'?: Csp.Sources;
```
```dts
'connect-src'?: Csp.Sources;
```
```dts
'font-src'?: Csp.Sources;
```
```dts
'img-src'?: Csp.Sources;
```
```dts
'manifest-src'?: Csp.Sources;
```
```dts
'media-src'?: Csp.Sources;
```
```dts
'object-src'?: Csp.Sources;
```
```dts
'prefetch-src'?: Csp.Sources;
```
```dts
'script-src'?: Array
;
```
```dts
'script-src-elem'?: Csp.Sources;
```
```dts
'script-src-attr'?: Csp.Sources;
```
```dts
'style-src'?: Array
;
```
```dts
'style-src-elem'?: Csp.Sources;
```
```dts
'style-src-attr'?: Csp.Sources;
```
```dts
'base-uri'?: Array
;
```
```dts
sandbox?: Array<
| 'allow-downloads-without-user-activation'
| 'allow-forms'
| 'allow-modals'
| 'allow-orientation-lock'
| 'allow-pointer-lock'
| 'allow-popups'
| 'allow-popups-to-escape-sandbox'
| 'allow-presentation'
| 'allow-same-origin'
| 'allow-scripts'
| 'allow-storage-access-by-user-activation'
| 'allow-top-navigation'
| 'allow-top-navigation-by-user-activation'
>;
```
```dts
'form-action'?: Array
;
```
```dts
'frame-ancestors'?: Array
;
```
```dts
'navigate-to'?: Array
;
```
```dts
'report-uri'?: string[];
```
```dts
'report-to'?: string[];
```
```dts
'require-trusted-types-for'?: Array<'script'>;
```
```dts
'trusted-types'?: Array<'none' | 'allow-duplicates' | '*' | string>;
```
```dts
'upgrade-insecure-requests'?: boolean;
```
```dts
'require-sri-for'?: Array<'script' | 'style' | 'script style'>;
```
```dts
'block-all-mixed-content'?: boolean;
```
```dts
'plugin-types'?: Array<`${string}/${string}` | 'none'>;
```
```dts
referrer?: Array<
| 'no-referrer'
| 'no-referrer-when-downgrade'
| 'origin'
| 'origin-when-cross-origin'
| 'same-origin'
| 'strict-origin'
| 'strict-origin-when-cross-origin'
| 'unsafe-url'
| 'none'
>;
```
## HttpMethod
```dts
type HttpMethod =
| 'GET'
| 'HEAD'
| 'POST'
| 'PUT'
| 'DELETE'
| 'PATCH'
| 'OPTIONS';
```
## Logger
```dts
interface Logger {/*…*/}
```
```dts
(msg: string): void;
```
```dts
success(msg: string): void;
```
```dts
error(msg: string): void;
```
```dts
warn(msg: string): void;
```
```dts
minor(msg: string): void;
```
```dts
info(msg: string): void;
```
## MaybePromise
```dts
type MaybePromise = T | Promise;
```
## PrerenderEntryGeneratorMismatchHandler
```dts
interface PrerenderEntryGeneratorMismatchHandler {/*…*/}
```
```dts
(details: { generatedFromId: string; entry: string; matchedId: string; message: string }): void;
```
## PrerenderEntryGeneratorMismatchHandlerValue
```dts
type PrerenderEntryGeneratorMismatchHandlerValue =
| 'fail'
| 'warn'
| 'ignore'
| PrerenderEntryGeneratorMismatchHandler;
```
## PrerenderHttpErrorHandler
```dts
interface PrerenderHttpErrorHandler {/*…*/}
```
```dts
(details: {
status: number;
path: string;
referrer: string | null;
referenceType: 'linked' | 'fetched';
message: string;
}): void;
```
## PrerenderHttpErrorHandlerValue
```dts
type PrerenderHttpErrorHandlerValue =
| 'fail'
| 'warn'
| 'ignore'
| PrerenderHttpErrorHandler;
```
## PrerenderMap
```dts
type PrerenderMap = Map;
```
## PrerenderMissingIdHandler
```dts
interface PrerenderMissingIdHandler {/*…*/}
```
```dts
(details: { path: string; id: string; referrers: string[]; message: string }): void;
```
## PrerenderMissingIdHandlerValue
```dts
type PrerenderMissingIdHandlerValue =
| 'fail'
| 'warn'
| 'ignore'
| PrerenderMissingIdHandler;
```
## PrerenderOption
```dts
type PrerenderOption = boolean | 'auto';
```
## PrerenderUnseenRoutesHandler
```dts
interface PrerenderUnseenRoutesHandler {/*…*/}
```
```dts
(details: { routes: string[]; message: string }): void;
```
## PrerenderUnseenRoutesHandlerValue
```dts
type PrerenderUnseenRoutesHandlerValue =
| 'fail'
| 'warn'
| 'ignore'
| PrerenderUnseenRoutesHandler;
```
## Prerendered
```dts
interface Prerendered {/*…*/}
```
```dts
pages: Map<
string,
{
/** The location of the .html file relative to the output directory */
file: string;
}
>;
```
A map of `path` to `{ file }` objects, where a path like `/foo` corresponds to `foo.html` and a path like `/bar/` corresponds to `bar/index.html`.
```dts
assets: Map<
string,
{
/** The MIME type of the asset */
type: string;
}
>;
```
A map of `path` to `{ type }` objects.
```dts
redirects: Map<
string,
{
status: number;
location: string;
}
>;
```
A map of redirects encountered during prerendering.
```dts
paths: string[];
```
An array of prerendered paths (without trailing slashes, regardless of the trailingSlash config)
## RequestOptions
```dts
interface RequestOptions {/*…*/}
```
```dts
getClientAddress(): string;
```
```dts
platform?: App.Platform;
```
## RouteSegment
```dts
interface RouteSegment {/*…*/}
```
```dts
content: string;
```
```dts
dynamic: boolean;
```
```dts
rest: boolean;
```
## TrailingSlash
```dts
type TrailingSlash = 'never' | 'always' | 'ignore';
```
# @sveltejs/kit/hooks
```js
// @noErrors
import { sequence } from '@sveltejs/kit/hooks';
```
## sequence
A helper function for sequencing multiple `handle` calls in a middleware-like manner.
The behavior for the `handle` options is as follows:
- `transformPageChunk` is applied in reverse order and merged
- `preload` is applied in forward order, the first option "wins" and no `preload` options after it are called
- `filterSerializedResponseHeaders` behaves the same as `preload`
```js
// @errors: 7031
/// file: src/hooks.server.js
import { sequence } from '@sveltejs/kit/hooks';
/** @type {import('@sveltejs/kit').Handle} */
async function first({ event, resolve }) {
console.log('first pre-processing');
const result = await resolve(event, {
transformPageChunk: ({ html }) => {
// transforms are applied in reverse order
console.log('first transform');
return html;
},
preload: () => {
// this one wins as it's the first defined in the chain
console.log('first preload');
return true;
}
});
console.log('first post-processing');
return result;
}
/** @type {import('@sveltejs/kit').Handle} */
async function second({ event, resolve }) {
console.log('second pre-processing');
const result = await resolve(event, {
transformPageChunk: ({ html }) => {
console.log('second transform');
return html;
},
preload: () => {
console.log('second preload');
return true;
},
filterSerializedResponseHeaders: () => {
// this one wins as it's the first defined in the chain
console.log('second filterSerializedResponseHeaders');
return true;
}
});
console.log('second post-processing');
return result;
}
export const handle = sequence(first, second);
```
The example above would print:
```
first pre-processing
first preload
second pre-processing
second filterSerializedResponseHeaders
second transform
first transform
second post-processing
first post-processing
```
```dts
function sequence(...handlers: Handle[]): Handle;
```
# @sveltejs/kit/node/polyfills
```js
// @noErrors
import { installPolyfills } from '@sveltejs/kit/node/polyfills';
```
## installPolyfills
Make various web APIs available as globals:
- `crypto`
- `File`
```dts
function installPolyfills(): void;
```
# @sveltejs/kit/node
```js
// @noErrors
import {
createReadableStream,
getRequest,
setResponse
} from '@sveltejs/kit/node';
```
## createReadableStream
Available since 2.4.0
Converts a file on disk to a readable stream
```dts
function createReadableStream(file: string): ReadableStream;
```
## getRequest
```dts
function getRequest({
request,
base,
bodySizeLimit
}: {
request: import('http').IncomingMessage;
base: string;
bodySizeLimit?: number;
}): Promise;
```
## setResponse
```dts
function setResponse(
res: import('http').ServerResponse,
response: Response
): Promise;
```
# @sveltejs/kit/vite
```js
// @noErrors
import { sveltekit } from '@sveltejs/kit/vite';
```
## sveltekit
Returns the SvelteKit Vite plugins.
```dts
function sveltekit(): Promise;
```
# $app/environment
```js
// @noErrors
import { browser, building, dev, version } from '$app/environment';
```
## browser
`true` if the app is running in the browser.
```dts
const browser: boolean;
```
## building
SvelteKit analyses your app during the `build` step by running it. During this process, `building` is `true`. This also applies during prerendering.
```dts
const building: boolean;
```
## dev
Whether the dev server is running. This is not guaranteed to correspond to `NODE_ENV` or `MODE`.
```dts
const dev: boolean;
```
## version
The value of `config.kit.version.name`.
```dts
const version: string;
```
# $app/forms
```js
// @noErrors
import { applyAction, deserialize, enhance } from '$app/forms';
```
## applyAction
This action updates the `form` property of the current page with the given data and updates `page.status`.
In case of an error, it redirects to the nearest error page.
```dts
function applyAction<
Success extends Record | undefined,
Failure extends Record | undefined
>(
result: import('@sveltejs/kit').ActionResult<
Success,
Failure
>
): Promise;
```
## deserialize
Use this function to deserialize the response from a form submission.
Usage:
```js
// @errors: 7031
import { deserialize } from '$app/forms';
async function handleSubmit(event) {
const response = await fetch('/form?/action', {
method: 'POST',
body: new FormData(event.target)
});
const result = deserialize(await response.text());
// ...
}
```
```dts
function deserialize<
Success extends Record | undefined,
Failure extends Record | undefined
>(
result: string
): import('@sveltejs/kit').ActionResult;
```
## enhance
This action enhances a `