### Create and Run SvelteKit Project Source: https://svelte.dev/docs/kit/creating-a-project Scaffolds a new SvelteKit project, navigates into the project directory, and starts the development server. Dependencies should be installed before running the development server if not done during creation. The development server typically runs on localhost:5173. ```bash npx sv create my-app cd my-app npm run dev ``` -------------------------------- ### Install and Configure @sveltejs/adapter-vercel in SvelteKit Source: https://svelte.dev/docs/kit/adapter-vercel This snippet shows how to install the adapter and configure it in your svelte.config.js file. It demonstrates the basic setup required to use Vercel's deployment features with SvelteKit. ```javascript import adapter from '@sveltejs/adapter-vercel'; /** @type {import('@sveltejs/kit').Config} */ const config = { kit: { adapter: adapter({ // see below for options that can be set here }) } }; export default config; ``` ```typescript import adapter from '@sveltejs/adapter-vercel'; import type { Config } from '@sveltejs/adapter-vercel'; /** @type {import('@sveltejs/kit').Config} */ const config: Config = { kit: { adapter: adapter({ // see below for options that can be set here }) } }; export default config; ``` -------------------------------- ### Install Node.js and Dependencies with npm Source: https://svelte.dev/docs/kit/adapter-static This snippet configures GitHub Actions to install a specific version of Node.js (20) and sets up caching for npm dependencies. It then proceeds to install the project's dependencies using `npm install`. ```yaml - name: Install Node.js uses: actions/setup-node@v4 with: node-version: 20 cache: npm - name: Install dependencies run: npm i ``` -------------------------------- ### Configure SvelteKit with Cloudflare Adapter Source: https://svelte.dev/docs/kit/adapter-cloudflare This snippet shows how to install and configure the `@sveltejs/adapter-cloudflare` in your `svelte.config.js` file. It demonstrates the basic setup required to enable Cloudflare deployment, including importing the adapter and assigning it to the `kit.adapter` property. ```javascript import adapter from '@sveltejs/adapter-cloudflare'; /** @type {import('@sveltejs/kit').Config} */ const config = { kit: { adapter: adapter({ // See below for an explanation of these options config: undefined, platformProxy: { configPath: undefined, environment: undefined, persist: undefined }, fallback: 'plaintext', routes: { include: ['/*'], exclude: [''] } }) } }; export default config; ``` -------------------------------- ### Setting up OpenTelemetry Node.js SDK with Auto-Instrumentation Source: https://svelte.dev/docs/kit/observability/llms This JavaScript code configures and starts the OpenTelemetry Node.js SDK for server-side tracing in SvelteKit. It includes necessary dependencies for auto-instrumentation and OTLP trace export. The `import-in-the-middle` package is used to hook into Node.js modules for instrumentation. This setup is intended to be placed in `src/instrumentation.server.js`. ```javascript /// file: src/instrumentation.server.js import { NodeSDK } from '@opentelemetry/sdk-node'; import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node'; import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto'; import { createAddHookMessageChannel } from 'import-in-the-middle'; import { register } from 'node:module'; const { registerOptions } = createAddHookMessageChannel(); register('import-in-the-middle/hook.mjs', import.meta.url, registerOptions); const sdk = new NodeSDK({ serviceName: 'test-sveltekit-tracing', traceExporter: new OTLPTraceExporter(), instrumentations: [getNodeAutoInstrumentations()] }); sdk.start(); ``` -------------------------------- ### Handle Function Example Source: https://svelte.dev/docs/kit/hooks An example demonstrating the usage of the SvelteKit handle function with various ResolveOptions. ```APIDOC ## POST /websites/svelte_dev_kit ### Description This endpoint demonstrates the SvelteKit handle function, which allows for custom request handling and response manipulation using `resolve` and `ResolveOptions`. ### Method POST ### Endpoint /websites/svelte_dev_kit ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "No request body for this example." } ``` ### Response #### Success Response (200) - **response** (Response) - The modified Response object after applying resolve options. #### Response Example ```json { "example": "A Response object representing the result of the resolve function." } ``` ### ResolveOptions Details #### `transformPageChunk` - **Description**: Applies custom transforms to HTML chunks. The `done` parameter indicates if it's the final chunk. - **Parameters**: - `input` (object) - Contains `html` (string) and `done` (boolean). - **Return Value**: A `MaybePromise` representing the transformed HTML chunk. - **Example Usage**: `transformPageChunk: ({ html }) => html.replace('old', 'new')` #### `filterSerializedResponseHeaders` - **Description**: Determines which headers to include in serialized responses when a `load` function fetches a resource. - **Parameters**: - `name` (string) - The header name. - `value` (string) - The header value. - **Return Value**: A boolean indicating whether to include the header. - **Example Usage**: `filterSerializedResponseHeaders: (name) => name.startsWith('x-')` #### `preload` - **Description**: Determines what should be added to the `` tag for preloading. - **Parameters**: - `input` (object) - Contains `type` (string: 'font' | 'css' | 'js' | 'asset') and `path` (string). - **Return Value**: A boolean indicating whether to preload the resource. - **Example Usage**: `preload: ({ type, path }) => type === 'js' || path.includes('/important/')` ### Error Handling If an error is thrown elsewhere during `handle`, SvelteKit will respond with a JSON representation of the error or a fallback error page, depending on the `Accept` header. ``` -------------------------------- ### Client Initialization API Source: https://svelte.dev/docs/kit/%40sveltejs-kit The `init` function is invoked once when the application starts in the browser. ```APIDOC ## ClientInit ### Description Initializes the client-side application when it starts in the browser. ### Method POST ### Endpoint /client/init ### Parameters No parameters required. ### Request Example ```json {} ``` ### Response #### Success Response (200) - **status** (string) - Indicates successful initialization. #### Response Example ```json { "status": "Client initialized successfully." } ``` ``` -------------------------------- ### Example: Using fetch and setHeaders in a load function Source: https://svelte.dev/docs/kit/%40sveltejs-kit Demonstrates how to use the `fetch` and `setHeaders` properties of the `RequestEvent` object within a `load` function. ```APIDOC ## `load` function example This example shows how to fetch data from an external API and set response headers using the `RequestEvent` object in a `load` function. ### File: `src/routes/blog/+page.js` ```javascript /** @type {import('./$types').PageLoad} */ export async function load({ fetch, setHeaders }) { const url = `https://cms.example.com/articles.json`; const response = await fetch(url); // Set response headers based on the fetched response setHeaders({ 'age': response.headers.get('age'), 'cache-control': response.headers.get('cache-control') }); return response.json(); } ``` ### Notes: - Setting the same header multiple times (even across different `load` functions) will result in an error. - The `set-cookie` header cannot be set using `setHeaders`; use the `cookies` API instead. ``` -------------------------------- ### Integrate svelte-preprocess in SvelteKit Source: https://svelte.dev/docs/kit/integrations/llms This example demonstrates how to install and configure `svelte-preprocess` in `svelte.config.js` for additional functionality like Pug, Babel, and global styles. It also notes the need to install corresponding libraries for preprocessors like Sass or Less. ```bash npm i -D svelte-preprocess ``` ```javascript // svelte.config.js import sveltePreprocess from 'svelte-preprocess'; /** @type {import('@sveltejs/kit').Config} */ const config = { preprocess: [sveltePreprocess()] }; export default config; ``` ```bash npm i -D sass ``` -------------------------------- ### Enable Yarn Berry and Install Dependencies Source: https://svelte.dev/docs/kit/faq/llms This code block shows how to enable Yarn Berry for your project and install all necessary dependencies. This is a crucial step for managing packages with Yarn 3. ```shell yarn set version berry yarn install ``` -------------------------------- ### Install and Configure svelte-preprocess Source: https://svelte.dev/docs/kit/integrations Instructions for installing and configuring svelte-preprocess in a SvelteKit project. This involves installing the package and adding it to the svelte.config.js, along with any necessary preprocessor libraries like sass or less. ```bash npm i -D svelte-preprocess # Example for SCSS support: npm i -D sass ``` -------------------------------- ### SvelteKit Server `handle` Hook Example Source: https://svelte.dev/docs/kit/hooks Demonstrates the `handle` hook in `src/hooks.server.js`, which intercepts incoming requests. It allows modification of responses or custom routing logic. This example shows how to return a custom response for paths starting with '/custom' or pass the request to the default handler. ```javascript import type { Handle } from '@sveltejs/kit'; export const handle: Handle = async ({ event, resolve }) => { if (event.url.pathname.startsWith('/custom')) { return new Response('custom response'); } const response = await resolve(event); return response; }; ``` -------------------------------- ### SvelteKit Load Function Example with Fetch and SetHeaders Source: https://svelte.dev/docs/kit/%40sveltejs-kit A SvelteKit load function example demonstrating how to use the enhanced fetch API to retrieve data from an external API and subsequently set response headers like 'age' and 'cache-control' based on the fetched response. It also shows how to return JSON data. ```javascript export async function load({ fetch, setHeaders }: { fetch: any; setHeaders: any }): Promise { const url = `https://cms.example.com/articles.json`; const response = await fetch(url); setHeaders({ age: response.headers.get('age'), 'cache-control': response.headers.get('cache-control') }); return response.json(); } ``` -------------------------------- ### Install OpenTelemetry Node.js Dependencies Source: https://svelte.dev/docs/kit/observability Installs necessary OpenTelemetry packages for Node.js applications, including SDK, auto-instrumentations, and OTLP trace exporter. These are required for collecting and exporting trace data. ```bash npm i @opentelemetry/sdk-node @opentelemetry/auto-instrumentations-node @opentelemetry/exporter-trace-otlp-proto import-in-the-middle ``` -------------------------------- ### Node.js: Spawn a Child Process with `child_process` Source: https://svelte.dev/docs/kit/configuration This Node.js example demonstrates spawning a child process using the `spawn` function from the `node:child_process` module. It captures stdout and stderr streams and listens for the 'close' event to get the exit code. This method is asynchronous and does not block the event loop. ```javascript import { spawn } from 'node:child_process'; import { once } from 'node:events'; const ls = spawn('ls', ['-lh', '/usr']); ls.stdout.on('data', (data) => { console.log(`stdout: ${data}`); }); ls.stderr.on('data', (data) => { console.error(`stderr: ${data}`); }); const [code] = await once(ls, 'close'); console.log(`child process exited with code ${code}`); ``` -------------------------------- ### Synchronous Reroute Example in SvelteKit Source: https://svelte.dev/docs/kit/hooks Demonstrates a synchronous implementation of the reroute hook in SvelteKit. This example uses a predefined mapping to translate incoming URLs to different route paths. It's suitable for static URL translations. ```javascript import type { Reroute } from '@sveltejs/kit'; const translated: Record = { '/en/about': '/en/about', '/de/ueber-uns': '/de/about', '/fr/a-propos': '/fr/about', }; export const reroute: Reroute = ({ url }) => { if (url.pathname in translated) { return translated[url.pathname]; } }; ``` -------------------------------- ### SvelteKit Load Function Example with Fetch and SetHeaders Source: https://svelte.dev/docs/kit/%40sveltejs-kit An example of a SvelteKit load function demonstrating how to use the `fetch` utility to make an HTTP request and `setHeaders` to add caching-related headers to the response. It fetches data from a JSON endpoint and sets 'age' and 'cache-control' headers based on the response. ```javascript export async function load({ fetch, setHeaders }) { const url = `https://cms.example.com/articles.json`; const response = await fetch(url); setHeaders({ age: response.headers.get('age'), 'cache-control': response.headers.get('cache-control') }); return response.json(); } ``` -------------------------------- ### SvelteKit Server Load Function Example (TypeScript) Source: https://svelte.dev/docs/kit/load Demonstrates a server load function in SvelteKit, typically used for accessing server-side resources like databases or environment variables. It returns a message string. ```typescript import type { PageServerLoad } from './$types'; export const load: PageServerLoad = async () => { return { serverMessage: 'hello from server load function' }; }; ``` -------------------------------- ### Asynchronous Reroute Example with Fetch in SvelteKit Source: https://svelte.dev/docs/kit/hooks Illustrates an asynchronous reroute hook in SvelteKit that utilizes the fetch API. This example shows how to query a special endpoint within the application to determine the correct route dynamically. It's useful when route decisions depend on external data or backend logic. ```javascript import type { Reroute } from '@sveltejs/kit'; export const reroute: Reroute = async ({ url, fetch }) => { // Prevent infinite loops by not rerouting API calls if (url.pathname === '/api/reroute') return; const api = new URL('/api/reroute', url); api.searchParams.set('pathname', url.pathname); const result = await fetch(api).then(r => r.json()); return result.pathname; }; ``` -------------------------------- ### Creating an API Endpoint with +server.js (GET) Source: https://svelte.dev/docs/kit/routing/llms Defines a server-side API route using +server.js with a GET handler. This example creates an endpoint '/api/random-number' that accepts 'min' and 'max' query parameters to generate a random number within the specified range. It uses SvelteKit's 'error' utility for input validation. ```javascript /// file: src/routes/api/random-number/+server.js import { error } from '@sveltejs/kit'; /** @type {import('./$types').RequestHandler} */ export function GET({ url }) { const min = Number(url.searchParams.get('min') ?? '0'); const max = Number(url.searchParams.get('max') ?? '1'); const d = max - min; if (isNaN(d) || d < 0) { error(400, 'min and max must be numbers, and min must be less than max'); } const random = min + Math.random() * d; return new Response(String(random)); } ``` -------------------------------- ### Install and Configure @sveltejs/enhanced-img Plugin Source: https://svelte.dev/docs/kit/images/llms Shows the npm command to install the @sveltejs/enhanced-img plugin and how to integrate it into your vite.config.js file. The plugin must be added before the sveltekit() plugin. ```bash npm i -D @sveltejs/enhanced-img ``` ```javascript import { sveltekit } from '@sveltejs/kit/vite'; import { enhancedImages } from '@sveltejs/enhanced-img'; import { defineConfig } from 'vite'; export default defineConfig({ plugins: [ enhancedImages(), // must come before the SvelteKit plugin sveltekit() ] }); ``` -------------------------------- ### Customize Focus Management with afterNavigate Hook in SvelteKit Source: https://svelte.dev/docs/kit/accessibility This example shows how to customize SvelteKit's default focus management after navigation using the `afterNavigate` lifecycle function. It illustrates focusing a specific element with the class 'focus-me' or nullifying focus if the element is not found, enhancing accessibility for keyboard and screen reader users. ```typescript import { afterNavigate } from '$app/navigation'; afterNavigate(() => { const to_focus = document.querySelector('.focus-me'); to_focus?.focus(); }); ``` -------------------------------- ### Prerender Page with Server Route Fetch Source: https://svelte.dev/docs/kit/page-options/llms This example shows a `+page.js` file that enables prerendering and fetches data from a server route. The server route (`my-server-route.json/+server.js`) will also be treated as prerenderable unless explicitly disabled. ```javascript /// file: +page.js export const prerender = true; /** @type {import('./$types').PageLoad} */ export async function load({ fetch }) { const res = await fetch('/my-server-route.json'); return await res.json(); } ``` -------------------------------- ### Deploy a Specific Route as an Individual Serverless Function Source: https://svelte.dev/docs/kit/adapter-vercel/llms This example demonstrates how to deploy a specific route as an individual serverless function by setting the `split` option to `true` within the route's `+page.js` file. This allows for granular control over function deployment. ```javascript /// file: about/+page.js /** @type {import('@sveltejs/adapter-vercel').Config} */ export const config = { split: true }; ``` -------------------------------- ### Initialize Database Connection in SvelteKit Server Hooks Source: https://svelte.dev/docs/kit/hooks/llms Demonstrates the `init` function in `src/hooks.server.js` for performing asynchronous initialization tasks, such as connecting to a database. This function runs once when the server starts. ```javascript // @errors: 2307 /// file: src/hooks.server.js import * as db from '$lib/server/database'; /** @type {import('@sveltejs/kit').ServerInit} */ export async function init() { await db.connect(); } ``` -------------------------------- ### Inline Asset Example with TypeScript in Svelte Source: https://svelte.dev/docs/kit/configuration Shows an example of importing and using an asset (favicon.png) in a Svelte component using TypeScript. Similar to the JavaScript example, this asset will be inlined as a base64 URL due to the Vite configuration. ```svelte ``` -------------------------------- ### Configure SvelteKit with adapter-node Source: https://svelte.dev/docs/kit/adapter-node/llms This snippet shows how to install and configure the adapter-node in your svelte.config.js file to generate a standalone Node.js server for your SvelteKit application. It requires installing the adapter as a dev dependency. ```javascript // @errors: 2307 /// file: svelte.config.js import adapter from '@sveltejs/adapter-node'; /** @type {import('@sveltejs/kit').Config} */ const config = { kit: { adapter: adapter() } }; export default config; ``` -------------------------------- ### SvelteKit Layout Server Load Function Example (TypeScript) Source: https://svelte.dev/docs/kit/load This TypeScript code defines a layout server load function for a blog section. It fetches summaries of all blog posts to be used across multiple pages within the blog layout. It depends on a database module for fetching post summaries. ```typescript import * as db from '$lib/server/database'; import type { LayoutServerLoad } from './$types'; export const load: LayoutServerLoad = async () => { return { posts: await db.getPostSummaries() }; }; ``` -------------------------------- ### SvelteKit Route Encoding Examples Source: https://svelte.dev/docs/kit/advanced-routing/llms Illustrates SvelteKit's hexadecimal and Unicode escape sequence formats for file system characters that cannot be used directly in routes. Includes examples for common special characters and emojis. ```svelte // Example for a smiley route using hexadecimal encoding // src/routes/smileys/[x+3a]-[x+29]/+page.svelte // Example for a route with an emoji using Unicode encoding // src/routes/[u+d83e][u+dd2a]/+page.svelte // Equivalent to: src/routes/🤪/+page.svelte // Example for encoding '.well-known' routes due to TypeScript limitations // src/routes/[x+2e]well-known/.../+page.svelte ``` -------------------------------- ### Install @sveltejs/enhanced-img Plugin Source: https://svelte.dev/docs/kit/images Command to install the @sveltejs/enhanced-img plugin as a development dependency. This plugin enhances Vite's image processing capabilities. ```bash npm i -D @sveltejs/enhanced-img ``` -------------------------------- ### Configure SvelteKit Node Adapter (JavaScript) Source: https://svelte.dev/docs/kit/adapter-node/llms Example configuration for the SvelteKit Node adapter in svelte.config.js. It demonstrates setting the output directory ('out'), enabling precompression ('precompress'), and configuring environment variable prefixes ('envPrefix'). ```javascript // @errors: 2307 /// file: svelte.config.js import adapter from '@sveltejs/adapter-node'; /** @type {import('@sveltejs/kit').Config} */ const config = { kit: { adapter: adapter({ // default options are shown out: 'build', precompress: true, envPrefix: '' }) } }; export default config; ``` -------------------------------- ### handleFetch Hook Implementation Source: https://svelte.dev/docs/kit/hooks This example demonstrates how to implement the handleFetch hook to add a 'cookie' header to requests targeting a specific domain. ```APIDOC ## POST /websites/svelte_dev_kit ### Description The `handleFetch` hook allows you to modify or replace the result of an `event.fetch` call that runs on the server (or during prerendering) inside an endpoint, `load`, `action`, `handle`, `handleError` or `reroute`. This specific implementation intercepts requests to `https://api.my-domain.com/` and adds the incoming 'cookie' header to the outgoing request. ### Method `POST` (This is inferred from the project path, actual method depends on usage) ### Endpoint `/websites/svelte_dev_kit` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body This endpoint does not explicitly define a request body in the provided documentation. The `handleFetch` hook operates on `Request` objects. ### Request Example ```json { "event": { ... }, "request": { "url": "https://api.my-domain.com/some/resource", "headers": { "cookie": "session_id=12345" } }, "fetch": "function" } ``` ### Response #### Success Response (200) - **Response** (Response) - The modified or original `Response` object from the `fetch` call. #### Response Example ```json { "status": 200, "ok": true, "headers": { ... }, "body": { ... } } ``` ``` -------------------------------- ### Configure Route Splitting with @sveltejs/adapter-vercel Source: https://svelte.dev/docs/kit/adapter-vercel This example demonstrates how to configure a specific route to be deployed as an individual serverless function by setting the `split` option to `true`. This allows for granular control over function deployment. ```javascript /** @type {import('@sveltejs/adapter-vercel').Config} */ export const config = { split: true }; ``` ```typescript import type { Config } from '@sveltejs/adapter-vercel'; export const config: Config = { split: true }; ``` -------------------------------- ### GET /websites/svelte_dev_kit/+server Source: https://svelte.dev/docs/kit/web-standards This endpoint demonstrates how to access incoming request headers and set custom response headers using the `json` function. ```APIDOC ## GET /websites/svelte_dev_kit/+server ### Description This endpoint retrieves the 'user-agent' header from the incoming request and returns it in a JSON response, along with a custom 'x-custom-header'. It also logs all request headers to the console. ### Method GET ### Endpoint /websites/svelte_dev_kit/+server ### Parameters #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **userAgent** (string | null) - The value of the 'user-agent' header from the request. - **x-custom-header** (string) - A custom header set on the response ('potato'). #### Response Example ```json { "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3" } ``` ``` -------------------------------- ### installPolyfills Source: https://svelte.dev/docs/kit/%40sveltejs-kit-node-polyfills/llms Installs global polyfills for web APIs such as `crypto` and `File` in a Node.js environment when using SvelteKit. ```APIDOC ## installPolyfills ### Description Make various web APIs available as globals: `crypto`, `File`. ### Method `function` ### Endpoint N/A (This is a function import) ### Parameters None ### Request Example ```js import { installPolyfills } from '@sveltejs/kit/node/polyfills'; installPolyfills(); ``` ### Response #### Success Response This function does not return a value, but makes APIs available globally. #### Response Example N/A ``` -------------------------------- ### Handling HTTP Methods in SvelteKit Routes Source: https://svelte.dev/docs/kit/routing Demonstrates how SvelteKit routes handle different HTTP methods. For GET requests, it returns the HTTP method, defaulting to 'GET'. HEAD requests are handled by the GET handler, taking precedence over the fallback. This is crucial for defining API endpoints alongside pages. ```javascript export function GET({ request }) { const method = request.method; return new Response(`Method is ${method}!`); } ``` -------------------------------- ### Using Custom Environment Variables (Shell) Source: https://svelte.dev/docs/kit/adapter-node/llms Example of running a SvelteKit Node.js application using custom environment variable prefixes. This shows how to set variables like HOST, PORT, and ORIGIN with the specified prefix. ```sh MY_CUSTOM_HOST=127.0.0.1 \ MY_CUSTOM_PORT=4000 \ MY_CUSTOM_ORIGIN=https://my.site \ node build ``` -------------------------------- ### Install Wrangler and Deploy to Cloudflare Source: https://svelte.dev/docs/kit/adapter-cloudflare-workers Commands to install the Wrangler CLI, log in to your Cloudflare account, build the SvelteKit application, and deploy it to Cloudflare Workers. ```bash npm i -D wrangler wrangler login wrangler deploy ``` -------------------------------- ### SvelteKit Load Function Example Source: https://svelte.dev/docs/kit/%40sveltejs-kit Demonstrates a basic SvelteKit load function that checks the current URL pathname. If the pathname is the root ('/'), it returns a 'Welcome!' message. Otherwise, it returns undefined. This function is useful for pre-rendering data or setting initial page states. ```javascript load({ untrack, url }) { // Untrack url.pathname so that path changes don't trigger a rerun if (untrack(() => url.pathname === '/')) { return { message: 'Welcome!' }; } } ``` -------------------------------- ### Request Handler Example Source: https://svelte.dev/docs/kit/routing Demonstrates a SvelteKit RequestHandler that extracts 'min' and 'max' query parameters, validates them, and returns a random number within the specified range. ```APIDOC ## POST /websites/svelte_dev_kit ### Description Handles incoming server requests, extracts 'min' and 'max' query parameters, validates them, and returns a random number within the specified range. If validation fails, it throws an HTTP error. ### Method GET ### Endpoint /websites/svelte_dev_kit ### Parameters #### Query Parameters - **min** (number) - Optional - The minimum value for the random number range. Defaults to '0'. - **max** (number) - Optional - The maximum value for the random number range. Defaults to '1'. ### Request Example ```json { "example": "No request body for GET requests" } ``` ### Response #### Success Response (200) - **body** (string) - A string representation of a random number within the specified range. #### Response Example ```json { "example": "0.75321" } ``` #### Error Response (400) - **message** (string) - Description of the error (e.g., 'min and max must be numbers, and min must be less than max'). #### Error Response Example ```json { "example": { "message": "min and max must be numbers, and min must be less than max" } } ``` ``` -------------------------------- ### Build and Run Node.js Server Source: https://svelte.dev/docs/kit/adapter-node Commands to build your SvelteKit application for production and then run the generated Node.js server. Assumes the output directory is 'build'. ```bash npm run build node build ``` -------------------------------- ### Server Initialization Options Source: https://svelte.dev/docs/kit/%40sveltejs-kit The `ServerInitOptions` interface provides configuration for server initialization. It includes environment variables and an optional `read` function to convert asset filenames into `ReadableStream`s, which is necessary for the `$app/server` `read` export to function. ```typescript env: Record; ``` ```typescript read?: (file: string) => MaybePromise; ``` -------------------------------- ### ServerInitOptions Interface Source: https://svelte.dev/docs/kit/%40sveltejs-kit Options provided during server initialization, including environment variables and a function to read assets. ```APIDOC ## ServerInitOptions Interface ### Description Options provided during server initialization. ### Fields #### `env` ```typescript env: Record; ``` A map of environment variables. #### `read` ```typescript read?: (file: string) => MaybePromise; ``` A function that turns an asset filename into a `ReadableStream`. Required for the `read` export from `$app/server` to work. ``` -------------------------------- ### Initialize Server with Database Connection (TypeScript) Source: https://svelte.dev/docs/kit/hooks This TypeScript code snippet demonstrates how to initialize a server in SvelteKit by connecting to a database using the `init` function. It imports a database module and calls its connect function asynchronously. This function runs once when the server is created or the app starts in the browser. ```typescript import * as import dbdb from '$lib/server/database'; /** @type {import('@sveltejs/kit').ServerInit} */ export async function function init(): Promise @type{import('@sveltejs/kit').ServerInit} init() { await import dbdb.connect(); } ``` ```typescript import * as import dbdb from '$lib/server/database'; import type { type ServerInit = () => MaybePromise The init will be invoked before the server responds to its first request @since2.10.0 ServerInit } from '@sveltejs/kit'; export const const init: ServerInitinit: type ServerInit = () => MaybePromise The init will be invoked before the server responds to its first request @since2.10.0 ServerInit = async () => { await import dbdb.connect(); }; ``` -------------------------------- ### Example Usage of Remote Query with Schema Validation Source: https://svelte.dev/docs/kit/hooks This example demonstrates creating a remote query function 'getTodo' using SvelteKit's query utility and Valibot for schema validation. It expects a string argument, and if called with a non-string, it will trigger the handleValidationError hook. ```javascript import * as v from 'valibot'; import { query } from '$app/server'; export const getTodo = query(v.string(), async (id: string) => { // Implementation to fetch todo by id }); ``` -------------------------------- ### Redirect Helper Usage Source: https://svelte.dev/docs/kit/load Demonstrates how to use the `redirect` helper function from '@sveltejs/kit' to redirect users. It explains the parameters for status codes and location, and provides common status code examples like 303, 307, and 308. ```APIDOC ## POST /redirect ### Description This endpoint demonstrates the usage of the `redirect` helper function to redirect users to a new location with a specified HTTP status code. ### Method POST ### Endpoint /redirect ### Parameters #### Query Parameters - **status** (300-308) - Required - The HTTP status code for the redirect. - **location** (string | URL) - Required - The URL or path to redirect to. ### Request Body This endpoint does not require a request body. ### Request Example ```javascript // Example usage within a SvelteKit load function or server route import { redirect } from '@sveltejs/kit'; // To redirect to login page with a temporary redirect status redirect(307, '/login'); // To redirect after a form submission with a 'See Other' status redirect(303, '/success'); ``` ### Response #### Success Response (300-308) - **status** (number) - The HTTP status code indicating a redirect. - **headers** (object) - Contains the 'Location' header with the redirect URL. #### Response Example ```json { "status": 307, "headers": { "location": "/login" } } ``` ### Error Handling - **Error**: Throws an error if the provided status code is invalid or outside the 300-308 range. ``` -------------------------------- ### Get Context in Svelte Page (JavaScript) Source: https://svelte.dev/docs/kit/state-management Shows how to retrieve context data within a Svelte page component using `getContext`. This example retrieves the 'user' context, which is expected to be a function returning user information, and displays the user's name. ```javascript

