メインコンテンツへスキップ

ルーティング

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)でレンダリングされます。

src/routes/+page
<h1>Hello and welcome to my site!</h1>
<a href="/about">About my site</a>
src/routes/about/+page
<h1>About this site</h1>
<p>TODO...</p>
<a href="/">Home</a>

ページは data プロパティを介して load 関数からデータを受け取ることができます。

src/routes/blog/[slug]/+page
<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 モジュールを追加します

src/routes/blog/[slug]/+page
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.

@paramstatus The HTTP status code. Must be in the range 400-599.
@parambody An object that conforms to the App.Error type. If a string is passed, it will be used as the message property.
@throwsHttpError This error instructs SvelteKit to initiate HTTP error handling.
@throwsError If the provided status is invalid (not between 400 and 599).
error
} from '@sveltejs/kit';
/** @type {import('./$types').PageLoad} */ export function
function load({ params }: {
    params: any;
}): {
    title: string;
    content: string;
}
@type{import('./$types').PageLoad}
load
({ params: anyparams }) {
if (params: anyparams.slug === 'hello-world') { return { title: stringtitle: 'Hello world!', content: stringcontent: '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.

@paramstatus The HTTP status code. Must be in the range 400-599.
@parambody An object that conforms to the App.Error type. If a string is passed, it will be used as the message property.
@throwsHttpError This error instructs SvelteKit to initiate HTTP error handling.
@throwsError If the provided status is invalid (not between 400 and 599).
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.

@paramstatus The HTTP status code. Must be in the range 400-599.
@parambody An object that conforms to the App.Error type. If a string is passed, it will be used as the message property.
@throwsHttpError This error instructs SvelteKit to initiate HTTP error handling.
@throwsError If the provided status is invalid (not between 400 and 599).
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: PageLoadload:
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: stringtitle: 'Hello world!', content: stringcontent: '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.

@paramstatus The HTTP status code. Must be in the range 400-599.
@parambody An object that conforms to the App.Error type. If a string is passed, it will be used as the message property.
@throwsHttpError This error instructs SvelteKit to initiate HTTP error handling.
@throwsError If the provided status is invalid (not between 400 and 599).
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 に変更できます。

src/routes/blog/[slug]/+page.server
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.

@paramstatus The HTTP status code. Must be in the range 400-599.
@parambody An object that conforms to the App.Error type. If a string is passed, it will be used as the message property.
@throwsHttpError This error instructs SvelteKit to initiate HTTP error handling.
@throwsError If the provided status is invalid (not between 400 and 599).
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>>
@type{import('./$types').PageServerLoad}
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.

@paramstatus The HTTP status code. Must be in the range 400-599.
@parambody An object that conforms to the App.Error type. If a string is passed, it will be used as the message property.
@throwsHttpError This error instructs SvelteKit to initiate HTTP error handling.
@throwsError If the provided status is invalid (not between 400 and 599).
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.

@paramstatus The HTTP status code. Must be in the range 400-599.
@parambody An object that conforms to the App.Error type. If a string is passed, it will be used as the message property.
@throwsHttpError This error instructs SvelteKit to initiate HTTP error handling.
@throwsError If the provided status is invalid (not between 400 and 599).
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: PageServerLoadload: 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.

@paramstatus The HTTP status code. Must be in the range 400-599.
@parambody An object that conforms to the App.Error type. If a string is passed, it will be used as the message property.
@throwsHttpError This error instructs SvelteKit to initiate HTTP error handling.
@throwsError If the provided status is invalid (not between 400 and 599).
error
(404, 'Not found');
};

クライアント側のナビゲーション中、SvelteKit はこのデータをサーバーからロードします。つまり、返される値は devalue を使用してシリアライズ可能である必要があります。API の詳細については、load を参照してください。

+page.js と同様に、+page.server.jsページオプションprerenderssrcsr)をエクスポートできます。

+page.server.js ファイルは、アクションをエクスポートすることもできます。load がサーバーからデータを読み取れるようにする場合、actions を使用すると、<form> 要素を使用してサーバーデータを書き込むことができます。使用方法については、フォームアクションのセクションを参照してください。

+error

load 中にエラーが発生した場合、SvelteKit はデフォルトのエラーページをレンダリングします。+error.svelte ファイルを追加することで、ルートごとにこのエラーページをカスタマイズできます

src/routes/blog/[slug]/+error
<script>
	import { page } from '$app/stores';
</script>

<h1>{$page.status}: {$page.error.message}</h1>

SvelteKit は、最も近いエラー境界を探して「ツリーを上方向に移動」します。上のファイルが存在しない場合、src/routes/blog/+error.svelte を試してから、デフォルトのエラーページをレンダリングする前に src/routes/+error.svelte を試します。それが失敗した場合(または、ルート +layoutload 関数からエラーがスローされた場合。これはルート +error の「上」にあります)、SvelteKit は中止して、src/error.html ファイルを作成することでカスタマイズできる静的なフォールバックエラーページをレンダリングします。

エラーが +layout(.server).jsload 関数内で発生した場合、ツリー内の最も近いエラー境界は、そのレイアウトのにある +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 タグが含まれていることです。たとえば、ナビゲーションバーを追加してみましょう

src/routes/+layout
<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 のページを作成する場合...

src/routes/+page
<h1>Home</h1>
src/routes/about/+page
<h1>About</h1>
src/routes/settings/+page
<h1>Settings</h1>

...ナビゲーションは常に表示され、3 つのページ間をクリックすると <h1> のみが置き換えられます。

レイアウトはネストできます。/settings ページが 1 つだけでなく、/settings/profile/settings/notifications のように、共有サブメニューを持つネストされたページがあるとします(実際の例については、github.com/settingsを参照してください)。

/settings より下のページにのみ適用されるレイアウトを作成できます(トップレベルのナビゲーションを持つルートレイアウトを継承しながら)

src/routes/settings/+layout
<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.jsload 関数からデータを取得できます。

src/routes/settings/+layout
/** @type {import('./$types').LayoutLoad} */
export function 
function load(): {
    sections: {
        slug: string;
        title: string;
    }[];
}
@type{import('./$types').LayoutLoad}
load
() {
return {
sections: {
    slug: string;
    title: string;
}[]
sections
: [
{ slug: stringslug: 'profile', title: stringtitle: 'Profile' }, { slug: stringslug: 'notifications', title: stringtitle: '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: LayoutLoadload:
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: stringslug: 'profile', title: stringtitle: 'Profile' }, { slug: stringslug: 'notifications', title: stringtitle: 'Notifications' } ] }; };

+layout.jsページオプションprerenderssrcsr)をエクスポートする場合、それらは子ページのデフォルトとして使用されます。

