Web standards
このドキュメントを通じて、SvelteKit の土台となっている標準の Web API を参照することができます。私たちは車輪の再発明をするのではなく、プラットフォームを使用します 。つまり、既存の Web 開発スキルが SvelteKit にも活用できるということです。逆に言えば、SvelteKit の学習に時間を割くことは、あなたが他の場所でも通用する良い Web 開発者になるのに役立つでしょう。
これらの API は、全てのモダンブラウザはもちろん、Cloudflare Workers、Deno、Vercel Edge Functions といったブラウザ以外の環境でも使用することができます。開発中や、(AWS Lambda を含む) Node ベースの環境向けの adapters では、必要に応じて polyfill で利用できるようにしています (現時点においては。Node は急速により多くの Web 標準のサポートを追加しています)。
具体的には、以下のことが楽にできるでしょう:
Fetch APIs
SvelteKit は、ネットワーク越しにデータを取得するために fetch
を使用します。ブラウザだけでなく、hooks や サーバールート(server routes) の中でも使用することができます。
load
関数、server hooks、API routes の中では特別なバージョンのfetch
を使用することができ、サーバーサイドレンダリング中に、HTTP をコールすることなく、クレデンシャルを保持したまま、直接エンドポイント(endpoints)を呼び出すことができます。(load
の外側のサーバーサイドコードでクレデンシャル付きの fetch を行う場合は、明示的にcookie
やauthorization
ヘッダーなどを渡さなければなりません。) また、通常のサーバーサイドのfetch
では絶対パスの URL が必要となりますが、特別なバージョンのfetch
では相対パスのリクエストが可能です。
fetch
自体の他に、Fetch API には以下のインターフェイスが含まれています:
Request
Request
のインスタンスは hooks や サーバールート(server routes) で event.request
という形でアクセスすることができます。これには request.json()
や request.formData()
など、エンドポイントに送られたデータを取得するための便利なメソッドが含まれています。
Response
Response
のインスタンスは await fetch(...)
と +server.js
ファイル内のハンドラーから返されます。本質的には、SvelteKit アプリは Request
を Response
に変換するマシンです。
Headers
Headers
インターフェイスでは、受け取った request.headers
を読み取り、送信する response.headers
をセットすることができます。例えば以下のように、request.headers
を取得して、json
という便利な関数を使用して response.headers
を変更し送信することができます:
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 function function GET({ request }: {
request: any;
}): Response
GET({ request: any
request }) {
// log all headers
var console: Console
The console
module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
- A
Console
class with methods such as console.log()
, console.error()
and console.warn()
that can be used to write to any Node.js stream.
- A global
console
instance configured to write to process.stdout
and
process.stderr
. The global console
can be used without calling require('console')
.
Warning: The global console object’s methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the note on process I/O
for
more information.
Example using the global console
:
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console
class:
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
console.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to stdout
with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to printf(3)
(the arguments are all passed to util.format()
).
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
See util.format()
for more information.
log(...request: any
request.headers);
// create a JSON Response using a header we received
return function json(data: any, init?: ResponseInit | undefined): Response
Create a JSON Response
object from the supplied data.
json({
// retrieve a specific header
userAgent: any
userAgent: request: any
request.headers.get('user-agent')
}, {
// set a header on the response
ResponseInit.headers?: HeadersInit | undefined
headers: { 'x-custom-header': 'potato' }
});
}
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 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 = ({ request: Request
The original request object
request }) => {
// log all headers
var console: Console
The console
module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
- A
Console
class with methods such as console.log()
, console.error()
and console.warn()
that can be used to write to any Node.js stream.
- A global
console
instance configured to write to process.stdout
and
process.stderr
. The global console
can be used without calling require('console')
.
Warning: The global console object’s methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the note on process I/O
for
more information.
Example using the global console
:
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console
class:
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
console.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to stdout
with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to printf(3)
(the arguments are all passed to util.format()
).
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
See util.format()
for more information.
log(...request: Request
The original request object
request.Request.headers: Headers
Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the “Host” header.
headers);
// create a JSON Response using a header we received
return function json(data: any, init?: ResponseInit | undefined): Response
Create a JSON Response
object from the supplied data.
json({
// retrieve a specific header
userAgent: string | null
userAgent: request: Request
The original request object
request.Request.headers: Headers
Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the “Host” header.
headers.Headers.get(name: string): string | null
get('user-agent')
}, {
// set a header on the response
ResponseInit.headers?: HeadersInit | undefined
headers: { 'x-custom-header': 'potato' }
});
};
FormData
HTML のネイティブのフォーム送信を扱う場合は、FormData
オブジェクトを使用します。
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(event: any): Promise<Response>
POST(event: any
event) {
const const body: any
body = await event: any
event.request.formData();
// log all fields
var console: Console
The console
module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
- A
Console
class with methods such as console.log()
, console.error()
and console.warn()
that can be used to write to any Node.js stream.
- A global
console
instance configured to write to process.stdout
and
process.stderr
. The global console
can be used without calling require('console')
.
Warning: The global console object’s methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the note on process I/O
for
more information.
Example using the global console
:
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console
class:
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
console.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to stdout
with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to printf(3)
(the arguments are all passed to util.format()
).
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
See util.format()
for more information.
log([...const body: any
body]);
return function json(data: any, init?: ResponseInit | undefined): Response
Create a JSON Response
object from the supplied data.
json({
// get a specific field's value
name: any
name: const body: any
body.get('name') ?? 'world'
});
}
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 (event: Kit.RequestEvent<Record<string, any>, string | null>
event) => {
const const body: FormData
body = await event: Kit.RequestEvent<Record<string, any>, string | null>
event.RequestEvent<Record<string, any>, string | null>.request: Request
The original request object
request.Body.formData(): Promise<FormData>
formData();
// log all fields
var console: Console
The console
module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
- A
Console
class with methods such as console.log()
, console.error()
and console.warn()
that can be used to write to any Node.js stream.
- A global
console
instance configured to write to process.stdout
and
process.stderr
. The global console
can be used without calling require('console')
.
Warning: The global console object’s methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the note on process I/O
for
more information.
Example using the global console
:
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console
class:
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
console.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to stdout
with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to printf(3)
(the arguments are all passed to util.format()
).
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
See util.format()
for more information.
log([...const body: FormData
body]);
return function json(data: any, init?: ResponseInit | undefined): Response
Create a JSON Response
object from the supplied data.
json({
// get a specific field's value
name: FormDataEntryValue
name: const body: FormData
body.FormData.get(name: string): FormDataEntryValue | null
get('name') ?? 'world'
});
};
Stream APIs
ほとんどの場合、エンドポイント(endpoints) は 上記の userAgent
の例のように、完全なデータを返します。たまに、1度ではメモリに収まらない大きすぎるレスポンスを返したり、チャンクで配信したりしなければならないことがあります。このような場合のために、プラットフォームは streams — ReadableStream、WritableStream、TransformStream を提供しています。
URL APIs
URL は URL
インターフェイスで表現され、origin
や pathname
のような便利なプロパティが含まれています (ブラウザでは hash
なども)。このインターフェイスは、hooks と サーバールート(server routes) では event.url
、ページ(pages) では $page.url
、beforeNavigate
と afterNavigate
では from
と to
、など、様々な場所で使われています。
URLSearchParams
URL が存在する場所であれば、URLSearchParams
のインスタンスである url.searchParams
を使用してクエリパラメータにアクセスできます:
const const foo: string | null
foo = const url: URL
url.URL.searchParams: URLSearchParams
searchParams.URLSearchParams.get(name: string): string | null
Returns the first value associated to the given search parameter.
get('foo');
Web Crypto
Web Crypto API を、グローバルの crypto
経由で使用することができます。内部では Content Security Policy ヘッダーで使用されていますが、例えば UUID を生成するのにもお使い頂けます。
const const uuid: `${string}-${string}-${string}-${string}-${string}`
uuid = var crypto: Crypto
crypto.Crypto.randomUUID(): `${string}-${string}-${string}-${string}-${string}`
Available only in secure contexts.
randomUUID();