Welcome {user().name}

``` -------------------------------- ### Rest Parameter Capture Example in SvelteKit Source: https://svelte.dev/docs/kit/advanced-routing This example demonstrates how SvelteKit captures URL segments into parameters when using rest syntax. A request to a URL matching the rest parameter route will result in an object where each defined parameter, including the rest parameter, is assigned its corresponding value from the URL. The 'file' parameter here aggregates multiple segments. ```javascript { org: 'sveltejs', repo: 'kit', branch: 'main', file: 'documentation/docs/04-advanced-routing.md' } ``` -------------------------------- ### SvelteKit Manual Typing for Page and Layout Props (Older Versions) Source: https://svelte.dev/docs/kit/routing/llms These JavaScript examples illustrate how to manually type the props for SvelteKit page and layout components in older versions or when explicit typing is preferred. The first example shows typing `data` and `form` props for a page, while the second demonstrates typing `data` and `children` for a layout. These manual types are now often handled automatically by Svelte's IDE tooling. ```javascript /// file: +page.svelte /** @type {{ data: import('./$types').PageData, form: import('./$types').ActionData }} */ let { data, form } = $props(); ``` ```javascript /// file: +layout.svelte /** @type {{ data: import('./$types').LayoutData, children: Snippet }} */ let { data, children } = $props(); ``` -------------------------------- ### Configure SvelteKit with Vercel Adapter Source: https://svelte.dev/docs/kit/adapter-vercel/llms This snippet shows how to install and configure the `@sveltejs/adapter-vercel` in your `svelte.config.js` file. It sets up the adapter to handle Vercel-specific deployment options. ```javascript /// file: svelte.config.js import adapter from '@sveltejs/adapter-vercel'; /** @type {import('@sveltejs/kit').Config} */ const config = { kit: { adapter: adapter({ // see below for options that can be set here }) } }; export default config; ``` -------------------------------- ### SvelteKit Load Function Implementation with Promises and Fetch Source: https://svelte.dev/docs/kit/load Demonstrates a SvelteKit `load` function implementation. It shows how to define manual and fetched promises, including handling potential rejections and utilizing the enhanced server-side fetch. ```typescript import type { MaybePromise } from "@sveltejs/kit"; import type * as Kit from "./$types"; type PageServerLoad = (event: Kit.ServerLoadEvent, Record, string | null>) => MaybePromise>; export const load: PageServerLoad = async ({ fetch }) => { const ok_manual: Promise = new Promise(() => {}); ok_manual.catch(() => {}); const ok_fetch: Promise = fetch('/fetch/that/could/fail'); const dangerous_unhandled: Promise = new Promise(() => {}); dangerous_unhandled.catch(() => {}); return { ok_manual, ok_fetch, dangerous_unhandled }; }; ``` -------------------------------- ### Executing Commands with exec Source: https://svelte.dev/docs/kit/configuration Shows how to execute a command using `exec` and receive the output via a callback. ```APIDOC ## GET /exec ### Description Executes a command in a shell and captures its output. ### Method GET ### Endpoint /exec ### Parameters #### Query Parameters - **command** (string) - Required - The command to execute. ### Request Example ```json { "command": "echo 'Hello World'" } ``` ### Response #### Success Response (200) - **stdout** (string) - The standard output from the command. - **stderr** (string) - The standard error from the command. #### Response Example ```json { "stdout": "Hello World\n", "stderr": "" } ``` ``` -------------------------------- ### GET /api/posts/[slug] Source: https://svelte.dev/docs/kit/remote-functions/llms Fetches a single blog post by its slug. The slug is validated using Valibot. ```APIDOC ## GET /api/posts/[slug] ### Description Fetches a single blog post by its slug. This endpoint is exposed via the `getPost` query function. ### Method GET ### Endpoint `/api/posts/[slug]` ### Parameters #### Path Parameters - **slug** (string) - Required - The unique identifier for the blog post. #### Query Parameters None #### Request Body None ### Request Example None (This is a GET request, typically no body is sent) ### Response #### Success Response (200) - **post** (object) - An object containing the post data, including `title` and `content`. #### Response Example ```json { "title": "My Awesome Post", "content": "