レイアウトの load 関数から返されたデータは、すべての子ページでも利用できます

src/routes/settings/profile/+page
<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ページオプションprerenderssrcsr)をエクスポートできます。

+server

ページと同様に、+server.js ファイル(「APIルート」または「エンドポイント」と呼ばれることもあります)でルートを定義できます。これにより、応答を完全に制御できます。+server.js ファイルは、RequestEvent 引数を受け取り、Response オブジェクトを返す、GETPOSTPATCHPUTDELETEOPTIONS、および HEAD などの HTTP 動詞に対応する関数をエクスポートします。

たとえば、GET ハンドラーで /api/random-number ルートを作成できます

src/routes/api/random-number/+server
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.

@paramstatus The HTTP status code. Must be in the range 400-599.
@parambody An object that conforms to the App.Error type. If a string is passed, it will be used as the message property.
@throwsHttpError This error instructs SvelteKit to initiate HTTP error handling.
@throwsError If the provided status is invalid (not between 400 and 599).
error
} from '@sveltejs/kit';
/** @type {import('./$types').RequestHandler} */ export function
function GET({ url }: {
    url: any;
}): Response
@type{import('./$types').RequestHandler}
GET
({ url: anyurl }) {
const const min: numbermin =
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: anyurl.searchParams.get('min') ?? '0');
const const max: numbermax =
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: anyurl.searchParams.get('max') ?? '1');
const const d: numberd = const max: numbermax - const min: numbermin; if (function isNaN(number: number): boolean

Returns a Boolean value that indicates whether a value is the reserved value NaN (not a number).

@paramnumber A numeric value.
isNaN
(const d: numberd) || const d: numberd < 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.

@paramstatus The HTTP status code. Must be in the range 400-599.
@parambody An object that conforms to the App.Error type. If a string is passed, it will be used as the message property.
@throwsHttpError This error instructs SvelteKit to initiate HTTP error handling.
@throwsError If the provided status is invalid (not between 400 and 599).
error
(400, 'min and max must be numbers, and min must be less than max');
} const const random: numberrandom = const min: numbermin + 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: numberd;
return new var Response: new (body?: BodyInit | null, init?: ResponseInit) => Response

