ルーティング
SvelteKit の中心にあるのは、ファイルシステムベースのルーターです。アプリのルート(つまり、ユーザーがアクセスできる URL パス)は、コードベース内のディレクトリによって定義されます。
src/routes
はルートルートですsrc/routes/about
は/about
ルートを作成しますsrc/routes/blog/[slug]
は、ユーザーが/blog/hello-world
のようなページをリクエストしたときに動的にデータをロードするために使用できるパラメータであるslug
を持つルートを作成します
プロジェクト設定を編集することで、
src/routes
を別のディレクトリに変更できます。
各ルートディレクトリには、+
プレフィックスで識別できる 1 つ以上のルートファイルが含まれています。
これらのファイルについては後で詳しく説明しますが、SvelteKit のルーティングがどのように機能するかを覚えるのに役立ついくつかの簡単なルールを以下に示します。
- すべてのファイルはサーバー上で実行できます
+server
ファイルを除くすべてのファイルはクライアント上で実行されます+layout
および+error
ファイルは、それらが存在するディレクトリだけでなく、サブディレクトリにも適用されます
+page
+page.svelte
+page.svelte
コンポーネントは、アプリのページを定義します。デフォルトでは、ページは最初の要求に対してサーバー側(SSR)でレンダリングされ、その後のナビゲーションではブラウザ(CSR)でレンダリングされます。
<h1>Hello and welcome to my site!</h1>
<a href="/about">About my site</a>
<h1>About this site</h1>
<p>TODO...</p>
<a href="/">Home</a>
ページは data
プロパティを介して load
関数からデータを受け取ることができます。
<script>
/** @type {{ data: import('./$types').PageData }} */
let { data } = $props();
</script>
<h1>{data.title}</h1>
<div>{@html data.content}</div>
<script lang="ts">
import type { PageData } from './$types';
let { data }: { data: PageData } = $props();
</script>
<h1>{data.title}</h1>
<div>{@html data.content}</div>
レガシーモード
Svelte 4 では、代わりに
export let data
を使用していました
SvelteKit は、フレームワーク固有の
<Link>
コンポーネントではなく、<a>
要素を使用してルート間を移動することに注意してください。
+page.js
多くの場合、ページをレンダリングする前に、いくつかのデータをロードする必要があります。このために、load
関数をエクスポートする +page.js
モジュールを追加します
import { function error(status: number, body: App.Error): never (+1 overload)
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.
error } from '@sveltejs/kit';
/** @type {import('./$types').PageLoad} */
export function function load({ params }: {
params: any;
}): {
title: string;
content: string;
}
load({ params: any
params }) {
if (params: any
params.slug === 'hello-world') {
return {
title: string
title: 'Hello world!',
content: string
content: 'Welcome to our blog. Lorem ipsum dolor sit amet...'
};
}
function error(status: number, body?: {
message: string;
} extends App.Error ? App.Error | string | undefined : never): never (+1 overload)
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.
error(404, 'Not found');
}
import { function error(status: number, body: App.Error): never (+1 overload)
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.
error } from '@sveltejs/kit';
import type { type PageLoad = (event: Kit.LoadEvent<Record<string, any>, Record<string, any> | null, Record<string, any>, string | null>) => MaybePromise<void | Record<string, any>>
type PageLoad = (event: Kit.LoadEvent<Record<string, any>, Record<string, any> | null, Record<string, any>, string | null>) => MaybePromise<void | Record<string, any>>
PageLoad } from './$types';
export const const load: PageLoad
load: type PageLoad = (event: Kit.LoadEvent<Record<string, any>, Record<string, any> | null, Record<string, any>, string | null>) => MaybePromise<void | Record<string, any>>
type PageLoad = (event: Kit.LoadEvent<Record<string, any>, Record<string, any> | null, Record<string, any>, string | null>) => MaybePromise<void | Record<string, any>>
PageLoad = ({ params: Record<string, any>
The parameters of the current page - e.g. for a route like /blog/[slug]
, a { slug: string }
object
params }) => {
if (params: Record<string, any>
The parameters of the current page - e.g. for a route like /blog/[slug]
, a { slug: string }
object
params.slug === 'hello-world') {
return {
title: string
title: 'Hello world!',
content: string
content: 'Welcome to our blog. Lorem ipsum dolor sit amet...'
};
}
function error(status: number, body?: {
message: string;
} extends App.Error ? App.Error | string | undefined : never): never (+1 overload)
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.
error(404, 'Not found');
};
この関数は +page.svelte
と並行して実行されます。つまり、サーバー側レンダリング中はサーバーで実行され、クライアント側のナビゲーション中はブラウザで実行されます。API の詳細については、load
を参照してください。
+page.js
は、load
に加えて、ページの動作を構成する値をエクスポートできます
export const prerender = true
またはfalse
または'auto'
export const ssr = true
またはfalse
export const csr = true
またはfalse
詳細については、ページオプションを参照してください。
+page.server.js
load
関数がサーバーでのみ実行できる場合(たとえば、データベースからデータをフェッチする必要がある場合や、API キーなどのプライベートな環境変数にアクセスする必要がある場合)、+page.js
を +page.server.js
に名前変更し、PageLoad
型を PageServerLoad
に変更できます。
import { function error(status: number, body: App.Error): never (+1 overload)
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.
error } from '@sveltejs/kit';
/** @type {import('./$types').PageServerLoad} */
export async function function load(event: ServerLoadEvent<Record<string, any>, Record<string, any>, string | null>): MaybePromise<void | Record<string, any>>
load({ params: Record<string, any>
The parameters of the current route - e.g. for a route like /blog/[slug]
, a { slug: string }
object
params }) {
const const post: {
title: string;
content: string;
}
post = await const getPostFromDatabase: (slug: string) => {
title: string;
content: string;
}
getPostFromDatabase(params: Record<string, any>
The parameters of the current route - e.g. for a route like /blog/[slug]
, a { slug: string }
object
params.slug);
if (const post: {
title: string;
content: string;
}
post) {
return const post: {
title: string;
content: string;
}
post;
}
function error(status: number, body?: {
message: string;
} extends App.Error ? App.Error | string | undefined : never): never (+1 overload)
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.
error(404, 'Not found');
}
import { function error(status: number, body: App.Error): never (+1 overload)
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.
error } from '@sveltejs/kit';
import type { type PageServerLoad = (event: ServerLoadEvent<Record<string, any>, Record<string, any>, string | null>) => MaybePromise<void | Record<string, any>>
PageServerLoad } from './$types';
export const const load: PageServerLoad
load: type PageServerLoad = (event: ServerLoadEvent<Record<string, any>, Record<string, any>, string | null>) => MaybePromise<void | Record<string, any>>
PageServerLoad = async ({ params: Record<string, any>
The parameters of the current route - e.g. for a route like /blog/[slug]
, a { slug: string }
object
params }) => {
const const post: {
title: string;
content: string;
}
post = await const getPostFromDatabase: (slug: string) => {
title: string;
content: string;
}
getPostFromDatabase(params: Record<string, any>
The parameters of the current route - e.g. for a route like /blog/[slug]
, a { slug: string }
object
params.slug);
if (const post: {
title: string;
content: string;
}
post) {
return const post: {
title: string;
content: string;
}
post;
}
function error(status: number, body?: {
message: string;
} extends App.Error ? App.Error | string | undefined : never): never (+1 overload)
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.
error(404, 'Not found');
};
クライアント側のナビゲーション中、SvelteKit はこのデータをサーバーからロードします。つまり、返される値は devalue を使用してシリアライズ可能である必要があります。API の詳細については、load
を参照してください。
+page.js
と同様に、+page.server.js
は ページオプション(prerender
、ssr
、csr
)をエクスポートできます。
+page.server.js
ファイルは、アクションをエクスポートすることもできます。load
がサーバーからデータを読み取れるようにする場合、actions
を使用すると、<form>
要素を使用してサーバーにデータを書き込むことができます。使用方法については、フォームアクションのセクションを参照してください。
+error
load
中にエラーが発生した場合、SvelteKit はデフォルトのエラーページをレンダリングします。+error.svelte
ファイルを追加することで、ルートごとにこのエラーページをカスタマイズできます
<script>
import { page } from '$app/stores';
</script>
<h1>{$page.status}: {$page.error.message}</h1>
SvelteKit は、最も近いエラー境界を探して「ツリーを上方向に移動」します。上のファイルが存在しない場合、src/routes/blog/+error.svelte
を試してから、デフォルトのエラーページをレンダリングする前に src/routes/+error.svelte
を試します。それが失敗した場合(または、ルート +layout
の load
関数からエラーがスローされた場合。これはルート +error
の「上」にあります)、SvelteKit は中止して、src/error.html
ファイルを作成することでカスタマイズできる静的なフォールバックエラーページをレンダリングします。
エラーが +layout(.server).js
の load
関数内で発生した場合、ツリー内の最も近いエラー境界は、そのレイアウトの上にある +error.svelte
ファイルです(隣ではありません)。
ルートが見つからない場合(404)、src/routes/+error.svelte
(または、そのファイルが存在しない場合はデフォルトのエラーページ)が使用されます。
+error.svelte
は、handle
または +server.js リクエストハンドラー内でエラーが発生した場合、使用されません。
エラー処理の詳細については、こちらを参照してください。
+layout
これまで、ページを完全にスタンドアロンなコンポーネントとして扱ってきました。ナビゲーション時に、既存の +page.svelte
コンポーネントは破棄され、新しいコンポーネントに置き換えられます。
しかし、多くのアプリでは、トップレベルのナビゲーションやフッターなど、すべてのページに表示される要素があります。すべての +page.svelte
で繰り返す代わりに、レイアウトにそれらを配置できます。
+layout.svelte
すべてのページに適用されるレイアウトを作成するには、src/routes/+layout.svelte
というファイルを作成します。デフォルトのレイアウト(独自のレイアウトを使用しない場合に SvelteKit が使用するもの)は、次のようになります...
<script>
let { children } = $props();
</script>
{@render children()}
...ただし、必要なマークアップ、スタイル、および動作を追加できます。唯一の要件は、コンポーネントにページコンテンツの @render
タグが含まれていることです。たとえば、ナビゲーションバーを追加してみましょう
<script>
let { children } = $props();
</script>
<nav>
<a href="/">Home</a>
<a href="/about">About</a>
<a href="/settings">Settings</a>
</nav>
{@render children()}
/
、/about
、および /settings
のページを作成する場合...
<h1>Home</h1>
<h1>About</h1>
<h1>Settings</h1>
...ナビゲーションは常に表示され、3 つのページ間をクリックすると <h1>
のみが置き換えられます。
レイアウトはネストできます。/settings
ページが 1 つだけでなく、/settings/profile
や /settings/notifications
のように、共有サブメニューを持つネストされたページがあるとします(実際の例については、github.com/settingsを参照してください)。
/settings
より下のページにのみ適用されるレイアウトを作成できます(トップレベルのナビゲーションを持つルートレイアウトを継承しながら)
<script>
/** @type {{ data: import('./$types').LayoutData, children: import('svelte').Snippet }} */
let { data, children } = $props();
</script>
<h1>Settings</h1>
<div class="submenu">
{#each data.sections as section}
<a href="/settings/{section.slug}">{section.title}</a>
{/each}
</div>
{@render children()}
<script lang="ts">
import type { LayoutData } from './$types';
import type { Snippet } from 'svelte';
let { data, children }: { data: LayoutData, children: Snippet } = $props();
</script>
<h1>Settings</h1>
<div class="submenu">
{#each data.sections as section}
<a href="/settings/{section.slug}">{section.title}</a>
{/each}
</div>
{@render children()}
data
がどのように設定されるかについては、すぐ下の次のセクションの +layout.js
の例を参照してください。
デフォルトでは、各レイアウトは上にあるレイアウトを継承します。そうでない場合もあります。この場合は、高度なレイアウトが役立ちます。
+layout.js
+page.svelte
が +page.js
からデータをロードするのと同様に、+layout.svelte
コンポーネントは +layout.js
の load
関数からデータを取得できます。
/** @type {import('./$types').LayoutLoad} */
export function function load(): {
sections: {
slug: string;
title: string;
}[];
}
load() {
return {
sections: {
slug: string;
title: string;
}[]
sections: [
{ slug: string
slug: 'profile', title: string
title: 'Profile' },
{ slug: string
slug: 'notifications', title: string
title: 'Notifications' }
]
};
}
import type { type LayoutLoad = (event: Kit.LoadEvent<Record<string, any>, Record<string, any> | null, Record<string, any>, string | null>) => MaybePromise<void | Record<string, any>>
type LayoutLoad = (event: Kit.LoadEvent<Record<string, any>, Record<string, any> | null, Record<string, any>, string | null>) => MaybePromise<void | Record<string, any>>
LayoutLoad } from './$types';
export const const load: LayoutLoad
load: type LayoutLoad = (event: Kit.LoadEvent<Record<string, any>, Record<string, any> | null, Record<string, any>, string | null>) => MaybePromise<void | Record<string, any>>
type LayoutLoad = (event: Kit.LoadEvent<Record<string, any>, Record<string, any> | null, Record<string, any>, string | null>) => MaybePromise<void | Record<string, any>>
LayoutLoad = () => {
return {
sections: {
slug: string;
title: string;
}[]
sections: [
{ slug: string
slug: 'profile', title: string
title: 'Profile' },
{ slug: string
slug: 'notifications', title: string
title: 'Notifications' }
]
};
};
+layout.js
が ページオプション(prerender
、ssr
、csr
)をエクスポートする場合、それらは子ページのデフォルトとして使用されます。
レイアウトの load
関数から返されたデータは、すべての子ページでも利用できます
<script>
/** @type {{ data: import('./$types').PageData }} */
let { data } = $props();
console.log(data.sections); // [{ slug: 'profile', title: 'Profile' }, ...]
</script>
<script lang="ts">
import type { PageData } from './$types';
let { data }: { data: PageData } = $props();
console.log(data.sections); // [{ slug: 'profile', title: 'Profile' }, ...]
</script>
多くの場合、レイアウトデータはページ間を移動しても変更されません。SvelteKit は、必要な場合に
load
関数をインテリジェントに再実行します。
+layout.server.js
レイアウトの load
関数をサーバー上で実行するには、+layout.server.js
に移動し、LayoutLoad
型を LayoutServerLoad
に変更します。
+layout.js
と同様に、+layout.server.js
は ページオプション(prerender
、ssr
、csr
)をエクスポートできます。
+server
ページと同様に、+server.js
ファイル(「APIルート」または「エンドポイント」と呼ばれることもあります)でルートを定義できます。これにより、応答を完全に制御できます。+server.js
ファイルは、RequestEvent
引数を受け取り、Response
オブジェクトを返す、GET
、POST
、PATCH
、PUT
、DELETE
、OPTIONS
、および HEAD
などの HTTP 動詞に対応する関数をエクスポートします。
たとえば、GET
ハンドラーで /api/random-number
ルートを作成できます
import { function error(status: number, body: App.Error): never (+1 overload)
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.
error } from '@sveltejs/kit';
/** @type {import('./$types').RequestHandler} */
export function function GET({ url }: {
url: any;
}): Response
GET({ url: any
url }) {
const const min: number
min = var Number: NumberConstructor
(value?: any) => number
An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers.
Number(url: any
url.searchParams.get('min') ?? '0');
const const max: number
max = var Number: NumberConstructor
(value?: any) => number
An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers.
Number(url: any
url.searchParams.get('max') ?? '1');
const const d: number
d = const max: number
max - const min: number
min;
if (function isNaN(number: number): boolean
Returns a Boolean value that indicates whether a value is the reserved value NaN (not a number).
isNaN(const d: number
d) || const d: number
d < 0) {
function error(status: number, body?: {
message: string;
} extends App.Error ? App.Error | string | undefined : never): never (+1 overload)
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.
error(400, 'min and max must be numbers, and min must be less than max');
}
const const random: number
random = const min: number
min + var Math: Math
An intrinsic object that provides basic mathematics functionality and constants.
Math.Math.random(): number
Returns a pseudorandom number between 0 and 1.
random() * const d: number
d;
return new var Response: new (body?: BodyInit | null, init?: ResponseInit) => Response
This Fetch API interface represents the response to a request.
Response(var String: StringConstructor
(value?: any) => string
Allows manipulation and formatting of text strings and determination and location of substrings within strings.
String(const random: number
random));
}
import { function error(status: number, body: App.Error): never (+1 overload)
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.
error } from '@sveltejs/kit';
import type { type RequestHandler = (event: Kit.RequestEvent<Record<string, any>, string | null>) => MaybePromise<Response>
type RequestHandler = (event: Kit.RequestEvent<Record<string, any>, string | null>) => MaybePromise<Response>
RequestHandler } from './$types';
export const const GET: RequestHandler
GET: type RequestHandler = (event: Kit.RequestEvent<Record<string, any>, string | null>) => MaybePromise<Response>
type RequestHandler = (event: Kit.RequestEvent<Record<string, any>, string | null>) => MaybePromise<Response>
RequestHandler = ({ url: URL
The requested URL.
url }) => {
const const min: number
min = var Number: NumberConstructor
(value?: any) => number
An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers.
Number(url: URL
The requested URL.
url.URL.searchParams: URLSearchParams
searchParams.URLSearchParams.get(name: string): string | null
Returns the first value associated to the given search parameter.
get('min') ?? '0');
const const max: number
max = var Number: NumberConstructor
(value?: any) => number
An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers.
Number(url: URL
The requested URL.
url.URL.searchParams: URLSearchParams
searchParams.URLSearchParams.get(name: string): string | null
Returns the first value associated to the given search parameter.
get('max') ?? '1');
const const d: number
d = const max: number
max - const min: number
min;
if (function isNaN(number: number): boolean
Returns a Boolean value that indicates whether a value is the reserved value NaN (not a number).
isNaN(const d: number
d) || const d: number
d < 0) {
function error(status: number, body?: {
message: string;
} extends App.Error ? App.Error | string | undefined : never): never (+1 overload)
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.
error(400, 'min and max must be numbers, and min must be less than max');
}
const const random: number
random = const min: number
min + var Math: Math
An intrinsic object that provides basic mathematics functionality and constants.
Math.Math.random(): number
Returns a pseudorandom number between 0 and 1.
random() * const d: number
d;
return new var Response: new (body?: BodyInit | null, init?: ResponseInit) => Response
This Fetch API interface represents the response to a request.
Response(var String: StringConstructor
(value?: any) => string
Allows manipulation and formatting of text strings and determination and location of substrings within strings.
String(const random: number
random));
};
Response
の最初の引数は、ReadableStream
にすることができ、大量のデータをストリーミングしたり、サーバー送信イベントを作成したりできます(AWS Lambda のように応答をバッファリングするプラットフォームにデプロイする場合を除く)。
便宜のため、@sveltejs/kit
の error
、redirect
、json
メソッドを使用できます(必須ではありません)。
エラーがスローされた場合(error(...)
または予期しないエラー)、レスポンスはエラーの JSON 表現、またはフォールバックエラーページになります。これは、Accept
ヘッダーに応じて、src/error.html
でカスタマイズできます。この場合、+error.svelte
コンポーネントはレンダリングされません。エラー処理の詳細については、こちらをご覧ください。
OPTIONS
ハンドラーを作成する場合、Vite がAccess-Control-Allow-Origin
およびAccess-Control-Allow-Methods
ヘッダーを挿入することに注意してください。これらは、追加しない限り、本番環境には存在しません。
データの受信
POST
/ PUT
/PATCH
/DELETE
/OPTIONS
/HEAD
ハンドラーをエクスポートすることで、+server.js
ファイルを使用して完全な API を作成できます。
<script>
let a = 0;
let b = 0;
let total = 0;
async function add() {
const response = await fetch('/api/add', {
method: 'POST',
body: JSON.stringify({ a, b }),
headers: {
'content-type': 'application/json'
}
});
total = await response.json();
}
</script>
<input type="number" bind:value={a}> +
<input type="number" bind:value={b}> =
{total}
<button onclick={add}>Calculate</button>
import { function json(data: any, init?: ResponseInit | undefined): Response
Create a JSON Response
object from the supplied data.
json } from '@sveltejs/kit';
/** @type {import('./$types').RequestHandler} */
export async function function POST({ request }: {
request: any;
}): Promise<Response>
POST({ request: any
request }) {
const { const a: any
a, const b: any
b } = await request: any
request.json();
return function json(data: any, init?: ResponseInit | undefined): Response
Create a JSON Response
object from the supplied data.
json(const a: any
a + const b: any
b);
}
import { function json(data: any, init?: ResponseInit | undefined): Response
Create a JSON Response
object from the supplied data.
json } from '@sveltejs/kit';
import type { type RequestHandler = (event: Kit.RequestEvent<Record<string, any>, string | null>) => MaybePromise<Response>
type RequestHandler = (event: Kit.RequestEvent<Record<string, any>, string | null>) => MaybePromise<Response>
RequestHandler } from './$types';
export const const POST: RequestHandler
POST: type RequestHandler = (event: Kit.RequestEvent<Record<string, any>, string | null>) => MaybePromise<Response>
type RequestHandler = (event: Kit.RequestEvent<Record<string, any>, string | null>) => MaybePromise<Response>
RequestHandler = async ({ request: Request
The original request object
request }) => {
const { const a: any
a, const b: any
b } = await request: Request
The original request object
request.Body.json(): Promise<any>
json();
return function json(data: any, init?: ResponseInit | undefined): Response
Create a JSON Response
object from the supplied data.
json(const a: any
a + const b: any
b);
};
一般的に、フォームアクションはブラウザからサーバーにデータを送信するより良い方法です。
GET
ハンドラーがエクスポートされている場合、HEAD
リクエストはGET
ハンドラーのレスポンスボディのcontent-length
を返します。
フォールバックメソッドハンドラー
fallback
ハンドラーをエクスポートすると、+server.js
から専用のエクスポートがない MOVE
のようなメソッドを含め、処理されていないリクエストメソッドすべてに一致します。
import { function json(data: any, init?: ResponseInit | undefined): Response
Create a JSON Response
object from the supplied data.
json, function text(body: string, init?: ResponseInit | undefined): Response
Create a Response
object from the supplied body.
text } from '@sveltejs/kit';
export async function function POST({ request }: {
request: any;
}): Promise<Response>
POST({ request: any
request }) {
const { const a: any
a, const b: any
b } = await request: any
request.json();
return function json(data: any, init?: ResponseInit | undefined): Response
Create a JSON Response
object from the supplied data.
json(const a: any
a + const b: any
b);
}
// This handler will respond to PUT, PATCH, DELETE, etc.
/** @type {import('./$types').RequestHandler} */
export async function function fallback({ request }: {
request: any;
}): Promise<Response>
fallback({ request: any
request }) {
return function text(body: string, init?: ResponseInit | undefined): Response
Create a Response
object from the supplied body.
text(`I caught your ${request: any
request.method} request!`);
}
import { function json(data: any, init?: ResponseInit | undefined): Response
Create a JSON Response
object from the supplied data.
json, function text(body: string, init?: ResponseInit | undefined): Response
Create a Response
object from the supplied body.
text } from '@sveltejs/kit';
import type { type RequestHandler = (event: Kit.RequestEvent<Record<string, any>, string | null>) => MaybePromise<Response>
type RequestHandler = (event: Kit.RequestEvent<Record<string, any>, string | null>) => MaybePromise<Response>
RequestHandler } from './$types';
export async function function POST({ request }: {
request: any;
}): Promise<Response>
POST({ request: any
request }) {
const { const a: any
a, const b: any
b } = await request: any
request.json();
return function json(data: any, init?: ResponseInit | undefined): Response
Create a JSON Response
object from the supplied data.
json(const a: any
a + const b: any
b);
}
// This handler will respond to PUT, PATCH, DELETE, etc.
export const const fallback: RequestHandler
fallback: type RequestHandler = (event: Kit.RequestEvent<Record<string, any>, string | null>) => MaybePromise<Response>
type RequestHandler = (event: Kit.RequestEvent<Record<string, any>, string | null>) => MaybePromise<Response>
RequestHandler = async ({ request: Request
The original request object
request }) => {
return function text(body: string, init?: ResponseInit | undefined): Response
Create a Response
object from the supplied body.
text(`I caught your ${request: Request
The original request object
request.Request.method: string
Returns request’s HTTP method, which is “GET” by default.
method} request!`);
};
HEAD
リクエストの場合、GET
ハンドラーがfallback
ハンドラーよりも優先されます。
コンテンツネゴシエーション
+server.js
ファイルは +page
ファイルと同じディレクトリに配置できるため、同じルートをページまたは API エンドポイントのいずれかにすることができます。どちらであるかを判断するために、SvelteKit は次のルールを適用します。
PUT
/PATCH
/DELETE
/OPTIONS
リクエストは常に+server.js
で処理されます。これはページには適用されないためです。GET
/POST
/HEAD
リクエストは、accept
ヘッダーがtext/html
を優先する場合(つまり、ブラウザのページリクエストの場合)はページリクエストとして扱われ、それ以外の場合は+server.js
で処理されます。GET
リクエストへのレスポンスにはVary: Accept
ヘッダーが含まれます。これにより、プロキシとブラウザは HTML レスポンスと JSON レスポンスを個別にキャッシュします。
$types
上記の例全体を通して、$types.d.ts
ファイルから型をインポートしています。これは、TypeScript (または JSDoc 型注釈付きの JavaScript) を使用している場合、SvelteKit がルートファイルの作業時に型安全性を実現するために、隠しディレクトリに作成するファイルです。
たとえば、let { data } = $props()
に PageData
(または +layout.svelte
ファイルの場合は LayoutData
) を注釈すると、data
の型が load
から返されたものになることを TypeScript に伝えます。
<script>
/** @type {{ data: import('./$types').PageData }} */
let { data } = $props();
</script>
<script lang="ts">
import type { PageData } from './$types';
let { data }: { data: PageData } = $props();
</script>
次に、load
関数に PageLoad
、PageServerLoad
、LayoutLoad
、または LayoutServerLoad
(+page.js
、+page.server.js
、+layout.js
、および +layout.server.js
用) を注釈すると、params
と戻り値が正しく型付けされることが保証されます。
VS Code または言語サーバープロトコルと TypeScript プラグインをサポートする IDE を使用している場合は、これらの型を完全に省略できます! Svelte の IDE ツールが適切な型を挿入してくれるため、自分で型を記述しなくても型チェックが得られます。これは、コマンドラインツール svelte-check
でも機能します。
$types
の省略については、ブログ記事で詳しく読むことができます。
その他のファイル
ルートディレクトリ内の他のファイルはすべて SvelteKit によって無視されます。つまり、コンポーネントとユーティリティモジュールを、それらを必要とするルートと同じ場所に配置できます。
コンポーネントとモジュールが複数のルートで必要な場合は、$lib
に配置することをお勧めします。