Skip to main content

Types

Edit this page on GitHub

@sveltejs/kitpermalink

All APIs in SvelteKit are fully typed. The following types can be imported from @sveltejs/kit:

Adapterpermalink

interface Adapter {
  name: string;
  adapt(builder: Builder): Promise<void>;
}

Builderpermalink

interface Builder {
  log: Logger;
  rimraf(dir: string): void;
  mkdirp(dir: string): void;

  appDir: string;
  trailingSlash: TrailingSlash;
  /**   * Create entry points that map to individual functions   * @param fn A function that groups a set of routes into an entry point   */  createEntries(
    fn: (route: RouteDefinition) => AdapterEntry
  ): void;

  generateManifest: (opts: {
    relativePath: string;
    format?: 'esm' | 'cjs';
  }) => string;

  getBuildDirectory(name: string): string;
  getClientDirectory(): string;
  getServerDirectory(): string;
  getStaticDirectory(): string;
  /**   * @param dest the destination folder to which files should be copied   * @returns an array of paths corresponding to the files that have been created by the copy   */  writeClient(dest: string): string[];
  /**   * @param dest the destination folder to which files should be copied   * @returns an array of paths corresponding to the files that have been created by the copy   */  writeServer(dest: string): string[];
  /**   * @param dest the destination folder to which files should be copied   * @returns an array of paths corresponding to the files that have been created by the copy   */  writeStatic(dest: string): string[];
  /**   * @param from the source file or folder   * @param to the destination file or folder   * @param opts.filter a function to determine whether a file or folder should be copied   * @param opts.replace a map of strings to replace   * @returns an array of paths corresponding to the files that have been created by the copy   */  copy(
    from: string,
    to: string,
    opts?: {
      filter?: (basename: string) => boolean;
      replace?: Record<string, string>;
    }
  ): string[];

  prerender(options: {
    all?: boolean;
    dest: string;
    fallback?: string;
  }): Promise<Prerendered>;
}

Configpermalink

interface Config {
  compilerOptions?: CompileOptions;
  extensions?: string[];
  kit?: {
    adapter?: Adapter;
    amp?: boolean;
    appDir?: string;
    browser?: {
      hydrate?: boolean;
      router?: boolean;
    };
    csp?: {
      mode?: 'hash' | 'nonce' | 'auto';
      directives?: CspDirectives;
    };
    files?: {
      assets?: string;
      hooks?: string;
      lib?: string;
      routes?: string;
      serviceWorker?: string;
      template?: string;
    };
    floc?: boolean;
    inlineStyleThreshold?: number;
    methodOverride?: {
      parameter?: string;
      allowed?: string[];
    };
    package?: {
      dir?: string;
      emitTypes?: boolean;
      exports?(filepath: string): boolean;
      files?(filepath: string): boolean;
    };
    paths?: {
      assets?: string;
      base?: string;
    };
    prerender?: {
      concurrency?: number;
      crawl?: boolean;
      enabled?: boolean;
      entries?: string[];
      onError?: PrerenderOnErrorValue;
    };
    routes?: (filepath: string) => boolean;
    serviceWorker?: {
      register?: boolean;
      files?: (filepath: string) => boolean;
    };
    trailingSlash?: TrailingSlash;
    version?: {
      name?: string;
      pollInterval?: number;
    };
    vite?:
      | import('vite').UserConfig
      | (() => MaybePromise<import('vite').UserConfig>);
  };
  preprocess?: any;
}

Csppermalink

namespace Csp {
  type ActionSource = 'strict-dynamic' | 'report-sample';
  type BaseSource =
    | 'self'
    | 'unsafe-eval'
    | 'unsafe-hashes'
    | 'unsafe-inline'
    | 'none';
  type CryptoSource = `${
    | 'nonce'
    | 'sha256'
    | 'sha384'
    | 'sha512'}-${string}`;
  type FrameSource =
    | HostSource
    | SchemeSource
    | 'self'
    | 'none';
  type HostNameScheme = `${string}.${string}` | 'localhost';
  type HostSource =
    `${HostProtocolSchemes}${HostNameScheme}${PortScheme}`;
  type HostProtocolSchemes = `${string}://` | '';
  type HttpDelineator = '/' | '?' | '#' | '\\';
  type PortScheme = `:${number}` | '' | ':*';
  type SchemeSource =
    | 'http:'
    | 'https:'
    | 'data:'
    | 'mediastream:'
    | 'blob:'
    | 'filesystem:';
  type Source =
    | HostSource
    | SchemeSource
    | CryptoSource
    | BaseSource;
  type Sources = Source[];
  type UriPath = `${HttpDelineator}${string}`;
}

CspDirectivespermalink

type 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'?: Csp.UriPath[];
  'report-to'?: string[];

  'require-trusted-types-for'?: Array<'script'>;
  'trusted-types'?: Array<
    'none' | 'allow-duplicates' | '*' | string
  >;
  'upgrade-insecure-requests'?: boolean;
  /** @deprecated */  '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'
  >;
};