This Fetch API interface represents the response to a request.

MDN Reference

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: numberrandom));
}
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.

@paramstatus The HTTP status code. Must be in the range 400-599.
@parambody An object that conforms to the App.Error type. If a string is passed, it will be used as the message property.
@throwsHttpError This error instructs SvelteKit to initiate HTTP error handling.
@throwsError If the provided status is invalid (not between 400 and 599).
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: RequestHandlerGET:
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: numbermin =
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: URLSearchParamssearchParams.URLSearchParams.get(name: string): string | null

Returns the first value associated to the given search parameter.

MDN Reference

get
('min') ?? '0');
const const max: numbermax =
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: URLSearchParamssearchParams.URLSearchParams.get(name: string): string | null

Returns the first value associated to the given search parameter.

MDN Reference

get
('max') ?? '1');
const const d: numberd = const max: numbermax - const min: numbermin; if (function isNaN(number: number): boolean

Returns a Boolean value that indicates whether a value is the reserved value NaN (not a number).

@paramnumber A numeric value.
isNaN
(const d: numberd) || const d: numberd < 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.

@paramstatus The HTTP status code. Must be in the range 400-599.
@parambody An object that conforms to the App.Error type. If a string is passed, it will be used as the message property.
@throwsHttpError This error instructs SvelteKit to initiate HTTP error handling.
@throwsError If the provided status is invalid (not between 400 and 599).
error
(400, 'min and max must be numbers, and min must be less than max');
} const const random: numberrandom = const min: numbermin + 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: numberd;
return new var Response: new (body?: BodyInit | null, init?: ResponseInit) => Response

This Fetch API interface represents the response to a request.

MDN Reference

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: numberrandom));
};

Response の最初の引数は、ReadableStream にすることができ、大量のデータをストリーミングしたり、サーバー送信イベントを作成したりできます(AWS Lambda のように応答をバッファリングするプラットフォームにデプロイする場合を除く)。

便宜のため、@sveltejs/kiterrorredirectjson メソッドを使用できます(必須ではありません)。

エラーがスローされた場合(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 を作成できます。

src/routes/add/+page
<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>
src/routes/api/add/+server
import { function json(data: any, init?: ResponseInit | undefined): Response

Create a JSON Response object from the supplied data.

@paramdata The value that will be serialized as JSON.
@paraminit Options such as status and headers that will be added to the response. Content-Type: application/json and Content-Length headers will be added automatically.
json
} from '@sveltejs/kit';
/** @type {import('./$types').RequestHandler} */ export async function
function POST({ request }: {
    request: any;
}): Promise<Response>
@type{import('./$types').RequestHandler}
POST
({ request: anyrequest }) {
const { const a: anya, const b: anyb } = await request: anyrequest.json(); return function json(data: any, init?: ResponseInit | undefined): Response

Create a JSON Response object from the supplied data.

@paramdata The value that will be serialized as JSON.
@paraminit Options such as status and headers that will be added to the response. Content-Type: application/json and Content-Length headers will be added automatically.
json
(const a: anya + const b: anyb);
}
import { function json(data: any, init?: ResponseInit | undefined): Response

Create a JSON Response object from the supplied data.

@paramdata The value that will be serialized as JSON.
@paraminit Options such as status and headers that will be added to the response. Content-Type: application/json and Content-Length headers will be added automatically.
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: RequestHandlerPOST:
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: anya, const b: anyb } = 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.

@paramdata The value that will be serialized as JSON.
@paraminit Options such as status and headers that will be added to the response. Content-Type: application/json and Content-Length headers will be added automatically.
json
(const a: anya + const b: anyb);
};

一般的に、フォームアクションはブラウザからサーバーにデータを送信するより良い方法です。

GET ハンドラーがエクスポートされている場合、HEAD リクエストは GET ハンドラーのレスポンスボディの content-length を返します。