Hello World

This is the content.

" } ``` ``` -------------------------------- ### Accessing Stores in Sapper and SvelteKit Source: https://svelte.dev/docs/kit/migrating Demonstrates how to access application stores in Sapper and the equivalent in SvelteKit. SvelteKit simplifies store access by allowing direct imports from '$app/stores'. ```javascript import { stores } from '@sapper/app'; const { preloading, page, session } = stores(); ``` ```javascript import { navigating, page } from '$app/stores'; // For Svelte 5 and SvelteKit 2.12+, consider '$app/state' ``` -------------------------------- ### ServerInit Hook Source: https://svelte.dev/docs/kit/%40sveltejs-kit The `init` hook is invoked before the server responds to its first request. Available since version 2.10.0. ```APIDOC ## ServerInit Hook ### Description Invoked before the server responds to its first request. ### Type Definition ```typescript type ServerInit = () => MaybePromise; ``` ### Availability Available since 2.10.0 ``` -------------------------------- ### GitHub Actions Workflow for SvelteKit Deployment Source: https://svelte.dev/docs/kit/adapter-static/llms This YAML file defines a GitHub Actions workflow to build and deploy a SvelteKit project to GitHub Pages. It includes steps for checking out code, setting up Node.js, installing dependencies using npm, building the SvelteKit application, and uploading the build artifacts. The deployment job then uses these artifacts to deploy the site. ```yaml name: Deploy to GitHub Pages on: push: branches: 'main' jobs: build_site: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v4 # If you're using pnpm, add this step then change the commands and cache key below to use `pnpm` # - name: Install pnpm # uses: pnpm/action-setup@v3 # with: # version: 8 - name: Install Node.js uses: actions/setup-node@v4 with: node-version: 20 cache: npm - name: Install dependencies run: npm i - name: build env: BASE_PATH: '/${{ github.event.repository.name }}' run: | npm run build - name: Upload Artifacts uses: actions/upload-pages-artifact@v3 with: # this should match the `pages` option in your adapter-static options path: 'build/' deploy: needs: build_site runs-on: ubuntu-latest permissions: pages: write id-token: write environment: name: github-pages url: ${{ steps.deployment.outputs.page_url }} steps: - name: Deploy id: deployment uses: actions/deploy-pages@v4 ``` -------------------------------- ### Initialize Sentry in SvelteKit (Client-Side) Source: https://svelte.dev/docs/kit/hooks Initializes the Sentry SDK for client-side error tracking in a SvelteKit application. This setup is typically done in `src/hooks.client.js`. ```javascript import * as Sentry from '@sentry/sveltekit'; Sentry.init({ // Configuration options for Sentry // ... }); ``` -------------------------------- ### Install and Configure Cloudflare Workers Adapter Source: https://svelte.dev/docs/kit/adapter-cloudflare-workers Installs the adapter and configures it within the svelte.config.js file. This is the primary step for enabling Cloudflare Workers deployment. ```javascript import adapter from '@sveltejs/adapter-cloudflare-workers'; /** @type {import('@sveltejs/kit').Config} */ const config = { kit: { adapter: adapter({ // see below for options that can be set here }) } }; export default config; ``` -------------------------------- ### Install Polyfills for Web APIs in Node.js with SvelteKit Source: https://svelte.dev/docs/kit/%40sveltejs-kit-node-polyfills The `installPolyfills` function from '@sveltejs/kit/node/polyfills' makes common web APIs such as `crypto` and `File` available as global variables. This is essential for running web-centric code in a Node.js environment. No external dependencies are required beyond SvelteKit itself. ```typescript import { installPolyfills } from '@sveltejs/kit/node/polyfills'; installPolyfills(); ``` -------------------------------- ### Create Svelte App with Yarn 3 Source: https://svelte.dev/docs/kit/faq/llms This snippet demonstrates the initial steps to create a new Svelte application using Yarn 3 and navigate into the project directory. It assumes Yarn 3 is already installed. ```shell yarn create svelte myapp cd myapp ``` -------------------------------- ### Accessing Sapper Stores Source: https://svelte.dev/docs/kit/migrating/llms Demonstrates how to import and access stores like `preloading`, `page`, and `session` in Sapper using '@sapper/app'. This is contrasted with SvelteKit's approach. ```javascript // @filename: ambient.d.ts declare module '@sapper/app'; // @filename: index.js // ---cut--- import { stores } from '@sapper/app'; const { preloading, page, session } = stores(); ``` -------------------------------- ### Configure SvelteKit with adapter-netlify (Standard) Source: https://svelte.dev/docs/kit/adapter-netlify This snippet shows how to configure your `svelte.config.js` to use the `adapter-netlify` for standard Node.js functions. It includes installing the adapter and setting it within the `kit.adapter` configuration. ```javascript import adapter from '@sveltejs/adapter-netlify'; /** @type {import('@sveltejs/kit').Config} */ const config = { kit: { // default options are shown adapter: adapter({ // if true, will create a Netlify Edge Function rather // than using standard Node-based functions edge: false, // if true, will split your app into multiple functions // instead of creating a single one for the entire app. // if `edge` is true, this option cannot be used split: false }) } }; export default config; ``` -------------------------------- ### Enable CSS Preprocessors with vitePreprocess Source: https://svelte.dev/docs/kit/integrations/llms This example illustrates how to enable CSS preprocessors like PostCSS, SCSS, Less, Stylus, and SugarSS within `