@sveltejs/kit
import {
class ServerServer,
const VERSION: stringVERSION,
function error(status: {
status: number;
message: string;
} extends App.Error ? number : never, message?: string | undefined): never (+2 overloads)
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; the error will be passed to handleError as an expected error.
Make sure you're not catching the thrown error, which would prevent SvelteKit from handling it.
error,
function fail(status: number): ActionFailure<undefined> (+1 overload)Create an ActionFailure object. Call when form submission fails.
fail,
function invalid(...issues: (StandardSchemaV1<Input = unknown, Output = Input>.Issue | string)[]): neverUse this to throw a validation error to imperatively fail form validation.
Can be used in combination with issue passed to form actions to create field-specific issues.
invalid,
function isActionFailure(e: unknown): e is ActionFailureChecks whether this is an action failure thrown by
{@link
fail
}
.
isActionFailure,
function isHttpError<T extends number>(e: unknown, status?: T): e is (HttpError & {
status: T extends undefined ? never : T;
})
Checks whether this is an error thrown by
{@link
error
}
.
isHttpError,
function isRedirect(e: unknown): e is RedirectChecks whether this is a redirect thrown by
{@link
redirect
}
.
isRedirect,
function isValidationError(e: unknown): e is import("$app/server").ValidationErrorChecks whether this is an validation error thrown by
{@link
invalid
}
.
isValidationError,
function json(data: any, init?: ResponseInit): ResponseCreate a JSON Response object from the supplied data.
json,
function normalizeUrl(url: URL | string): {
url: URL;
wasNormalized: boolean;
denormalize: (url?: string | URL) => URL;
}
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.
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
normalizeUrl,
function redirect(status: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | ({} & number), location: string | URL, options?: {
external?: boolean | string[];
}): never
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
redirect,
function text(body: string, init?: ResponseInit): ResponseCreate a Response object from the supplied body.
text
} from '@sveltejs/kit';Server
class Server {…}constructor(manifest: SSRManifest);init(options: ServerInitOptions): Promise<void>;respond(request: Request, options: RequestOptions): Promise<Response>;VERSION
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; the error will be passed to handleError as an expected error.
Make sure you're not catching the thrown error, which would prevent SvelteKit from handling it.
function error(
status: {
status: number;
message: string;
} extends App.Error
? number
: never,
message?: string | undefined
): never;function error(
status: number,
message: string,
properties: keyof Omit<
App.Error,
'status' | 'message'
> extends never
? never
: Omit<App.Error, 'status' | 'message'>
): never;function error(
status: number,
properties: Omit<App.Error, 'status'> & {
status?: App.Error['status'];
}
): never;fail
Create an ActionFailure object. Call when form submission fails.
function fail(status: number): ActionFailure<undefined>;function fail<T = undefined>(
status: number,
data: T
): ActionFailure<T>;invalid
Available since 2.47.3
Use this to throw a validation error to imperatively fail form validation.
Can be used in combination with issue passed to form actions to create field-specific issues.
import { function invalid(...issues: (StandardSchemaV1<Input = unknown, Output = Input>.Issue | string)[]): neverUse this to throw a validation error to imperatively fail form validation.
Can be used in combination with issue passed to form actions to create field-specific issues.
invalid } from '@sveltejs/kit';
import { function form<Output>(fn: () => MaybePromise<Output>): RemoteForm<void, Output> (+2 overloads)Creates a form object that can be spread onto a <form> element.
See Remote functions for full documentation.
form } from '$app/server';
import { import tryLogintryLogin } from '#lib/server/auth';
import * as import vv from 'valibot';
export const const login: RemoteForm<{
name: string;
_password: string;
}, void>
login = form<v.ObjectSchema<{
readonly name: v.StringSchema<undefined>;
readonly _password: v.StringSchema<undefined>;
}, undefined>, void>(validate: v.ObjectSchema<{
readonly name: v.StringSchema<undefined>;
readonly _password: v.StringSchema<undefined>;
}, undefined>, fn: (data: {
name: string;
_password: string;
}, issue: {
name: (message: string) => StandardSchemaV1<Input = unknown, Output = Input>.Issue;
_password: (message: string) => StandardSchemaV1<Input = unknown, Output = Input>.Issue;
} & ((message: string) => StandardSchemaV1<Input = unknown, Output = Input>.Issue)) => MaybePromise<...>): RemoteForm<...> (+2 overloads)
Creates a form object that can be spread onto a <form> element.
See Remote functions for full documentation.
form(
import vv.object<{
readonly name: v.StringSchema<undefined>;
readonly _password: v.StringSchema<undefined>;
}>(entries: {
readonly name: v.StringSchema<undefined>;
readonly _password: v.StringSchema<undefined>;
}): v.ObjectSchema<{
readonly name: v.StringSchema<undefined>;
readonly _password: v.StringSchema<undefined>;
}, undefined> (+1 overload)
export object
Creates an object schema.
Hint: This schema removes unknown entries. The output will only include the
entries you specify. To include unknown entries, use looseObject. To
return an issue for unknown entries, use strictObject. To include and
validate unknown entries, use objectWithRest.
object({ name: v.StringSchema<undefined>name: import vv.function string(): v.StringSchema<undefined> (+1 overload)
export string
Creates a string schema.
string(), _password: v.StringSchema<undefined>_password: import vv.function string(): v.StringSchema<undefined> (+1 overload)
export string
Creates a string schema.
string() }),
async ({ name: stringname, _password: string_password }) => {
const const success: anysuccess = import tryLogintryLogin(name: stringname, _password: string_password);
if (!const success: anysuccess) {
function invalid(...issues: (StandardSchemaV1<Input = unknown, Output = Input>.Issue | string)[]): neverUse this to throw a validation error to imperatively fail form validation.
Can be used in combination with issue passed to form actions to create field-specific issues.
invalid('Incorrect username or password');
}
// ...
}
);function invalid(
...issues: (StandardSchemaV1.Issue | string)[]
): never;isActionFailure
Checks whether this is an action failure thrown by fail.
function isActionFailure(e: unknown): e is ActionFailure;isHttpError
Checks whether this is an error thrown by error.
function isHttpError<T extends number>(
e: unknown,
status?: T
): e is HttpError & {
status: T extends undefined ? never : T;
};isRedirect
Checks whether this is a redirect thrown by redirect.
function isRedirect(e: unknown): e is Redirect;isValidationError
Available since 2.47.3
Checks whether this is an validation error thrown by invalid.
function isValidationError(
e: unknown
): e is import('$app/server').ValidationError;json
use
Response.json
Create a JSON Response object from the supplied data.
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.
import { function normalizeUrl(url: URL | string): {
url: URL;
wasNormalized: boolean;
denormalize: (url?: string | URL) => URL;
}
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.
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
normalizeUrl } from '@sveltejs/kit';
const { const url: URLurl, const denormalize: (url?: string | URL) => URLdenormalize } = function normalizeUrl(url: URL | string): {
url: URL;
wasNormalized: boolean;
denormalize: (url?: string | URL) => URL;
}
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.
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
normalizeUrl('/blog/post/__data.json');
var console: ConsoleThe 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 importing the node:console module.
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 url: URLurl.URL.pathname: stringThe pathname property of the URL interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a / character.
pathname); // /blog/post
var console: ConsoleThe 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 importing the node:console module.
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 denormalize: (url?: string | URL) => URLdenormalize('/blog/post/a')); // /blog/post/a/__data.jsonfunction 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 method308 Permanent Redirect: redirect will keep the request method, SEO will be transferred to the new page
function redirect(
status:
| 300
| 301
| 302
| 303
| 304
| 305
| 306
| 307
| 308
| ({} & number),
location: string | URL,
options?: {
external?: boolean | string[];
}
): never;text
use
new Response
Create a Response object from the supplied body.
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 for more information.
type Action<
Params extends AppLayoutParams<'/'> =
AppLayoutParams<'/'>,
OutputData extends Record<string, any> | void = Record<
string,
any
> | void,
RouteId extends AppRouteId | null = AppRouteId | null
> = (
event: RequestEvent<Params, RouteId>
) => MaybePromise<OutputData>;ActionFailure
interface ActionFailure<T = undefined> {…}status: number;data: T;[uniqueSymbol]: true;Actions
Shape of the export const actions = {...} object in +page.server.js.
See form actions for more information.
type Actions<
Params extends AppLayoutParams<'/'> =
AppLayoutParams<'/'>,
OutputData extends Record<string, any> | void = Record<
string,
any
> | void,
RouteId extends AppRouteId | null = AppRouteId | null
> = Record<string, Action<Params, OutputData, RouteId>>;Adapter
Adapters are responsible for taking the production build and turning it into something that can be deployed to a platform of your choosing.
interface Adapter {…}name: string;The name of the adapter, using for logging. Will typically correspond to the package name.
adapt: (builder: Builder) => MaybePromise<void>;builderAn object provided by SvelteKit that contains methods for adapting the app
This function is called after SvelteKit has built your app.
supports?: {…}Checks called during dev and build to determine whether specific features will work in production with this adapter.
read?: (details: { config: Record<string, any>; route: { id: string } }) => boolean;details.configThe merged adapter-specific route config exported from the route withexport const config
Test support for read from $app/server.
instrumentation?: () => boolean;- available since v2.31.0
Test support for instrumentation.server.js. To pass, the adapter must support running instrumentation.server.js prior to the application code.
getRequest?: typeof getRequest;- available since v3.0.0
This function overrides the default behavior to convert an http.IncomingMessage to a Request object.
To call the original setRequest function, import it from @sveltejs/kit/node.
setResponse?: typeof setResponse;- available since v3.0.0
This function overrides the default behavior to write a Response object to an http.ServerResponse.
To call the original setResponse function, import it from @sveltejs/kit/node.
emulate?: () => MaybePromise<Emulator>;Creates an Emulator, which allows the adapter to influence the environment
during dev, build and prerendering.
vite?: {
plugins?: {
/**
* Vite plugins placed before any of SvelteKit's own plugins.
* @since 3.0.0
*/
pre?: Plugin[];
/**
* Vite plugins placed after any of SvelteKit's own plugins.
* @since 3.0.0
*/
post?: Plugin[];
};
};AwaitedActions
type AwaitedActions<
T extends Record<string, (...args: any) => any>
> = OptionalUnion<
{
[Key in keyof T]: UnpackValidationError<
Awaited<ReturnType<T[Key]>>
>;
}[keyof T]
>;Builder
This object is passed to the adapt function of adapters.
It contains various methods and properties that are useful for adapting the app.
interface Builder {…}log: Logger;Print messages to the console. log.info and log.minor are silent unless Vite's logLevel is info.
rimraf: (dir: string) => void;- deprecated Use
fs.rmSync(dir, { force: true, recursive: true })instead
Remove dir and all its contents.
mkdirp: (dir: string) => void;- deprecated Use
fs.mkdirSync(dir, { recursive: true })instead
Create dir and any required parent directories.
config: ValidatedConfig;The fully resolved SvelteKit config.
prerendered: Prerendered;Information about prerendered pages and assets, if any.
routes: RouteDefinition[];An array of all routes (including prerendered)
createEntries?: (fn: (route: RouteDefinition) => AdapterEntry) => Promise<void>;fnA function that groups a set of routes into an entry point- deprecated removed in 3.0. Use
builder.routesinstead
Create separate functions that map to one or more routes of your app.
findServerAssets: (routes: RouteDefinition[]) => string[];Find all the assets imported by server files belonging to routes
generateFallback: (dest: string) => Promise<void>;Generate a fallback page for a static webserver to use when no route is matched. Useful for single-page apps.
generateEnvModule: () => void;Generate a module exposing public environment variables as $app/env/public if the app uses it.
generateManifest: (opts: { relativePath: string; routes?: RouteDefinition[] }) => string;opts.relativePathA relative path to the base directory of the server build output
Generate a server-side manifest to initialise the SvelteKit server with.
getBuildDirectory: (name: string) => string;namepath to the file, relative to the build directory
Resolve a path to the name directory inside outDir, e.g. /path/to/.svelte-kit/my-adapter.
getClientDirectory: () => string;Get the fully resolved path to the directory containing client-side assets, including the contents of your static directory.
getServerDirectory: () => string;Get the fully resolved path to the directory containing server-side code.
getAppPath: () => string;Get the application path including any configured base path, e.g. my-base-path/_app.
writeClient: (dest: string) => string[];destthe destination folder- returns an array of files written to
dest
Write client assets to dest.
writePrerendered: (dest: string) => string[];destthe destination folder- returns an array of files written to
dest
Write prerendered files to dest.
writeServer: (dest: string) => string[];destthe destination folder- returns an array of files written to
dest
Write server-side code to dest.
copy: (
from: string,
to: string,
opts?: {
filter?(basename: string): boolean;
replace?: Record<string, string>;
}
) => string[];fromthe source file or directorytothe destination file or directoryopts.filtera function to determine whether a file or directory should be copiedopts.replacea map of strings to replace- returns an array of files that were copied
Copy a file or directory.
hasServerInstrumentationFile: () => boolean;- returns true if the server instrumentation file exists, false otherwise
- available since v2.31.0
Check if the server instrumentation file exists.
instrument: (args: {
entrypoint: string;
instrumentation: string;
start?: string;
module?:
| {
exports: string[];
}
| {
generateText: (args: { instrumentation: string; start: string }) => string;
};
}) => void;optionsan object containing the following properties:options.entrypointthe path to the entrypoint to trace.options.instrumentationthe path to the instrumentation file.options.startthe name of the start file. This is whatentrypointwill be renamed to.options.moduleconfiguration for the resulting entrypoint module.options.module.generateTexta function that receives the relative paths to the instrumentation and start files, and generates the text of the module to be traced. If not provided, the default implementation will be used, which uses top-level await.- available since v2.31.0
Instrument entrypoint with instrumentation.
Renames entrypoint to start and creates a new module at
entrypoint which imports instrumentation and then dynamically imports start. This allows
the module hooks necessary for instrumentation libraries to be loaded prior to any application code.
Caveats:
- "Live exports" will not work. If your adapter uses live exports, your users will need to manually import the server instrumentation on startup.
- If
tlaisfalse, OTEL auto-instrumentation may not work properly. Use it if your environment supports it. - Use
hasServerInstrumentationFileto check if the user has a server instrumentation file; if they don't, you shouldn't do this.
compress: (directory: string) => Promise<string[]>;directoryThe directory containing the files to be compressed- returns an array of the files in
directorythat were compressed
Compress files in directory with gzip and brotli, where appropriate. Generates .gz and .br files alongside the originals.
Config
See the configuration reference for details.
Cookies
interface Cookies {…}get: (name: string, opts?: import('cookie').ParseOptions) => string | undefined;namethe name of the cookieoptsthe options, passed directly tocookie.parseCookie. See documentation here
Gets a cookie that was previously set with cookies.set, or from the request headers.
getAll: (opts?: import('cookie').ParseOptions) => Array<{ name: string; value: string }>;optsthe options, passed directly tocookie.parseCookie. See documentation here
Gets all cookies that were previously set with cookies.set, or from the request headers.
set: (name: string, value: string, opts: import('cookie').SerializeOptions) => void;namethe name of the cookievaluethe cookie valueoptsthe options passed tocookie.stringifySetCookiewith the SvelteKit defaults described above. See documentation here
Sets a cookie. This will add a set-cookie header to the response, but also make the cookie available via cookies.get or cookies.getAll during the current request.
The httpOnly is true by default, as is secure, except during development, when it defaults to false. These must be explicitly disabled if you want cookies to be readable by client-side JavaScript and/or transmitted over HTTP.
The path option is '/' by default. You can use relative paths, or set path: '' to make the cookie only available on the current path and its children.
delete: (name: string, opts: import('cookie').SerializeOptions) => void;namethe name of the cookieoptsthe options passed tocookie.stringifySetCookiewith the SvelteKit defaults described above. See documentation here
Deletes a cookie by setting its value to an empty string and setting the expiry date in the past.
The httpOnly is true by default, as is secure, except during development, when it defaults to false. These must be explicitly disabled if you want cookies to be readable by client-side JavaScript and/or transmitted over HTTP.
The path option is '/' by default. You can use relative paths, or set path: '' to make the cookie only available on the current path and its children.
parse: typeof import('cookie').parseSetCookie;Parses a single Set-Cookie header. This allows you to apply cookies received from an external source:
import { function getRequestEvent(): RequestEventReturns the current RequestEvent. Can be used inside server hooks, server load functions, actions, and endpoints (and functions called by them).
In environments without AsyncLocalStorage, this must be called synchronously (i.e. not after an await).
getRequestEvent } from '$app/server';
export async function function GET(): Promise<void>GET() {
const { const cookies: CookiesGet or set cookies related to the current request
cookies } = function getRequestEvent(): RequestEventReturns the current RequestEvent. Can be used inside server hooks, server load functions, actions, and endpoints (and functions called by them).
In environments without AsyncLocalStorage, this must be called synchronously (i.e. not after an await).
getRequestEvent();
const const response: Responseresponse = await function fetch(input: string | URL | Request, init?: RequestInit): Promise<Response> (+1 overload)fetch('...');
for (const const str: stringstr of const response: Responseresponse.Response.headers: HeadersThe headers read-only property of the Response interface contains the Headers object associated with the response.
headers.Headers.getSetCookie(): string[]The getSetCookie() method of the Headers interface returns an array containing the values of all Set-Cookie headers associated with a response. This allows Headers objects to handle having multiple Set-Cookie headers, which wasn't possible prior to its implementation.
getSetCookie()) {
const { const name: stringSpecifies the name of the cookie.
name, const value: string | undefinedSpecifies the string to be the value for the cookie.
value, ...const options: {
maxAge?: number;
expires?: Date;
domain?: string;
path?: string;
httpOnly?: boolean;
secure?: boolean;
partitioned?: boolean;
priority?: "low" | "medium" | "high";
sameSite?: boolean | "lax" | "strict" | "none";
}
options } = const cookies: CookiesGet or set cookies related to the current request
cookies.Cookies.parse: (str: string, options?: ParseOptions) => SetCookieDeserialize a Set-Cookie header into an object.
parseSetCookie('foo=bar; HttpOnly')
=> { name: 'foo', value: 'bar', httpOnly: true }
parse(const str: stringstr);
const cookies: CookiesGet or set cookies related to the current request
cookies.Cookies.set: (name: string, value: string, opts: SerializeOptions) => voidSets a cookie. This will add a set-cookie header to the response, but also make the cookie available via cookies.get or cookies.getAll during the current request.
The httpOnly is true by default, as is secure, except during development, when it defaults to false. These must be explicitly disabled if you want cookies to be readable by client-side JavaScript and/or transmitted over HTTP.
The path option is '/' by default. You can use relative paths, or set path: '' to make the cookie only available on the current path and its children.
set(const name: stringSpecifies the name of the cookie.
name, const value: string | undefinedSpecifies the string to be the value for the cookie.
value, { ...const options: {
maxAge?: number;
expires?: Date;
domain?: string;
path?: string;
httpOnly?: boolean;
secure?: boolean;
partitioned?: boolean;
priority?: "low" | "medium" | "high";
sameSite?: boolean | "lax" | "strict" | "none";
}
options, path?: string | undefinedSpecifies the value for the Path Set-Cookie attribute.
When no path is set, the path is considered the "default path".
path: '/' });
}
// ...
}Note the use of headers.getSetCookie(), which returns an array of cookie headers, not headers.get('set-cookie') which returns a single comma-separated string.
serialize: (name: string, value: string, opts: import('cookie').SerializeOptions) => string;namethe name of the cookievaluethe cookie valueoptsthe options passed tocookie.stringifySetCookiewith the SvelteKit defaults described above. See documentation here
Serialize a cookie name-value pair into a Set-Cookie header string, but don't apply it to the response.
The httpOnly is true by default, as is secure, except during development, when it defaults to false. These must be explicitly disabled if you want cookies to be readable by client-side JavaScript and/or transmitted over HTTP.
The path option is '/' by default. You can use relative paths, or set path: '' to make the cookie only available on the current path and its children.
Emulator
A collection of functions that influence the environment during dev, build and prerendering
interface Emulator {…}platform?(details: { config: any; prerender: PrerenderOption }): MaybePromise<App.Platform>;A function that is called with the current route config and prerender option
and returns an App.Platform object
HttpError
The object returned by the error function.
interface HttpError {…}status: number;The HTTP status code, in the range 400-599.
body: App.Error;The content of the error.
KitConfig
See the configuration reference for details.
Load
The generic form of PageLoad and LayoutLoad. You should import those from ./$types (see generated types)
rather than using Load directly.
type Load<
Params extends AppLayoutParams<'/'> =
AppLayoutParams<'/'>,
InputData extends Record<string, unknown> | null = Record<
string,
any
> | null,
ParentData extends Record<string, unknown> = Record<
string,
any
>,
OutputData extends Record<string, unknown> | void =
Record<string, any> | void,
RouteId extends AppRouteId | null = AppRouteId | null
> = (
event: LoadEvent<Params, InputData, ParentData, RouteId>
) => MaybePromise<OutputData>;LoadEvent
The generic form of PageLoadEvent and LayoutLoadEvent. You should import those from ./$types (see generated types)
rather than using LoadEvent directly.
interface LoadEvent<
Params extends AppLayoutParams<'/'> =
AppLayoutParams<'/'>,
Data extends Record<string, unknown> | null = Record<
string,
any
> | null,
ParentData extends Record<string, unknown> = Record<
string,
any
>,
RouteId extends AppRouteId | null = AppRouteId | null
> extends NavigationEvent<Params, RouteId> {…}fetch: typeof fetch;fetch is equivalent to the native fetch web API, with a few additional features:
- It can be used to make credentialed requests on the server, as it inherits the
cookieandauthorizationheaders for the page request. - It can make relative requests on the server (ordinarily,
fetchrequires a URL with an origin when used in a server context). - Internal requests (e.g. for
+server.jsroutes) 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
textandjsonmethods of theResponseobject. Note that headers will not be serialized, unless explicitly included viafilterSerializedResponseHeaders - 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
data: Data;Contains the data returned by the route's server load function (in +layout.server.js or +page.server.js), if any.
setHeaders: (headers: Record<string, string>) => 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:
export async function function load({ fetch, setHeaders }: {
fetch: any;
setHeaders: any;
}): Promise<any>
load({ fetch, setHeaders }) {
const const url: "https://cms.example.com/articles.json"url = `https://cms.example.com/articles.json`;
const const response: anyresponse = await fetch: anyfetch(const url: "https://cms.example.com/articles.json"url);
setHeaders: anysetHeaders({
age: anyage: const response: anyresponse.headers.get('age'),
'cache-control': const response: anyresponse.headers.get('cache-control')
});
return const response: anyresponse.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 API in a server-only load function instead.
setHeaders has no effect when a load function runs in the browser.
parent: () => Promise<ParentData>;await parent() returns data from parent +layout.js load functions.
Implicitly, a missing +layout.js is treated as a ({ data }) => data function, meaning that it will return and forward data from parent +layout.server.js files.
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.
depends: (...deps: Array<`${string}:${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() 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.
Custom identifiers have to be prefixed with one or more lowercase letters followed by a colon to conform to the URI specification.
The following example shows how to use depends to register a dependency on a custom identifier, which is invalidated after a button click, making the load function rerun.
let let count: numbercount = 0;
export async function function load({ depends }: {
depends: any;
}): Promise<{
count: number;
}>
load({ depends }) {
depends: anydepends('increase:count');
return { count: numbercount: let count: numbercount++ };
}<script>
import { invalidate } from '$app/navigation';
let { data } = $props();
const increase = async () => {
await invalidate('increase:count');
}
</script>
<p>{data.count}<p>
<button on:click={increase}>Increase Count</button>untrack: <T>(fn: () => T) => T;Use this function to opt out of dependency tracking for everything that is synchronously called within the callback. Example:
export async function function load({ untrack, url }: {
untrack: any;
url: any;
}): Promise<{
message: string;
} | undefined>
load({ untrack, url }) {
// Untrack url.pathname so that path changes don't trigger a rerun
if (untrack: anyuntrack(() => url: anyurl.pathname === '/')) {
return { message: stringmessage: 'Welcome!' };
}
}tracing: {…}- available since v2.31.0
Access to spans for tracing. If tracing is not enabled or the function is being run in the browser, these spans will do nothing.
enabled: boolean;Whether tracing is enabled.
root: Span;The root span for the request. This span is named sveltekit.handle.root.
current: Span;The span associated with the current load function.
LoadProperties
type LoadProperties<
input extends Record<string, any> | void
> = input extends void
? undefined // needs to be undefined, because void will break intellisense
: input extends Record<string, any>
? input
: unknown;NavigationEvent
interface NavigationEvent<
Params extends AppLayoutParams<'/'> =
AppLayoutParams<'/'>,
RouteId extends AppRouteId | null = AppRouteId | null
> {…}params: Params;The parameters of the current page - e.g. for a route like /blog/[slug], a { slug: string } object
route: {…}Info about the current route
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.
url: URL;The URL of the current page
PrerenderOption
type PrerenderOption = boolean | 'auto';Redirect
The object returned by the redirect function.
interface Redirect {…}status: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308;The HTTP status code, in the range 300-308.
location: string;The location to redirect to.
RequestEvent
interface RequestEvent<
Params extends AppLayoutParams<'/'> =
AppLayoutParams<'/'>,
RouteId extends AppRouteId | null = AppRouteId | null
> {…}readonly cookies: Cookies;Get or set cookies related to the current request
readonly fetch: typeof fetch;fetch is equivalent to the native fetch web API, with a few additional features:
- It can be used to make credentialed requests on the server, as it inherits the
cookieandauthorizationheaders for the page request. - It can make relative requests on the server (ordinarily,
fetchrequires a URL with an origin when used in a server context). - Internal requests (e.g. for
+server.jsroutes) 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
textandjsonmethods of theResponseobject. Note that headers will not be serialized, unless explicitly included viafilterSerializedResponseHeaders - 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.
readonly getClientAddress: () => string;The client's IP address, set by the adapter.
readonly locals: App.Locals;Contains custom data that was added to the request within the server handle hook.
readonly params: Params;The parameters of the current route - e.g. for a route like /blog/[slug], a { slug: string } object.
Inside query functions (including query.batch and query.live), accessing this property throws an error.
Pass values from the page as arguments to the query instead. Inside form and command functions it relates to the page
the remote function was called from, not the URL of the endpoint SvelteKit creates for the remote function. Never use it
to determine whether or not a user is authorized to access certain data, as these values are part of the request which could be manipulated.
readonly platform: Readonly<App.Platform> | undefined;Additional data made available through the adapter.
readonly request: Request;The original request object.
readonly route: {…}Info about the current route.
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.
Inside query functions (including query.batch and query.live), accessing this property throws an error.
Pass values from the page as arguments to the query instead. Inside form and command functions it relates to the page
the remote function was called from, not the URL of the endpoint SvelteKit creates for the remote function. Never use it
to determine whether or not a user is authorized to access certain data, as these values are part of the request which could be manipulated.
readonly setHeaders: (headers: Record<string, string>) => 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:
export async function function load({ fetch, setHeaders }: {
fetch: any;
setHeaders: any;
}): Promise<any>
load({ fetch, setHeaders }) {
const const url: "https://cms.example.com/articles.json"url = `https://cms.example.com/articles.json`;
const const response: anyresponse = await fetch: anyfetch(const url: "https://cms.example.com/articles.json"url);
setHeaders: anysetHeaders({
age: anyage: const response: anyresponse.headers.get('age'),
'cache-control': const response: anyresponse.headers.get('cache-control')
});
return const response: anyresponse.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 API instead.
readonly url: URL;The requested URL.
Inside query functions (including query.batch and query.live), accessing this property throws an error.
Pass values from the page as arguments to the query instead. Inside form and command functions it relates to the page
the remote function was called from, not the URL of the endpoint SvelteKit creates for the remote function. Never use it
to determine whether or not a user is authorized to access certain data, as these values are part of the request which could be manipulated.
readonly 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.
readonly 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.
readonly tracing: {…}- available since v2.31.0
Access to spans for tracing. If tracing is not enabled, these spans will do nothing.
enabled: boolean;Whether tracing is enabled.
root: Span;The root span for the request. This span is named sveltekit.handle.root.
current: Span;The span associated with the current handle hook, load function, or form action.
readonly 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 instead.
type RequestHandler<
Params extends AppLayoutParams<'/'> =
AppLayoutParams<'/'>,
RouteId extends AppRouteId | null = AppRouteId | null
> = (
event: RequestEvent<Params, RouteId>
) => MaybePromise<Response>;RouteDefinition
interface RouteDefinition<Config = any> {…}id: string;api: {
methods: Array<HttpMethod | '*'>;
};page: {
methods: Array<Extract<HttpMethod, 'GET' | 'POST'>>;
};pattern: RegExp;prerender: PrerenderOption;segments: RouteSegment[];methods: Array<HttpMethod | '*'>;config: Config;SSRManifest
Information required to instantiate a new Server instance.
interface SSRManifest {…}appDir: string;The directory where SvelteKit keeps its stuff, including static assets (such as JS and CSS) and internally-used routes.
appPath: string;The base and appDir settings combined without a leading slash.
assets: Set<string>;Static files from config.files.assets and the service worker (if any).
mimeTypes: Record<string, string>;ServerInitOptions
interface ServerInitOptions {…}env: Record<string, string | undefined>;A map of environment variables.
read?: (file: string) => MaybePromise<ReadableStream | null>;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)
rather than using ServerLoad directly.
type ServerLoad<
Params extends AppLayoutParams<'/'> =
AppLayoutParams<'/'>,
ParentData extends Record<string, any> = Record<
string,
any
>,
OutputData extends Record<string, any> | void = Record<
string,
any
> | void,
RouteId extends AppRouteId | null = AppRouteId | null
> = (
event: ServerLoadEvent<Params, ParentData, RouteId>
) => MaybePromise<OutputData>;ServerLoadEvent
interface ServerLoadEvent<
Params extends AppLayoutParams<'/'> =
AppLayoutParams<'/'>,
ParentData extends Record<string, any> = Record<
string,
any
>,
RouteId extends AppRouteId | null = AppRouteId | null
> extends RequestEvent<Params, RouteId> {…}parent: () => Promise<ParentData>;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.
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() 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.
Custom identifiers have to be prefixed with one or more lowercase letters followed by a colon to conform to the URI specification.
The following example shows how to use depends to register a dependency on a custom identifier, which is invalidated after a button click, making the load function rerun.
let let count: numbercount = 0;
export async function function load({ depends }: {
depends: any;
}): Promise<{
count: number;
}>
load({ depends }) {
depends: anydepends('increase:count');
return { count: numbercount: let count: numbercount++ };
}<script>
import { invalidate } from '$app/navigation';
let { data } = $props();
const increase = async () => {
await invalidate('increase:count');
}
</script>
<p>{data.count}<p>
<button on:click={increase}>Increase Count</button>untrack: <T>(fn: () => T) => T;Use this function to opt out of dependency tracking for everything that is synchronously called within the callback. Example:
export async function function load({ untrack, url }: {
untrack: any;
url: any;
}): Promise<{
message: string;
} | undefined>
load({ untrack, url }) {
// Untrack url.pathname so that path changes don't trigger a rerun
if (untrack: anyuntrack(() => url: anyurl.pathname === '/')) {
return { message: stringmessage: 'Welcome!' };
}
}tracing: {…}- available since v2.31.0
Access to spans for tracing. If tracing is not enabled, these spans will do nothing.
enabled: boolean;Whether tracing is enabled.
root: Span;The root span for the request. This span is named sveltekit.handle.root.
current: Span;The span associated with the current server load function.
Snapshot
Use the
snapshothelper from$app/navigationinstead.
The type of export const snapshot exported from a page or layout component.
interface Snapshot<T = any> {…}capture: () => T;restore: (snapshot: T) => void;Private types
The following are referenced by the public types documented above, but cannot be imported directly:
AdapterEntry
interface AdapterEntry {…}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
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:/fooshould be deployed to the edge,/barand/bazshould be deployed to a serverless function
complete(entry: { generateManifest(opts: { relativePath: string }): string }): MaybePromise<void>;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
namespace Csp {
type ActionSource = 'strict-dynamic' | 'report-sample';
type BaseSource =
| 'self'
| 'unsafe-eval'
| 'unsafe-hashes'
| 'unsafe-inline'
| 'unsafe-allow-redirects'
| 'unsafe-webtransport-hashes'
| 'wasm-unsafe-eval'
| 'trusted-types-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:'
| 'ws:'
| 'wss:'
| 'data:'
| 'mediastream:'
| 'blob:'
| 'filesystem:'
| (`${string}:` & {});
type Source =
| HostSource
| SchemeSource
| CryptoSource
| BaseSource;
type Sources = Source[];
}CspDirectives
interface CspDirectives {…}'child-src'?: Csp.Sources;'default-src'?: Array<Csp.Source | Csp.ActionSource>;'frame-src'?: Csp.Sources;'worker-src'?: Csp.Sources;'connect-src'?: Csp.Sources;'font-src'?: Csp.Sources;'img-src'?: Csp.Sources;'manifest-src'?: Csp.Sources;'media-src'?: Csp.Sources;'object-src'?: Csp.Sources;'prefetch-src'?: Csp.Sources;'script-src'?: Array<Csp.Source | Csp.ActionSource>;'script-src-elem'?: Csp.Sources;'script-src-attr'?: Csp.Sources;'style-src'?: Array<Csp.Source | Csp.ActionSource>;'style-src-elem'?: Csp.Sources;'style-src-attr'?: Csp.Sources;'base-uri'?: Array<Csp.Source | Csp.ActionSource>;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'
>;'form-action'?: Array<Csp.Source | Csp.ActionSource>;'frame-ancestors'?: Array<Csp.HostSource | Csp.SchemeSource | Csp.FrameSource>;'navigate-to'?: Array<Csp.Source | Csp.ActionSource>;'report-uri'?: string[];'report-to'?: string[];'require-trusted-types-for'?: Array<'script'>;'trusted-types'?: Array<'none' | 'allow-duplicates' | '*' | string>;'upgrade-insecure-requests'?: boolean;'require-sri-for'?: Array<'script' | 'style' | 'script style'>;- deprecated
'block-all-mixed-content'?: boolean;- deprecated
'plugin-types'?: Array<`${string}/${string}` | 'none'>;- deprecated
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'
>;- deprecated
DeepPartial
type DeepPartial<T> = T extends
| Record<PropertyKey, unknown>
| unknown[]
? {
[K in keyof T]?: T[K] extends
| Record<PropertyKey, unknown>
| unknown[]
? DeepPartial<T[K]>
: T[K];
}
: T | undefined;HasNonOptionalBoolean
type HasNonOptionalBoolean<T> =
IsAny<T> extends true
? never
: [T] extends [boolean]
? true
: T extends Array<infer U>
? HasNonOptionalBoolean<U>
: T extends Record<string, any>
? {
[K in keyof T]: HasNonOptionalBoolean<T[K]>;
}[keyof T]
: never;HttpMethod
type HttpMethod =
| 'GET'
| 'HEAD'
| 'POST'
| 'PUT'
| 'DELETE'
| 'PATCH'
| 'OPTIONS';IsAny
type IsAny<T> = 0 extends 1 & T ? true : false;Logger
interface Logger {…}(msg: string): void;success(msg: string): void;error(msg: string): void;Print a bold red message to stderr
warn(msg: string): void;Print a bold yellow message to stderr
minor(msg: string): void;Print faded text to stdout if verbose === true
info(msg: string): void;Print to stdout if verbose === true
err(msg: string): void;Print to stderr without formatting
prettyError(error: unknown, caller?: string): void;Print a bold red message, followed by a stack trace for each error (following .cause chains)
MaybePromise
type MaybePromise<T> = T | Promise<T>;PrerenderEntryGeneratorMismatchHandler
interface PrerenderEntryGeneratorMismatchHandler {…}(details: { generatedFromId: string; entry: string; matchedId: string; message: string }): void;PrerenderEntryGeneratorMismatchHandlerValue
type PrerenderEntryGeneratorMismatchHandlerValue =
| 'fail'
| 'warn'
| 'ignore'
| PrerenderEntryGeneratorMismatchHandler;PrerenderHttpErrorHandler
interface PrerenderHttpErrorHandler {…}(details: {
status: number;
path: string;
referrer: string | null;
referenceType: 'linked' | 'fetched';
message: string;
}): void;PrerenderHttpErrorHandlerValue
type PrerenderHttpErrorHandlerValue =
| 'fail'
| 'warn'
| 'ignore'
| PrerenderHttpErrorHandler;PrerenderInvalidUrlHandler
interface PrerenderInvalidUrlHandler {…}(details: { href: string; referrer: string | null; message: string }): void;PrerenderInvalidUrlHandlerValue
type PrerenderInvalidUrlHandlerValue =
| 'fail'
| 'warn'
| 'ignore'
| PrerenderInvalidUrlHandler;PrerenderMap
type PrerenderMap = Map<string, PrerenderOption>;PrerenderMissingIdHandler
interface PrerenderMissingIdHandler {…}(details: { path: string; id: string; referrers: string[]; message: string }): void;PrerenderMissingIdHandlerValue
type PrerenderMissingIdHandlerValue =
| 'fail'
| 'warn'
| 'ignore'
| PrerenderMissingIdHandler;PrerenderOption
type PrerenderOption = boolean | 'auto';PrerenderUnseenRoutesHandler
interface PrerenderUnseenRoutesHandler {…}(details: { routes: string[]; message: string }): void;PrerenderUnseenRoutesHandlerValue
type PrerenderUnseenRoutesHandlerValue =
| 'fail'
| 'warn'
| 'ignore'
| PrerenderUnseenRoutesHandler;Prerendered
interface Prerendered {…}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.
assets: Map<
string,
{
/** The MIME type of the asset */
type: string;
}
>;A map of path to { type } objects.
redirects: Map<
string,
{
status: number;
location: string;
}
>;A map of redirects encountered during prerendering.
paths: string[];An array of prerendered paths (without trailing slashes, regardless of the trailingSlash config)
RequestOptions
interface RequestOptions {…}getClientAddress(): string;platform?: App.Platform;RouteSegment
interface RouteSegment {…}content: string;dynamic: boolean;rest: boolean;TrailingSlash
type TrailingSlash = 'never' | 'always' | 'ignore';Edit this page on GitHub llms.txt