フォールバックメソッドハンドラー

fallback ハンドラーをエクスポートすると、+server.js から専用のエクスポートがない MOVE のようなメソッドを含め、処理されていないリクエストメソッドすべてに一致します。

src/routes/api/add/+server
import { function json(data: any, init?: ResponseInit | undefined): Response

Create a JSON Response object from the supplied data.

@paramdata The value that will be serialized as JSON.
@paraminit Options such as status and headers that will be added to the response. Content-Type: application/json and Content-Length headers will be added automatically.
json
, function text(body: string, init?: ResponseInit | undefined): Response

Create a Response object from the supplied body.

@parambody The value that will be used as-is.
@paraminit Options such as status and headers that will be added to the response. A Content-Length header will be added automatically.
text
} from '@sveltejs/kit';
export async function
function POST({ request }: {
    request: any;
}): Promise<Response>
POST
({ request: anyrequest }) {
const { const a: anya, const b: anyb } = await request: anyrequest.json(); return function json(data: any, init?: ResponseInit | undefined): Response

Create a JSON Response object from the supplied data.

@paramdata The value that will be serialized as JSON.
@paraminit Options such as status and headers that will be added to the response. Content-Type: application/json and Content-Length headers will be added automatically.
json
(const a: anya + const b: anyb);
} // This handler will respond to PUT, PATCH, DELETE, etc. /** @type {import('./$types').RequestHandler} */ export async function
function fallback({ request }: {
    request: any;
}): Promise<Response>
@type{import('./$types').RequestHandler}
fallback
({ request: anyrequest }) {
return function text(body: string, init?: ResponseInit | undefined): Response

Create a Response object from the supplied body.

@parambody The value that will be used as-is.
@paraminit Options such as status and headers that will be added to the response. A Content-Length header will be added automatically.
text
(`I caught your ${request: anyrequest.method} request!`);
}
import { function json(data: any, init?: ResponseInit | undefined): Response

Create a JSON Response object from the supplied data.

@paramdata The value that will be serialized as JSON.
@paraminit Options such as status and headers that will be added to the response. Content-Type: application/json and Content-Length headers will be added automatically.
json
, function text(body: string, init?: ResponseInit | undefined): Response

Create a Response object from the supplied body.

@parambody The value that will be used as-is.
@paraminit Options such as status and headers that will be added to the response. A Content-Length header will be added automatically.
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: anyrequest }) {
const { const a: anya, const b: anyb } = await request: anyrequest.json(); return function json(data: any, init?: ResponseInit | undefined): Response

Create a JSON Response object from the supplied data.

@paramdata The value that will be serialized as JSON.
@paraminit Options such as status and headers that will be added to the response. Content-Type: application/json and Content-Length headers will be added automatically.
json
(const a: anya + const b: anyb);
} // This handler will respond to PUT, PATCH, DELETE, etc. export const const fallback: RequestHandlerfallback:
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.

@parambody The value that will be used as-is.
@paraminit Options such as status and headers that will be added to the response. A Content-Length header will be added automatically.
text
(`I caught your ${request: Request

The original request object

request
.Request.method: string

Returns request’s HTTP method, which is “GET” by default.

MDN Reference

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 に伝えます。

src/routes/blog/[slug]/+page
<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 関数に PageLoadPageServerLoadLayoutLoad、または LayoutServerLoad (+page.js+page.server.js+layout.js、および +layout.server.js 用) を注釈すると、params と戻り値が正しく型付けされることが保証されます。

VS Code または言語サーバープロトコルと TypeScript プラグインをサポートする IDE を使用している場合は、これらの型を完全に省略できます! Svelte の IDE ツールが適切な型を挿入してくれるため、自分で型を記述しなくても型チェックが得られます。これは、コマンドラインツール svelte-check でも機能します。

$types の省略については、ブログ記事で詳しく読むことができます。

その他のファイル

ルートディレクトリ内の他のファイルはすべて SvelteKit によって無視されます。つまり、コンポーネントとユーティリティモジュールを、それらを必要とするルートと同じ場所に配置できます。

コンポーネントとモジュールが複数のルートで必要な場合は、$lib に配置することをお勧めします。

さらに詳しく

GitHub でこのページを編集