EndpointOutputpermalink

interface EndpointOutput<Output extends Body = Body> {
  status?: number;
  headers?: Headers | Partial<ResponseHeaders>;
  body?: Output;
}

ErrorLoadpermalink

interface ErrorLoad<
  Params = Record<string, string>,
  Props = Record<string, any>
> {
  (input: ErrorLoadInput<Params>): MaybePromise<
    LoadOutput<Props>
  >;
}

ErrorLoadInputpermalink

interface ErrorLoadInput<Params = Record<string, string>>
  extends LoadInput<Params> {
  status?: number;
  error?: Error;
}

ExternalFetchpermalink

interface ExternalFetch {
  (req: Request): Promise<Response>;
}

GetSessionpermalink

interface GetSession {
  (event: RequestEvent): MaybePromise<App.Session>;
}

Handlepermalink

interface Handle {
  (input: {
    event: RequestEvent;
    resolve(
      event: RequestEvent,
      opts?: ResolveOptions
    ): MaybePromise<Response>;
  }): MaybePromise<Response>;
}

HandleErrorpermalink

interface HandleError {
  (input: {
    error: Error & { frame?: string };
    event: RequestEvent;
  }): void;
}

Loadpermalink

interface Load<
  Params = Record<string, string>,
  Props = Record<string, any>
> {
  (input: LoadInput<Params>): MaybePromise<
    Either<Fallthrough, LoadOutput<Props>>
  >;
}

LoadInputpermalink

interface LoadInput<Params = Record<string, string>> {
  url: URL;
  params: Params;
  props: Record<string, any>;
  fetch(
    info: RequestInfo,
    init?: RequestInit
  ): Promise<Response>;
  session: App.Session;
  stuff: Partial<App.Stuff>;
}

LoadOutputpermalink

interface LoadOutput<Props = Record<string, any>> {
  status?: number;
  error?: string | Error;
  redirect?: string;
  props?: Props;
  stuff?: Partial<App.Stuff>;
  maxage?: number;
}

PrerenderErrorHandlerpermalink

interface PrerenderErrorHandler {
  (details: {
    status: number;
    path: string;
    referrer: string | null;
    referenceType: 'linked' | 'fetched';
  }): void;
}

Prerenderedpermalink

interface Prerendered {
  pages: Map<
    string,
    {
      /** The location of the .html file relative to the output directory */      file: string;
    }
  >;
  assets: Map<
    string,
    {
      /** The MIME type of the asset */      type: string;
    }
  >;
  redirects: Map<
    string,
    {
      status: number;
      location: string;
    }
  >;
  /** An array of prerendered paths (without trailing slashes, regardless of the trailingSlash config) */  paths: string[];
}

RequestEventpermalink

interface RequestEvent<Params = Record<string, string>> {
  request: Request;
  url: URL;
  params: Params;
  locals: App.Locals;
  platform: Readonly<App.Platform>;
}

RequestHandlerpermalink

A function exported from an endpoint that corresponds to an HTTP verb (get, put, patch, etc) and handles requests with that method. Note that since 'delete' is a reserved word in JavaScript, delete handles are called 'del' instead.

interface RequestHandler<
  Params = Record<string, string>,
  Output extends Body = Body
> {
  (event: RequestEvent<Params>): MaybePromise<
    Either<
      Output extends Response
        ? Response
        : EndpointOutput<Output>,
      Fallthrough
    >
  >;
}

RequestOptionspermalink

interface RequestOptions {
  platform?: App.Platform;
}

ResolveOptionspermalink

type ResolveOptions = Partial<RequiredResolveOptions>;

SSRManifestpermalink

interface SSRManifest {
  appDir: string;
  assets: Set<string>;
  /** private fields */  _: {
    mime: Record<string, string>;
    entry: {
      file: string;
      js: string[];
      css: string[];
    };
    nodes: SSRNodeLoader[];
    routes: SSRRoute[];
  };
}

Serverpermalink

class Server {
  constructor(manifest: SSRManifest);
  respond(
    request: Request,
    options?: RequestOptions
  ): Promise<Response>;
}

ValidatedConfigpermalink

type ValidatedConfig = RecursiveRequired<Config>;

The App namespacepermalink

It's possible to tell SvelteKit how to type objects inside your app by declaring the App namespace. By default, a new project will have a file called src/app.d.ts containing the following:

/// <reference types="@sveltejs/kit" />

declare namespace App {
  interface Locals {}

  interface Platform {}

  interface Session {}

  interface Stuff {}
}

By populating these interfaces, you will gain type safety when using event.locals, event.platform, session and stuff:

App.Localspermalink

The interface that defines event.locals, which can be accessed in hooks (handle, handleError and getSession) and endpoints.

App.Platformpermalink

If your adapter provides platform-specific context via event.platform, you can specify it here.

App.Sessionpermalink

The interface that defines session, both as an argument to load functions and the value of the session store.

App.Stuffpermalink

The interface that defines stuff, as input or output to load or as the value of the stuff property of the page store.

previous Configuration
next SEO