### Basic Spiceflow Application Setup Source: https://context7_llms This snippet demonstrates the basic setup of a Spiceflow application, creating a new instance and chaining route definitions for GET and POST requests. It shows how to return a simple string or process a JSON request body. ```ts import { Spiceflow } from 'spiceflow' const app = new Spiceflow() .get('/hello', () => 'Hello, World!') .post('/echo', async ({ request }) => { const body = await request.json() return { echo: body } }) app.listen(3000) ``` -------------------------------- ### Generate Spiceflow RPC Client in TypeScript Source: https://context7_llms Demonstrates how to define a Spiceflow application with different HTTP methods and routes (GET, POST, streaming) and then generate and use an RPC client for interacting with the defined API. Shows examples of making GET, POST, and streaming requests using the generated client. ```typescript import { createSpiceflowClient } from 'spiceflow/client' import { Spiceflow } from 'spiceflow' import { z } from 'zod' // Define the app with multiple routes and features const app = new Spiceflow() .get('/hello/:id', ({ params }) => `Hello, ${params.id}!`) .post( '/users', async ({ request }) => { const body = await request.json() // here body has type { name?: string, email?: string } return `Created user: ${body.name}` }, { body: z.object({ name: z.string().optional(), email: z.string().email().optional(), }), }, ) .get('/stream', async function* () { yield 'Start' await new Promise((resolve) => setTimeout(resolve, 1000)) yield 'Middle' await new Promise((resolve) => setTimeout(resolve, 1000)) yield 'End' }) // Create the client const client = createSpiceflowClient('http://localhost:3000') // Example usage of the client async function exampleUsage() { // GET request const { data: helloData, error: helloError } = await client .hello({ id: 'World' }) .get() if (helloError) { console.error('Error fetching hello:', helloError) } else { console.log('Hello response:', helloData) } // POST request const { data: userData, error: userError } = await client.users.post({ name: 'John Doe', email: 'john.doe@example.com', }) if (userError) { console.error('Error creating user:', userError) } else { console.log('User creation response:', userData) } // Async generator (streaming) request const { data: streamData, error: streamError } = await client.stream.get() if (streamError) { console.error('Error fetching stream:', streamError) } else { for await (const chunk of streamData) { console.log('Stream chunk:', chunk) } } } ``` -------------------------------- ### Installing Spiceflow and Zod Source: https://context7_llms This command installs the Spiceflow framework and the Zod library, which is used for schema-based validation, using npm. ```bash npm install spiceflow zod ``` -------------------------------- ### Handling GET Request with Body, Response, and Params Schemas Source: https://context7_llms This example demonstrates defining a GET route that includes Zod schemas for the request body, response payload, and URL parameters. It shows how to access typed request body and parameters and return a response that conforms to the specified schema. ```ts import { z } from 'zod' import { Spiceflow } from 'spiceflow' new Spiceflow().get( '/users/:id', ({ request, params }) => { const typedJson = await request.json() // this body will have the correct type return { id: Number(params.id), name: typedJson.name } }, { body: z.object({ name: z.string(), }), response: z.object({ id: z.number(), name: z.string(), }), params: z.object({ id: z.string(), }), }, ) ``` -------------------------------- ### Incorrect Spiceflow Application Setup (Loses Type Safety) Source: https://context7_llms This example illustrates an incorrect way to define routes in Spiceflow by declaring the app instance separately and adding routes afterwards. This approach breaks the type safety provided by the framework's chaining mechanism. ```ts // This is an example of what NOT to do when using Spiceflow import { Spiceflow } from 'spiceflow' // DO NOT declare the app separately and add routes later const app = new Spiceflow() // Do NOT do this! Adding routes separately like this will lose type safety app.get('/hello', () => 'Hello, World!') app.post('/echo', async ({ request }) => { const body = await request.json() return body }) ``` -------------------------------- ### Handling Spiceflow Client Errors and Responses (TypeScript) Source: https://context7_llms Shows how to initialize a Spiceflow app with different endpoint behaviors (throwing errors, returning 401, returning 200) and how the client receives these as either "error" or "data" properties. Includes example client calls and logging. ```ts import { Spiceflow } from 'spiceflow' import { createSpiceflowClient } from 'spiceflow/client' const app = new Spiceflow() .get('/error', () => { throw new Error('Something went wrong') }) .get('/unauthorized', () => { return new Response('Unauthorized access', { status: 401 }) }) .get('/success', () => { throw new Response('Success message', { status: 200 }) return '' }) const client = createSpiceflowClient('http://localhost:3000') async function handleErrors() { const errorResponse = await client.error.get() console.log('Calling error endpoint...') // Logs: Error occurred: Something went wrong if (errorResponse.error) { console.error('Error occurred:', errorResponse.error) } const unauthorizedResponse = await client.unauthorized.get() console.log('Calling unauthorized endpoint...') // Logs: Unauthorized: Unauthorized access (Status: 401) if (unauthorizedResponse.error) { console.error('Unauthorized:', unauthorizedResponse.error) } const successResponse = await client.success.get() console.log('Calling success endpoint...') // Logs: Success: Success message if (successResponse.data) { console.log('Success:', successResponse.data) } } ``` -------------------------------- ### Using Spiceflow Client Server-Side (TypeScript) Source: https://context7_llms Demonstrates creating a Spiceflow client by passing the app instance directly instead of a URL. This enables programmatic interaction with endpoints without network calls. The example shows fetching and saving the OpenAPI schema. ```tsx import { Spiceflow } from 'spiceflow' import { createSpiceflowClient } from 'spiceflow/client' import { openapi } from 'spiceflow/openapi' import { writeFile } from 'node:fs/promises' const app = new Spiceflow() .use(openapi({ path: '/openapi' })) .get('/users', () => [ { id: 1, name: 'John' }, { id: 2, name: 'Jane' }, ]) .post('/users', ({ request }) => request.json()) // Create client by passing app instance directly const client = createSpiceflowClient(app) // Get OpenAPI schema and write to disk const { data } = await client.openapi.get() await writeFile('openapi.json', JSON.stringify(data, null, 2)) console.log('OpenAPI schema saved to openapi.json') ``` -------------------------------- ### Using Fern SDK with Streaming and Standard Requests (TypeScript) Source: https://context7_llms Initializes a Fern-generated TypeScript SDK client and demonstrates how to consume data from a streaming endpoint using an async iterator and how to make a standard GET request. ```typescript import { ExampleSdkClient } from './sdk-typescript' const sdk = new ExampleSdkClient({ environment: 'http://localhost:3000', }) // Get stream data const stream = await sdk.getStream() for await (const data of stream) { console.log('Stream data:', data) } // Simple GET request const response = await sdk.getUsers() console.log('Users:', response) ``` -------------------------------- ### Implement Streaming with Async Generators in Spiceflow (TypeScript) Source: https://context7_llms Explains how to create server-sent events (SSE) endpoints using async generators in Spiceflow. The example defines a GET route that yields data chunks over time and shows how to consume this stream using the generated RPC client. ```typescript import { Spiceflow } from 'spiceflow' const app = new Spiceflow().get('/sseStream', async function* () { yield { message: 'Start' } await new Promise((resolve) => setTimeout(resolve, 1000)) yield { message: 'Middle' } await new Promise((resolve) => setTimeout(resolve, 1000)) yield { message: 'End' } }) // Server-Sent Events (SSE) format // The server will send events in the following format: // data: {"message":"Start"} // data: {"message":"Middle"} // data: {"message":"End"} // Example response output: // data: {"message":"Start"} // data: {"message":"Middle"} // data: {"message":"End"} // Client usage example with RPC client import { createSpiceflowClient } from 'spiceflow/client' const client = createSpiceflowClient('http://localhost:3000') async function fetchStream() { const response = await client.sseStream.get() if (response.error) { console.error('Error fetching stream:', response.error) } else { for await (const chunk of response.data) { console.log('Stream chunk:', chunk) } } } fetchStream() ``` -------------------------------- ### Adding CORS Headers with Spiceflow Middleware (TypeScript) Source: https://context7_llms Provides a concise example of applying the cors middleware to a Spiceflow app using the .use() method. This automatically adds necessary CORS headers to responses. ```ts import { cors } from 'spiceflow/cors' import { Spiceflow } from 'spiceflow' const app = new Spiceflow().use(cors()).get('/hello', () => 'Hello, World!') ``` -------------------------------- ### Non-Blocking Authentication Middleware with Spiceflow (TypeScript) Source: https://context7_llms This example shows how to implement non-blocking authentication in Spiceflow using `Promise.withResolvers()`. It allows public routes to respond immediately while authentication for protected routes is fetched asynchronously in the background, improving performance for public access. ```TypeScript import { Spiceflow } from 'spiceflow' new Spiceflow() .state('userId', Promise.resolve('')) .state('userEmail', Promise.resolve('')) .use(async ({ request, state }, next) => { const sessionKey = request.headers.get('sessionKey') const userIdPromise = Promise.withResolvers() const userEmailPromise = Promise.withResolvers() state.userId = userIdPromise.promise state.userEmail = userEmailPromise.promise async function resolveUser() { if (!sessionKey) { userIdPromise.resolve('') userEmailPromise.resolve('') return } const user = await getUser(sessionKey) userIdPromise.resolve(user?.id ?? '') userEmailPromise.resolve(user?.email ?? '') } resolveUser() }) .get('/protected', async ({ state }) => { const userId = await state.userId if (!userId) throw new Error('Not authenticated') return { message: 'Protected data' } }) .get('/public', () => ({ message: 'Public data' })) async function getUser(sessionKey: string) { await new Promise((resolve) => setTimeout(resolve, 100)) return sessionKey === 'valid' ? { id: '123', email: 'user@example.com' } : null } ``` -------------------------------- ### Passing State and Cloudflare Env Bindings in Spiceflow - TypeScript Source: https://context7_llms This example shows how to define and pass state, such as Cloudflare environment bindings, to Spiceflow route handlers. It uses the `.state()` method to declare the state type and accesses the state object within route handlers via the second argument of the `handle` method. ```tsx import { Spiceflow } from 'spiceflow' import { z } from 'zod' interface Env { KV: KVNamespace QUEUE: Queue SECRET: string } const app = new Spiceflow() .state('env', null as Env | null) .get('/kv/:key', async ({ params, state }) => { const value = await state.env!.KV.get(params.key) return { key: params.key, value } }) .post('/queue', async ({ request, state }) => { const body = await request.json() await state.env!.QUEUE.send(body) return { success: true, message: 'Added to queue' } }) export default { fetch(request: Request, env: Env, ctx: ExecutionContext) { // Pass the env bindings to the app return app.handle(request, { env }) } } ``` -------------------------------- ### Generating OpenAPI Spec for Fern Docs/SDKs with Spiceflow - TypeScript Source: https://context7_llms This script demonstrates how to use the Spiceflow openapi plugin to fetch the generated OpenAPI specification from a running Spiceflow app. It then writes the specification to a local `openapi.yml` file, which can be used as input for tools like Fern to generate API documentation and SDKs. ```ts import fs from 'fs' import path from 'path' import yaml from 'js-yaml' import { Spiceflow } from 'spiceflow' import { openapi } from 'spiceflow/openapi' import { createSpiceflowClient } from 'spiceflow/client' const app = new Spiceflow() .use(openapi({ path: '/openapi' })) .get('/hello', () => 'Hello World') async function main() { console.log('Creating Spiceflow client...') const client = createSpiceflowClient(app) console.log('Fetching OpenAPI spec...') const { data: openapiJson, error } = await client.openapi.get() if (error) { console.error('Failed to fetch OpenAPI spec:', error) throw error } const outputPath = path.resolve('./openapi.yml') console.log('Writing OpenAPI spec to', outputPath) fs.writeFileSync( outputPath, yaml.dump(openapiJson, { indent: 2, lineWidth: -1, }), ) console.log('Successfully wrote OpenAPI spec') } main().catch((e) => { console.error('Failed to generate OpenAPI spec:', e) process.exit(1) }) ``` -------------------------------- ### Integrating Spiceflow with Model Context Protocol (MCP) - TypeScript Source: https://context7_llms This snippet demonstrates how to mount the Spiceflow MCP plugin to expose API routes as AI tools and resources. It also shows how to use the MCP client SDK to connect to the plugin endpoint and programmatically list available tools/resources and call a specific tool. ```tsx // Import the MCP plugin and client import { mcp } from 'spiceflow/mcp' import { Client } from '@modelcontextprotocol/sdk/client/index.js' import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js' import { Spiceflow } from 'spiceflow' import { ListToolsResultSchema, CallToolResultSchema, ListResourcesResultSchema, } from '@modelcontextprotocol/sdk/types.js' // Create a new app with some example routes const app = new Spiceflow() // Mount the MCP plugin at /mcp (default path) .use(mcp()) // These routes will be available as tools .get('/hello', () => 'Hello World') .get('/users/:id', ({ params }) => ({ id: params.id })) .post('/echo', async ({ request }) => { const body = await request.json() return body }) // Start the server app.listen(3000) // Example client usage: const transport = new SSEClientTransport(new URL('http://localhost:3000/mcp')) const client = new Client( { name: 'example-client', version: '1.0.0' }, { capabilities: {} }, ) await client.connect(transport) // List available tools const tools = await client.request( { method: 'tools/list' }, ListToolsResultSchema, ) // Call a tool const result = await client.request( { method: 'tools/call', params: { name: 'GET /hello', arguments: {}, }, }, CallToolResultSchema, ) // List available resources (only GET /hello is exposed since it has no params) const resources = await client.request( { method: 'resources/list' }, ListResourcesResultSchema, ) ``` -------------------------------- ### Mount Spiceflow Sub-Apps in TypeScript Source: https://context7_llms Illustrates how to integrate one Spiceflow application (a sub-app) into another main application using the `.use()` method. This allows for modular organization of routes and features. ```typescript import { Spiceflow } from 'spiceflow' import { z } from 'zod' const mainApp = new Spiceflow() .post( '/users', async ({ request }) => `Created user: ${(await request.json()).name}`, { body: z.object({ name: z.string(), }), }, ) .use(new Spiceflow().get('/', () => 'Users list')) ``` -------------------------------- ### Mermaid Diagram of MCP Architecture Source: https://modelcontextprotocol.io/ This Mermaid flowchart illustrates the general client-server architecture of the Model Context Protocol (MCP), showing how a Host with an MCP Client connects to multiple MCP Servers, which in turn access Local Data Sources or Remote Services. ```Mermaid flowchart LR\n subgraph \"Your Computer\"\n Host[\"Host with MCP Client\\n(Claude, IDEs, Tools)\"\]\n S1[\"MCP Server A\"]\n S2[\"MCP Server B\"]\n S3[\"MCP Server C\"]\n Host \u003c--\u003e|\"MCP Protocol\"| S1\n Host \u003c--\u003e|\"MCP Protocol\"| S2\n Host \u003c--\u003e|\"MCP Protocol\"| S3\n S1 \u003c--\u003e D1[(\"Local\\nData Source A\")]\n S2 \u003c--\u003e D2[(\"Local\\nData Source B\")]\n end\n subgraph \"Internet\"\n S3 \u003c--\u003e|\"Web APIs\"| D3[(\"Remote\\nService C\")]\n end ``` -------------------------------- ### Mermaid Diagram: General Architecture Source: https://modelcontextprotocol.io/ This Mermaid diagram illustrates the general client-server architecture of the Model Context Protocol (MCP). It shows how a Host application with an MCP Client connects to multiple MCP Servers, which in turn access Local Data Sources or Remote Services. ```Mermaid flowchart LR\n subgraph \"Your Computer\"\n Host[\"Host with MCP Client\n(Claude, IDEs, Tools)\"]\n S1[\"MCP Server A\"]\n S2[\"MCP Server B\"]\n S3[\"MCP Server C\"]\n Host \u003c--\u003e|\"MCP Protocol\"| S1\n Host \u003c--\u003e|\"MCP Protocol\"| S2\n Host \u003c--\u003e|\"MCP Protocol\"| S3\n S1 \u003c--\u003e D1[(\"Local\nData Source A\")]\n S2 \u003c--\u003e D2[(\"Local\nData Source B\")]\n end\n subgraph \"Internet\"\n S3 \u003c--\u003e|\"Web APIs\"| D3[(\"Remote\nService C\")]\n end ``` -------------------------------- ### Initialize Dark Mode - JavaScript Source: https://modelcontextprotocol.io/ Checks local storage and user preferences to set the initial dark mode state for the document element on page load. It prioritizes local storage settings over the user's system preference. ```javascript try { if (localStorage.isDarkMode === 'true') { document.documentElement.classList.add('dark'); } else if (localStorage.isDarkMode === 'false') { document.documentElement.classList.remove('dark'); } else if ((true && !('isDarkMode' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches) || false) { document.documentElement.classList.add('dark'); } else { document.documentElement.classList.remove('dark'); } } catch (_) {} ``` -------------------------------- ### MDX Content Wrapper (JSX) Source: https://modelcontextprotocol.io/ This function serves as a wrapper for the generated MDX content. It optionally applies a layout component (`MDXLayout`) before rendering the main content. ```JSX function MDXContent(props = {}) { const {wrapper: MDXLayout} = { ..._provideComponents(), ...props.components }; return MDXLayout ? _jsx(MDXLayout, { ...props, children: _jsx(_createMdxContent, { ...props }) }) : _createMdxContent(props); } ``` -------------------------------- ### Define Color and Layout Variables - CSS Source: https://modelcontextprotocol.io/ Defines a comprehensive set of CSS variables for primary colors, background colors, and grayscale shades within the :root selector. It also includes basic layout styles for a feature support matrix table wrapper. ```css :root { --primary: 9 9 11; --primary-light: 250 250 250; --primary-dark: 9 9 11; --background-light: 255 255 255; --background-dark: 14 14 16; --gray-50: 243 243 243; --gray-100: 238 238 238; --gray-200: 222 222 222; --gray-300: 206 206 206; --gray-400: 158 158 158; --gray-500: 112 112 112; --gray-600: 80 80 80; --gray-700: 62 62 62; --gray-800: 37 37 37; --gray-900: 23 23 23; --gray-950: 10 10 10; } #feature-support-matrix-wrapper { overflow-x: auto; } #feature-support-matrix-wrapper table { min-width: 800px; } ``` -------------------------------- ### Generating Spiceflow OpenAPI Schema Programmatically (TypeScript) Source: https://context7_llms Demonstrates integrating the openapi middleware into a Spiceflow app. It shows how to define endpoint schemas using Zod and how to generate the OpenAPI JSON by creating a virtual Request and handling it with the app instance. ```ts import { openapi } from 'spiceflow/openapi' import { Spiceflow } from 'spiceflow' import { z } from 'zod' const app = new Spiceflow() .use(openapi({ path: '/openapi.json' })) .get('/hello', () => 'Hello, World!', { query: z.object({ name: z.string(), age: z.number(), }), response: z.string(), }) .post( '/user', () => { return new Response('Hello, World!') }, { body: z.object({ name: z.string(), email: z.string().email(), }), }, ) const openapiSchema = await ( await app.handle(new Request('http://localhost:3000/openapi.json')) ).json() ``` -------------------------------- ### Rendering MDX Content with React/JSX in JavaScript Source: https://modelcontextprotocol.io/ This JavaScript code defines functions used to render MDX content, likely within a React or similar JSX environment. It handles providing components and optionally wrapping the content with a layout component. ```JavaScript "use strict";\nconst {jsx: _jsx} = arguments[0];\nconst {useMDXComponents: _provideComponents} = arguments[0];\nfunction _createMdxContent(props) {\n const _components = {\n p: "p",\n ..._provideComponents(),\n ...props.components\n };\n return _jsx(_components.p, {\n children: "Get started with the Model Context Protocol (MCP)"\n });\n}\nfunction MDXContent(props = {}) {\n const {wrapper: MDXLayout} = {\n ..._provideComponents(),\n ...props.components\n };\n return MDXLayout ? _jsx(MDXLayout, {\n ...props,\n children: _jsx(_createMdxContent, {\n ...props\n })\n }) : _createMdxContent(props);\n}\nreturn {\n default: MDXContent\n};\n ``` -------------------------------- ### Compiled MDX JavaScript Source Source: https://modelcontextprotocol.io/ This snippet is the JavaScript code generated by compiling an MDX file. It sets up necessary components and functions for rendering the MDX content within a React or similar environment. ```javascript "use strict";\nconst {Fragment: \_Fragment, jsx: \_jsx, jsxs: \_jsxs} = arguments[0];\nconst {useMDXComponents: \_provideComponents} = arguments[0];\nfunction \_createMdxContent(props) {\n const \_components = {\n a: \"a\",\n li: \"li\",\n p: \"p\",\n strong: \"strong\",\n ul: \"ul\",\n ...\_provideComponents(),\n ...props.components\n }, {Card, CardGroup, Heading, Mermaid, Note} = \_components;\n if (!Card) \_missingMdxReference(\"Card\", true);\n if (!CardGroup) \_missingMdxReference(\"CardGroup\", true);\n if (!Heading) \_missingMdxReference(\"Heading\", true);\n if (!Mermaid) \_missingMdxReference(\"Mermaid\", true);\n if (!Note) \_missingMdxReference(\"Note\", true);\n return \_jsxs(\_Fragment, {\n children: [\_jsxs(Note, {\n children: [\"C# SDK released! Check out \", \_jsx(\_components.a, {\n href: \" ``` -------------------------------- ### Add Middleware to Spiceflow App in TypeScript Source: https://context7_llms Shows how to add middleware to a Spiceflow application using the `.use()` method. The middleware function is executed for incoming requests before route handlers, allowing for tasks like logging or authentication. ```typescript import { Spiceflow } from 'spiceflow' new Spiceflow().use(({ request }) => { console.log(`Received ${request.method} request to ${request.url}`) }) ``` -------------------------------- ### Handle Missing MDX References (JS) Source: https://modelcontextprotocol.io/ This utility function is called when an expected MDX component or object reference is not found. It throws an error indicating the missing reference. ```JavaScript function _missingMdxReference(id, component) { throw new Error("Expected " + (component ? "component" : "object") + " `" + id + "` to be defined: you likely forgot to import, pass, or provide it."); } ``` -------------------------------- ### Set Base Path for Spiceflow App in TypeScript Source: https://context7_llms Shows how to configure a base path for all routes within a Spiceflow application using the `basePath` option in the constructor. All defined routes will be prefixed with this path. ```typescript import { Spiceflow } from 'spiceflow' const app = new Spiceflow({ basePath: '/api/v1' }) app.get('/hello', () => 'Hello') // Accessible at /api/v1/hello ``` -------------------------------- ### Generate MDX Content (JSX) Source: https://modelcontextprotocol.io/ This function generates the main content of the MDX page using JSX components. It constructs a list of links related to the Model Context Protocol discussions and support. ```JSX function _createMdxContent(props) { const _components = { a: "a", li: "li", ul: "ul", ...props.components }; return _jsxs(_components.ul, { children: ["\n", _jsxs(_components.li, { children: ["For discussions or Q\u0026A about the MCP specification, use the ", _jsx(_components.a, { href: "https://github.com/modelcontextprotocol/specification/discussions", children: "specification discussions" })] }), "\n", _jsxs(_components.li, { children: ["For discussions or Q\u0026A about other MCP open source components, use the ", _jsx(_components.a, { href: "https://github.com/orgs/modelcontextprotocol/discussions", children: "organization discussions" })] }), "\n", _jsxs(_components.li, { children: ["For bug reports, feature requests, and questions related to Claude.app and claude.ai’s MCP integration, please see Anthropic’s guide on ", _jsx(_components.a, { href: "https://support.anthropic.com/en/articles/9015913-how-to-get-support", children: "How to Get Support" })] }), "\n"] }); } ``` -------------------------------- ### Implement Error Handling in Spiceflow (TypeScript) Source: https://context7_llms Demonstrates how to set up a global error handler for a Spiceflow application using the `.onError()` method. The handler receives the error and the request context, allowing for custom logging and response generation. ```typescript import { Spiceflow } from 'spiceflow' new Spiceflow().onError(({ error }) => { console.error(error) return new Response('An error occurred', { status: 500 }) }) ``` -------------------------------- ### MDX Content Rendering Function - JavaScript Source: https://modelcontextprotocol.io/ This function defines how MDX content is wrapped by a layout component if available, otherwise renders the content directly. It also includes a helper function `_missingMdxReference` used to throw errors when required components or objects are not provided. ```JavaScript const {wrapper: MDXLayout} = { ..._provideComponents(), ...props.components }; return MDXLayout ? _jsx(MDXLayout, { ...props, children: _jsx(_createMdxContent, { ...props }) }) : _createMdxContent(props); } return { default: MDXContent }; function _missingMdxReference(id, component) { throw new Error("Expected " + (component ? "component" : "object") + " `" + id + "` to be defined: you likely forgot to import, pass, or provide it."); } ``` -------------------------------- ### Export MDX Content Function (JS) Source: https://modelcontextprotocol.io/ This code block exports the main `MDXContent` function as the default export for the module, making it available for use in other parts of the application. ```JavaScript return { default: MDXContent }; ``` -------------------------------- ### Define Font Variables - CSS Source: https://modelcontextprotocol.io/ Defines CSS variables within the :root selector to specify custom fonts for the website, including 'Inter' and 'JetBrains Mono', with fallback options. ```css :root{--font-inter:'__Inter_a4e4e2', '__Inter_Fallback_a4e4e2';--font-jetbrains-mono:'__JetBrains_Mono_3bbdad', '__JetBrains_Mono_Fallback_3bbdad'} ``` -------------------------------- ### Handling POST Request with Zod Body Schema Source: https://context7_llms This snippet shows how to define a POST route with a Zod schema for the request body. It demonstrates accessing the request body using `request.json()` and how Spiceflow provides type safety for the parsed body based on the defined schema. ```ts import { z } from 'zod' import { Spiceflow } from 'spiceflow' new Spiceflow().post( '/users', async ({ request }) => { const body = await request.json() // here body has type { name: string, email: string } return `Created user: ${body.name}` }, { body: z.object({ name: z.string(), email: z.string().email(), }), }, ) ``` -------------------------------- ### Implementing Authorization Middleware in Spiceflow (TypeScript) Source: https://context7_llms This code defines a Spiceflow middleware that checks for a user session. If a session exists, it's stored in the state; otherwise, the request is potentially blocked or handled differently. It also demonstrates how to propagate 'Set-Cookie' headers from the middleware response. ```TypeScript import { z } from 'zod' import { Spiceflow } from 'spiceflow' new Spiceflow() .state('session', null as Session | null) .use(async ({ request: req, state }, next) => { const res = new Response() const { session } = await getSession({ req, res }) if (!session) { return } state.session = session const response = await next() const cookies = res.headers.getSetCookie() for (const cookie of cookies) { response.headers.append('Set-Cookie', cookie) } return response }) .post('/protected', async ({ state }) => { const { session } = state if (!session) { throw new Error('Not logged in') } return { ok: true } }) ``` -------------------------------- ### Proxying Requests with Spiceflow Middleware (TypeScript) Source: https://context7_llms This snippet demonstrates how to create a middleware function in Spiceflow to proxy incoming requests to a different target URL, such as an external API. It shows how to modify request headers like 'origin' and handle the response from the target. ```TypeScript import { Spiceflow } from 'spiceflow' import { MiddlewareHandler } from 'spiceflow/dist/types' const app = new Spiceflow() function createProxyMiddleware({ target, changeOrigin = false, }): MiddlewareHandler { return async (context) => { const { request } = context const url = new URL(request.url) const proxyReq = new Request( new URL(url.pathname + url.search, target), request, ) if (changeOrigin) { proxyReq.headers.set('origin', new URL(target).origin || '') } console.log('proxying', proxyReq.url) const res = await fetch(proxyReq) return res } } app.use( createProxyMiddleware({ target: 'https://api.openai.com', changeOrigin: true, }), ) // or with a basePath app.use( new Spiceflow({ basePath: '/v1/completions' }).use( createProxyMiddleware({ target: 'https://api.openai.com', changeOrigin: true, }), ), ) app.listen(3030) ``` -------------------------------- ### Modifying Spiceflow Response with Middleware (TypeScript) Source: https://context7_llms Illustrates how to define middleware in Spiceflow using the .use() method. The middleware intercepts the response from the next handler and modifies its headers before returning it. ```ts import { Spiceflow } from 'spiceflow' new Spiceflow() .use(async ({ request }, next) => { const response = await next() if (response) { // Add a custom header to all responses response.headers.set('X-Powered-By', 'Spiceflow') } return response }) .get('/example', () => { return { message: 'Hello, World!' } }) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.