### Install Project Dependencies Source: https://docs.solidjs.com/solid-start/getting-started After creating your project directory and choosing a template, run this command to install all required dependencies. ```bash npm i ``` ```bash pnpm i ``` ```bash yarn i ``` ```bash bun i ``` ```bash deno i ``` -------------------------------- ### Basic Server Entrypoint Example Source: https://docs.solidjs.com/solid-start/reference/entrypoints/entry-server A complete example of a server entrypoint file, including imports, a Document component, and the handler definition. ```typescript import { createHandler, StartServer } from "@solidjs/start/server"; function Document(props) { return ( {props.assets}
{props.children}
{props.scripts} ); } export default createHandler((event) => ); ``` -------------------------------- ### Install @solidjs/meta Source: https://docs.solidjs.com/solid-start/building-your-application/head-and-metadata Install the @solidjs/meta library using npm. ```bash npm i @solidjs/meta ``` -------------------------------- ### Import GET from SolidStart Source: https://docs.solidjs.com/solid-start/reference/server/get Import the GET utility from the @solidjs/start package. ```typescript import { GET } from "@solidjs/start"; ``` -------------------------------- ### Basic Usage Example Source: https://docs.solidjs.com/solid-start/reference/routing/file-routes Demonstrates how to import and use the FileRoutes component within a SolidStart application's router. ```typescript import { Router } from "@solidjs/router"; import { FileRoutes } from "@solidjs/start/router"; export default function App() { return ( ); } ``` -------------------------------- ### Implement GraphQL API Route in SolidStart Source: https://docs.solidjs.com/solid-start/building-your-application/api-routes Define a GraphQL schema and resolvers, then export a handler function for API routes. This example shows how to set up both GET and POST handlers for the GraphQL endpoint. ```typescript import { buildSchema, graphql } from "graphql"; import type { APIEvent } from "@solidjs/start/server"; // Define GraphQL Schema const schema = buildSchema(` type Message { message: String } type Query { hello(input: String): Message goodbye: String } `); // Define GraphQL Resolvers const rootValue = { hello: () => { return { message: "Hello World", }; }, goodbye: () => { return "Goodbye"; }, }; // request handler const handler = async (event: APIEvent) => { // get request body const body = await new Response(event.request.body).json(); // pass query and save results const result = await graphql({ rootValue, schema, source: body.query }); // send query result return result; }; export const GET = handler; export const POST = handler; ``` -------------------------------- ### Example API Route: Fetching Products Source: https://docs.solidjs.com/solid-start/building-your-application/api-routes An example of an API route that retrieves products based on category and brand parameters. ```APIDOC An example of an API route that returns products from a certain category and brand is shown below: ```javascript import type { APIEvent } from "@solidjs/start/server"; import store from "./store"; export async function GET({ params }: APIEvent) { console.log(`Category: ${params.category}, Brand: ${params.brand}`); const products = await store.getProducts(params.category, params.brand); return products; } ``` ``` -------------------------------- ### Run the SolidStart Application Source: https://docs.solidjs.com/solid-start/getting-started Execute this command to start the development server and run your SolidStart application locally. The application will typically be available at http://localhost:3000. ```bash npm run dev ``` ```bash pnpm dev ``` ```bash yarn dev ``` ```bash bun run dev ``` ```bash deno run dev ``` -------------------------------- ### Basic SolidStart App Structure Source: https://docs.solidjs.com/solid-start/reference/entrypoints/app Sets up the root of a SolidStart application using the Router and FileRoutes for dynamic routing. Ensure @solidjs/router is installed. ```typescript import { Router } from "@solidjs/router"; import { FileRoutes } from "@solidjs/start/router"; export default function App() { return ( ); } ``` -------------------------------- ### Basic App Configuration Source: https://docs.solidjs.com/solid-start/reference/entrypoints/app-config A basic example of configuring a SolidStart application using defineConfig with an empty configuration object. ```typescript import { defineConfig } from "@solidjs/start/config"; export default defineConfig({}); ``` -------------------------------- ### Basic Usage of GET Source: https://docs.solidjs.com/solid-start/reference/server/get Demonstrates how to use the GET function to create a handler from a function that has a .GET property. The handler will return the value of the .GET property. ```typescript import { GET } from "@solidjs/start"; const getMessage = Object.assign(async () => "hello", { GET: async () => "hello", }); const handler = GET(getMessage); ``` -------------------------------- ### Basic createHandler Usage Source: https://docs.solidjs.com/solid-start/reference/server/create-handler Example of basic usage for createHandler, passing a StartServer component to render the SolidStart application. ```typescript import { createHandler, StartServer } from "@solidjs/start/server"; export default createHandler((event) => ); ``` -------------------------------- ### Update Dependencies with bun Source: https://docs.solidjs.com/solid-start/migrating-from-v1 Install the necessary v2 packages and update Vite using bun. ```bash bun i @solidjs/start@2.0.0-alpha.2 @solidjs/vite-plugin-nitro-2 vite@7 ``` -------------------------------- ### Update Dependencies with deno Source: https://docs.solidjs.com/solid-start/migrating-from-v1 Install the necessary v2 packages and update Vite using deno. ```bash deno add npm:@solidjs/start@2.0.0-alpha.2 @solidjs/vite-plugin-nitro-2 vite@7 ``` -------------------------------- ### Triggering an Action Programmatically (JavaScript) Source: https://docs.solidjs.com/solid-start/guides/data-mutation Use `useAction` to programmatically trigger an action defined with `action`. This example shows how to bind the action to a button click after getting the trigger function. ```javascript import { createSignal } from "solid-js"; import { action, useAction } from "@solidjs/router"; const addPost = action(async (title) => { await fetch("https://my-api.com/posts", { method: "POST", body: JSON.stringify({ title }), }); }, "addPost"); export default function Page() { const [title, setTitle] = createSignal(""); const addPostAction = useAction(addPost); return (
setTitle(e.target.value)} />
); } ``` -------------------------------- ### GET Function Source: https://docs.solidjs.com/solid-start/reference/server/get The GET function in SolidStart is used to retrieve the .GET property from a provided function. It takes a function `fn` as input and returns a new function that, when called, returns the value of `fn.GET`. ```APIDOC ## GET ### Description `GET` returns the `.GET` property from a function. ### Import ```javascript import { GET } from "@solidjs/start"; ``` ### Type ```typescript function GET any>( fn: T ): (...args: Parameters) => ReturnType; ``` ### Parameters #### `fn` * **Type:** `T extends (...args: any[]) => any` * **Required:** Yes Function with a `GET` property. ### Return value * **Type:** `(...args: Parameters) => ReturnType` Returns `fn.GET`. ### Examples #### Basic usage ```javascript import { GET } from "@solidjs/start"; const getMessage = Object.assign(async () => "hello", { GET: async () => "hello", }); const handler = GET(getMessage); ``` ``` -------------------------------- ### Basic clientOnly Usage Example Source: https://docs.solidjs.com/solid-start/reference/client/client-only Demonstrates how to use `clientOnly` to wrap an async component import. The `fallback` prop is rendered on the server, and the component is loaded lazily on the client. ```javascript import { clientOnly } from "@solidjs/start"; const Map = clientOnly(() => import("./Map"), { lazy: true, }); export default function Page() { return Loading map...

} />; } ``` -------------------------------- ### Update Dependencies with npm Source: https://docs.solidjs.com/solid-start/migrating-from-v1 Install the necessary v2 packages and update Vite using npm. ```bash npm i @solidjs/start@2.0.0-alpha.2 @solidjs/vite-plugin-nitro-2 vite@7 ``` -------------------------------- ### Update Dependencies with pnpm Source: https://docs.solidjs.com/solid-start/migrating-from-v1 Install the necessary v2 packages and update Vite using pnpm. ```bash pnpm i @solidjs/start@2.0.0-alpha.2 @solidjs/vite-plugin-nitro-2 vite@7 ``` -------------------------------- ### Protected Routes with Solid Router Source: https://docs.solidjs.com/solid-start/advanced/auth This example demonstrates protecting routes by checking user authentication within a server function. If the user is not logged in, they are redirected to the login page. Set `deferStream: true` to prevent streaming issues with server-side redirects. ```javascript import { redirect } from "@solidjs/router"; import { createAsync } from "@solidjs/router"; import { query } from "@solidjs/router"; // Assuming query is a helper for server functions // Placeholder for getUser and db functions async function getUser() { // Replace with actual user retrieval logic return null; // Simulate unauthenticated user } const db = { getPosts: async ({ userId, private }) => { // Replace with actual database logic return [{ id: 1, title: "Private Post 1" }]; } }; const getPrivatePosts = query(async function () { "use server"; const user = await getUser(); if (!user) { throw redirect("/login"); } return db.getPosts({ userId: user.id, private: true }); }); export default function Page() { const posts = createAsync(() => getPrivatePosts(), { deferStream: true }); // Render posts here return
Posts: {JSON.stringify(posts())}
; } ``` -------------------------------- ### Basic Usage of HttpStatusCode Source: https://docs.solidjs.com/solid-start/reference/server/http-status-code Example of using the HttpStatusCode component to set a 404 Not Found status and text in a SolidStart application. ```typescript import { HttpStatusCode } from "@solidjs/start"; export default function NotFound() { return ; } ``` -------------------------------- ### Update Dependencies with yarn Source: https://docs.solidjs.com/solid-start/migrating-from-v1 Install the necessary v2 packages and update Vite using yarn. ```bash yarn add @solidjs/start@2.0.0-alpha.2 @solidjs/vite-plugin-nitro-2 vite@7 ``` -------------------------------- ### API Route with Dynamic Parameters and Data Fetching Source: https://docs.solidjs.com/solid-start/building-your-application/api-routes An example of an API route that accepts dynamic parameters (category, brand) from the URL, logs them, fetches products using a store, and returns the products. ```typescript import type { APIEvent } from "@solidjs/start/server"; import store from "./store"; export async function GET({ params }: APIEvent) { console.log(`Category: ${params.category}, Brand: ${params.brand}`); const products = await store.getProducts(params.category, params.brand); return products; } ``` -------------------------------- ### Basic Usage of createMiddleware Source: https://docs.solidjs.com/solid-start/reference/server/create-middleware Example of using `createMiddleware` to add a custom header to the response based on the request path. The `onRequest` middleware is executed for each incoming request. ```typescript import { createMiddleware } from "@solidjs/start/middleware"; export default createMiddleware({ onRequest: async (event) => { event.response.headers.set( "x-request-path", new URL(event.request.url).pathname ); }, }); ``` -------------------------------- ### File Directive Example Source: https://docs.solidjs.com/solid-start/reference/server/use-server Placing the "use server" directive at the top of a file exports all functions within that file as server functions. This is useful for grouping related server-side logic. ```typescript "use server"; export async function logMessage(message: string) { console.log(message); } ``` -------------------------------- ### Basic HttpHeader Usage Source: https://docs.solidjs.com/solid-start/reference/server/http-header Example of using the HttpHeader component to set a 'cache-control' header with a specific value. This is intended for server-side rendering. ```typescript import { HttpHeader } from "@solidjs/start"; export default function Page() { return ; } ``` -------------------------------- ### Define tRPC Router Source: https://docs.solidjs.com/solid-start/building-your-application/api-routes Create a tRPC router with procedures and input validation. This example uses Valibot for input schema definition. ```typescript import { initTRPC } from "@trpc/server"; import { wrap } from "@decs/typeschema"; import { string } from "valibot"; const t = initTRPC.create(); export const appRouter = t.router({ hello: t.procedure.input(wrap(string())).query(({ input }) => { return `hello ${input ?? "world"}`; }), }); export type AppRouter = typeof appRouter; ``` -------------------------------- ### Configure Nitro Server Preset Source: https://docs.solidjs.com/solid-start/reference/config/define-config Use the `server.preset` option to specify the Nitro build and deployment preset. For example, 'netlify_edge' is used for Netlify Edge Functions. ```typescript import { defineConfig } from "@solidjs/start/config"; export default defineConfig({ server: { preset: "netlify_edge", }, }); ``` -------------------------------- ### WebSocket Event Handler in SolidStart Source: https://docs.solidjs.com/solid-start/advanced/websocket Manage WebSocket connections and events using the `eventHandler` function. This example shows how to define handlers for connection open, message, close, and error events. ```typescript import { eventHandler } from "vinxi/http"; export default eventHandler({ handler() {}, websocket: { async open(peer) { console.log("open", peer.id, peer.url); }, async message(peer, msg) { const message = msg.text(); console.log("msg", peer.id, peer.url, message); }, async close(peer, details) { console.log("close", peer.id, peer.url); }, async error(peer, error) { console.log("error", peer.id, peer.url, error); }, }, }); ``` -------------------------------- ### Single-flight Product Update Action Source: https://docs.solidjs.com/solid-start/building-your-application/data-mutation This example demonstrates a single-flight mutation for updating product data. The action runs on the server, and the associated query is preloaded to ensure the UI stays in sync after the mutation. The form submission triggers a single POST request. ```typescript import { action, query, createAsync, type RouteDefinition, type RouteSectionProps, } from "@solidjs/router"; import { db } from "./db"; const updateProductAction = action(async (id: string, formData: FormData) => { "use server"; const name = formData.get("name")?.toString(); await db.products.update(id, { name }); }, "updateProduct"); const getProductQuery = query(async (id: string) => { "use server"; return await db.products.get(id); }, "product"); export const route = { preload: ({ params }) => getProductQuery(params.id as string), } satisfies RouteDefinition; export default function ProductDetail(props: RouteSectionProps) { const product = createAsync(() => getProductQuery(props.params.id as string)); return (

Current name: {props.data.product?.name}

); } ``` -------------------------------- ### Triggering an Action Programmatically (TypeScript) Source: https://docs.solidjs.com/solid-start/guides/data-mutation Use `useAction` to programmatically trigger an action defined with `action`. This example shows how to bind the action to a button click after getting the trigger function. ```typescript import { createSignal } from "solid-js"; import { action, useAction } from "@solidjs/router"; const addPost = action(async (title: string) => { await fetch("https://my-api.com/posts", { method: "POST", body: JSON.stringify({ title }), }); }, "addPost"); export default function Page() { const [title, setTitle] = createSignal(""); const addPostAction = useAction(addPost); return (
setTitle(e.target.value)} />
); } ``` -------------------------------- ### Initialize a New SolidStart Project Source: https://docs.solidjs.com/solid-start/getting-started Use this command to create a new SolidStart project. Follow the prompts to select a template and configuration options. ```bash npm init solid ``` ```bash pnpm create solid ``` ```bash yarn create solid ``` ```bash bun create solid ``` ```bash deno init --npm solid ``` -------------------------------- ### GET Function Type Definition Source: https://docs.solidjs.com/solid-start/reference/server/get Defines the type signature for the GET function, which accepts a function with a GET property and returns a function with the same signature. ```typescript function GET any>( fn: T ): (...args: Parameters) => ReturnType; ``` -------------------------------- ### Basic StartServer Usage with Custom Document Source: https://docs.solidjs.com/solid-start/reference/server/start-server Demonstrates how to use StartServer with a custom Document component and createHandler for server-side rendering. The Document component defines the HTML structure, including where assets, the app's children, and scripts are placed. ```javascript import { createHandler, StartServer } from "@solidjs/start/server"; function Document(props) { return ( {props.assets}
{props.children}
{props.scripts} ); } export default createHandler((event) => ); ``` -------------------------------- ### StartServer Component Usage Source: https://docs.solidjs.com/solid-start/reference/server/start-server Demonstrates how to import and use the StartServer component with a custom Document component for server-side rendering. ```APIDOC ## StartServer `StartServer` is a component that renders the generated app inside the provided document component. ### Import ```javascript import { StartServer } from "@solidjs/start/server"; ``` ### Type ```typescript type DocumentComponentProps = { assets: JSX.Element; scripts: JSX.Element; children?: JSX.Element; }; function StartServer(props: { document: Component }): JSX.Element; ``` ### Props #### `document` * **Type:** `Component` * **Optional:** No Document component rendered around the app. ### Behavior * Reads the current request event as a `PageEvent`. * Registers page assets with `useAssets`. * Renders `` before the document component. * Passes `assets`, `scripts`, and `children` to the document component. * Wraps the app with error boundaries. ### Examples #### Basic usage ```javascript import { createHandler, StartServer } from "@solidjs/start/server"; function Document(props) { return ( {props.assets}
{props.children}
{props.scripts} ); } export default createHandler((event) => ); ``` ``` -------------------------------- ### Import Mount and StartClient Source: https://docs.solidjs.com/solid-start/reference/entrypoints/entry-client Imports the necessary functions `mount` and `StartClient` from the SolidStart client library. ```typescript import { mount, StartClient } from "@solidjs/start/client"; ``` -------------------------------- ### Import StartServer Component Source: https://docs.solidjs.com/solid-start/reference/server/start-server Import the StartServer component from the SolidStart server package. ```javascript import { StartServer } from "@solidjs/start/server"; ``` -------------------------------- ### Basic StartClient Usage Source: https://docs.solidjs.com/solid-start/reference/client/start-client Mount the SolidStart application using the StartClient component and the mount function. Ensure the target element with the ID 'app' exists in your HTML. ```typescript import { mount, StartClient } from "@solidjs/start/client"; mount(() => , document.getElementById("app")!); ``` -------------------------------- ### Import createHandler and StartServer Source: https://docs.solidjs.com/solid-start/reference/entrypoints/entry-server Imports the necessary functions for creating a server handler in SolidStart. ```typescript import { createHandler, StartServer } from "@solidjs/start/server"; ``` -------------------------------- ### Import createMiddleware Source: https://docs.solidjs.com/solid-start/reference/server/create-middleware Import the `createMiddleware` function from the SolidStart library. ```typescript import { createMiddleware } from "@solidjs/start/middleware"; ``` -------------------------------- ### Import StartClient Source: https://docs.solidjs.com/solid-start/reference/client/start-client Import the StartClient component from the @solidjs/start/client package. ```typescript import { StartClient } from "@solidjs/start/client"; ``` -------------------------------- ### Setting up Router with FileRoutes Source: https://docs.solidjs.com/solid-start/building-your-application/routing Integrate `@solidjs/router` and `` to enable file-based routing for your UI components. Ensure `props.children` is wrapped in `` to prevent hydration errors. ```typescript import { Suspense } from "solid-js"; import { Router } from "@solidjs/router"; import { FileRoutes } from "@solidjs/start/router"; export default function App() { return ( {props.children}}> ); } ``` -------------------------------- ### Import clientOnly Utility Source: https://docs.solidjs.com/solid-start/reference/client/client-only Import the `clientOnly` function from the `@solidjs/start` library. ```javascript import { clientOnly } from "@solidjs/start"; ``` -------------------------------- ### Import getServerFunctionMeta Source: https://docs.solidjs.com/solid-start/reference/server/get-server-function-meta Import the getServerFunctionMeta function from the @solidjs/start package. ```typescript import { getServerFunctionMeta } from "@solidjs/start"; ``` -------------------------------- ### Import mount function Source: https://docs.solidjs.com/solid-start/reference/client/mount Import the `mount` function from the SolidStart client library. ```typescript import { mount } from "@solidjs/start/client"; ``` -------------------------------- ### Function Directive Example Source: https://docs.solidjs.com/solid-start/reference/server/use-server Use the "use server" directive within an async function to mark it as a server function. This function will be executed on the server. ```typescript const logMessage = async (message: string) => { "use server"; console.log(message); }; ``` -------------------------------- ### Mount the Client Application Source: https://docs.solidjs.com/solid-start/reference/entrypoints/entry-client Mounts the SolidStart client application to a specified DOM element. This is the core function for initializing the client-side rendering. ```typescript mount(() => , element); ``` -------------------------------- ### Return JSON Response from Server Function Source: https://docs.solidjs.com/solid-start/advanced/return-responses Use the `json` helper from `@solidjs/router` to return a JSON response with custom headers from a server function. The `GET` handler is used here. ```typescript import { json } from "@solidjs/router"; import { GET } from "@solidjs/start"; const hello = GET(async (name: string) => { "use server"; return json( { hello: new Promise((r) => setTimeout(() => r(name), 1000)) }, { headers: { "cache-control": "max-age=60" } } ); }); ``` -------------------------------- ### Using useParams for Dynamic Segments Source: https://docs.solidjs.com/solid-start/building-your-application/routing Import and use the `useParams` primitive from `@solidjs/router` to access the values of dynamic route segments within your components. This example shows how to retrieve a user ID. ```typescript import { useParams } from "@solidjs/router"; export default function UserPage() { const params = useParams(); return
User {params.id}
; } ``` -------------------------------- ### Import HttpHeader Component Source: https://docs.solidjs.com/solid-start/reference/server/http-header Import the HttpHeader component from the @solidjs/start package. ```typescript import { HttpHeader } from "@solidjs/start"; ``` -------------------------------- ### Import defineConfig Source: https://docs.solidjs.com/solid-start/reference/entrypoints/app-config Import the defineConfig function from the SolidStart configuration module. ```typescript import { defineConfig } from "@solidjs/start/config"; ``` -------------------------------- ### Show Loading UI During Data Fetching in SolidStart Source: https://docs.solidjs.com/solid-start/guides/data-fetching Wrap your data rendering in `` and use the `fallback` prop to display a loading indicator while data is being fetched. Requires importing `Suspense` from `solid-js`. ```typescript // src/routes/index.tsx import { Suspense, For } from "solid-js"; import { query, createAsync } from "@solidjs/router"; const getPosts = query(async () => { const posts = await fetch("https://my-api.com/posts"); return await posts.json(); }, "posts"); export default function Page() { const posts = createAsync(() => getPosts()); return (
    Loading...}> {(post) =>
  • {post.title}
  • }
); } ``` ```javascript // src/routes/index.jsx import { Suspense, For } from "solid-js"; import { query, createAsync } from "@solidjs/router"; const getPosts = query(async () => { const posts = await fetch("https://my-api.com/posts"); return await posts.json(); }, "posts"); export default function Page() { const posts = createAsync(() => getPosts()); return (
    Loading...}> {(post) =>
  • {post.title}
  • }
); } ``` -------------------------------- ### Define HTTP Method Handlers for API Routes Source: https://docs.solidjs.com/solid-start/building-your-application/api-routes Export functions named after HTTP methods (GET, POST, PATCH, DELETE) to handle corresponding requests in an API route. The function body contains the server-side logic. ```typescript export function GET() { // ... } export function POST() { // ... } export function PATCH() { // ... } export function DELETE() { // ... } ``` -------------------------------- ### Import HttpStatusCode Component Source: https://docs.solidjs.com/solid-start/reference/server/http-status-code Import the HttpStatusCode component from the @solidjs/start package. ```typescript import { HttpStatusCode } from "@solidjs/start"; ``` -------------------------------- ### Import createHandler Source: https://docs.solidjs.com/solid-start/reference/server/create-handler Import the createHandler function from the SolidStart server library. ```typescript import { createHandler } from "@solidjs/start/server"; ``` -------------------------------- ### StartClient Component Source: https://docs.solidjs.com/solid-start/reference/client/start-client The StartClient component renders the client-side application and wraps it in an error boundary. It takes no arguments and returns a JSX element. ```APIDOC ## StartClient ### Description Renders the generated app inside the client error boundary. ### Type ```typescript function StartClient(): JSX.Element; ``` ### Parameters `StartClient` takes no arguments. ### Return Value - **Type:** `JSX.Element` Returns the client app element. ### Behavior - Renders the `#start/app` module. - Wraps the app in the shared `ErrorBoundary`. ### Examples #### Basic usage ```javascript import { mount, StartClient } from "@solidjs/start/client"; mount(() => , document.getElementById("app")!); ``` ``` -------------------------------- ### Configure SolidStart for WebSocket Support Source: https://docs.solidjs.com/solid-start/advanced/websocket Enable experimental WebSocket support in SolidStart by setting `websocket: true` in the server configuration. This snippet also demonstrates how to add a WebSocket router. ```typescript import { defineConfig } from "@solidjs/start/config"; export default defineConfig({ server: { experimental: { websocket: true, }, }, }).addRouter({ name: "ws", type: "http", handler: "./src/ws.ts", target: "server", base: "/ws", }); ``` -------------------------------- ### Configure Vite for SolidStart v2 Source: https://docs.solidjs.com/solid-start/migrating-from-v1 Set up the vite.config.ts file with SolidStart and the Nitro v2 plugin. The middleware option can be configured here. ```typescript import { solidStart } from "@solidjs/start/config"; import { defineConfig } from "vite"; import { nitroV2Plugin } from "@solidjs/vite-plugin-nitro-2"; export default defineConfig(() => { return { plugins: [ solidStart({ middleware: "./src/middleware/index.ts", }), nitroV2Plugin(), ], }; }); ``` -------------------------------- ### Basic Usage of getServerFunctionMeta Source: https://docs.solidjs.com/solid-start/reference/server/get-server-function-meta Demonstrates how to call getServerFunctionMeta to retrieve server function metadata. Ensure the function is imported before use. ```typescript import { getServerFunctionMeta } from "@solidjs/start"; const meta = getServerFunctionMeta(); ``` -------------------------------- ### Import FileRoutes Component Source: https://docs.solidjs.com/solid-start/reference/routing/file-routes Import the FileRoutes component from the SolidStart router library. ```javascript import { FileRoutes } from "@solidjs/start/router"; ``` -------------------------------- ### Basic API Route Structure Source: https://docs.solidjs.com/solid-start/building-your-application/api-routes Demonstrates how to export functions for different HTTP methods within an API route file. ```APIDOC ## Writing an API route To write an API route, you can create a file in a directory. While you can name this directory anything, it is common to name it `api` to indicate that the routes in this directory are for handling API requests: ```javascript export function GET() { // ... } export function POST() { // ... } export function PATCH() { // ... } export function DELETE() { // ... } ``` ``` -------------------------------- ### createMiddleware Function Source: https://docs.solidjs.com/solid-start/reference/server/create-middleware The createMiddleware function allows you to define and wrap middleware functions for handling request and response events in SolidStart applications. It accepts an object with optional `onRequest` and `onBeforeResponse` middleware handlers. ```APIDOC ## createMiddleware `createMiddleware` wraps request and response middleware functions with fetch events. ### Import ```typescript import { createMiddleware } from "@solidjs/start/middleware"; ``` ### Type ```typescript type RequestMiddleware = ( event: FetchEvent ) => Response | Promise | void | Promise; type ResponseMiddleware = ( event: FetchEvent, response: { body?: unknown } ) => Response | Promise | void | Promise; function createMiddleware(args: { onRequest?: RequestMiddleware | RequestMiddleware[]; onBeforeResponse?: ResponseMiddleware | ResponseMiddleware[]; }): { onRequest?: _RequestMiddleware | _RequestMiddleware[]; onBeforeResponse?: _ResponseMiddleware | _ResponseMiddleware[]; }; ``` ### Parameters #### `args` * **Type:** `{ onRequest?: RequestMiddleware | RequestMiddleware[]; onBeforeResponse?: ResponseMiddleware | ResponseMiddleware[] }` * **Required:** Yes Middleware functions grouped by request phase. ### Return value * **Type:** `{ onRequest?: _RequestMiddleware | _RequestMiddleware[]; onBeforeResponse?: _ResponseMiddleware | _ResponseMiddleware[] }` Returns the value from Vinxi `defineMiddleware`. ### Behavior * `onRequest` functions are wrapped so that a returned response ends the middleware. * `onBeforeResponse` functions are wrapped with the current fetch event and response object. * Single middleware inputs produce single wrapped functions. * Array inputs are mapped to arrays of wrapped functions. ### Examples #### Basic usage ```typescript import { createMiddleware } from "@solidjs/start/middleware"; export default createMiddleware({ onRequest: async (event) => { event.response.headers.set( "x-request-path", new URL(event.request.url).pathname ); }, }); ``` ``` -------------------------------- ### Configure Vite Options Source: https://docs.solidjs.com/solid-start/reference/config/define-config Use the `vite` option to pass Vite configuration objects, including plugins. This is the standard way to customize Vite's behavior within SolidStart. ```typescript import { defineConfig } from "@solidjs/start/config"; export default defineConfig({ vite: { // vite options plugins: [], }, }); ``` -------------------------------- ### Create and Access Query Data in SolidStart Source: https://docs.solidjs.com/solid-start/guides/data-fetching Use `query` to define a data fetching function and `createAsync` to access its data. This is useful for fetching initial data for a route. ```typescript // src/routes/index.tsx import { For } from "solid-js"; import { query, createAsync } from "@solidjs/router"; const getPosts = query(async () => { const posts = await fetch("https://my-api.com/posts"); return await posts.json(); }, "posts"); export default function Page() { const posts = createAsync(() => getPosts()); return (
    {(post) =>
  • {post.title}
  • }
); } ``` ```javascript // src/routes/index.jsx import { For } from "solid-js"; import { query, createAsync } from "@solidjs/router"; const getPosts = query(async () => { const posts = await fetch("https://my-api.com/posts"); return await posts.json(); }, "posts"); export default function Page() { const posts = createAsync(() => getPosts()); return (
    {(post) =>
  • {post.title}
  • }
); } ``` -------------------------------- ### Configure Environment Types Source: https://docs.solidjs.com/solid-start/migrating-from-v1 Add the '@solidjs/start/env' type to the 'types' array in tsconfig.json to enable environment type checking. ```json "compilerOptions": { "types": ["@solidjs/start/env"] } ``` -------------------------------- ### Configure CSP with Nonce in SolidStart Middleware Source: https://docs.solidjs.com/solid-start/guides/security Use this middleware to set a dynamic nonce for your Content Security Policy header. The nonce is generated on each request and stored in event.locals for use in your server entry file. ```typescript import { createMiddleware } from "@solidjs/start/middleware"; import { randomBytes } from "crypto"; export default createMiddleware({ onRequest: (event) => { const nonce = randomBytes(16).toString("base64"); event.locals.nonce = nonce; const csp = ` default-src 'self'; script-src 'nonce-${nonce}' 'strict-dynamic'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'; `.replace(/\s+/g, " "); event.response.headers.set("Content-Security-Policy", csp); }, }); ``` ```typescript // src/entry-server.tsx // @refresh reload import { createHandler, StartServer } from "@solidjs/start/server"; export default createHandler( () => , (event) => ({ nonce: event.locals.nonce }) ); ``` -------------------------------- ### Defining Catch-all Routes Source: https://docs.solidjs.com/solid-start/building-your-application/routing Use `[...paramName]` to define catch-all routes that match any number of subsequent URL segments. The parameter will contain a forward-slash delimited string of all matched segments. ```directory structure |-- routes/ |-- blog/ |-- index.tsx |-- [...post].tsx ``` -------------------------------- ### Define App Configuration Source: https://docs.solidjs.com/solid-start/reference/entrypoints/app-config Export the result of defineConfig as the default export. This configures the SolidStart application. ```typescript export default defineConfig(baseConfig); ``` -------------------------------- ### Handling Cookies with Middleware in SolidStart Source: https://docs.solidjs.com/solid-start/advanced/middleware Utilize Vinxi's http helpers (getCookie, setCookie) for simplified cookie management within middleware. Cookies are accessed via the Cookie request header and set via the Set-Cookie response header. ```typescript import { createMiddleware } from "@solidjs/start/middleware"; import { getCookie, setCookie } from "vinxi/http"; export default createMiddleware({ onRequest: (event) => { // Reading a cookie const theme = getCookie(event.nativeEvent, "theme"); // Setting a secure session cookie with expiration setCookie(event.nativeEvent, "session", "abc123", { httpOnly: true, secure: true, maxAge: 60 * 60 * 24, // 1 day }); }, }); ``` -------------------------------- ### Configure CSP Without Nonce in SolidStart Middleware Source: https://docs.solidjs.com/solid-start/guides/security This middleware configures a static Content Security Policy header. It should be registered to run during the onBeforeResponse event. ```typescript import { createMiddleware } from "@solidjs/start/middleware"; export default createMiddleware({ onBeforeResponse: (event) => { const csp = ` default-src 'self'; font-src 'self' ; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'; `.replace(/\s+/g, " "); event.response.headers.set("Content-Security-Policy", csp); }, }); ``` -------------------------------- ### Session Management with Cookies Source: https://docs.solidjs.com/solid-start/building-your-application/api-routes Illustrates how to manage user sessions using HTTP-only cookies by accessing the `Cookie` header and utilizing helpers from `vinxi/http`. ```APIDOC ## Session management Since HTTP is a stateless protocol, you need to manage the state of the session on the server. For example, if you want to know who the user is, the most secure way of doing this is through the use of HTTP-only cookies. Cookies are a way to store data in the user's browser that persist in the browser between requests. The user's request is exposed through the `Request` object. Through parsing the `Cookie` header, the cookies can be accessed and any helpers from `vinxi/http` can be used to make that a bit easier. ```javascript import type { APIEvent } from "@solidjs/start/server"; import { getCookie } from "vinxi/http"; import store from "./store"; export async function GET(event: APIEvent) { const userId = getCookie("userId"); if (!userId) { return new Response("Not logged in", { status: 401 }); } const user = await store.getUser(event.params.userId); if (user.id !== userId) { return new Response("Not authorized", { status: 403 }); } return user; } ``` In this example, you can see that the `userId` is read from the cookie and then used to look up the user in the store. For more information on how to use cookies for secure session management, read the session documentation. ``` -------------------------------- ### Create and Initialize a Session Source: https://docs.solidjs.com/solid-start/advanced/session Use the `useSession` helper in a server function to initialize a session or retrieve an existing one. It requires a secure password and allows defining custom session data types. The session is automatically updated with a `Set-Cookie` header. ```typescript import { useSession } from "vinxi/http"; type SessionData = { theme: "light" | "dark"; }; export async function useThemeSession() { "use server"; const session = await useSession({ password: process.env.SESSION_SECRET as string, name: "theme", }); if (!session.data.theme) { await session.update({ theme: "light", }); } return session; } ``` -------------------------------- ### Client-Side Data Fetching with createResource (JavaScript) Source: https://docs.solidjs.com/solid-start/guides/data-fetching Use createResource to fetch data exclusively on the client. Wrap the data fetching logic in Suspense and ErrorBoundary for a better user experience. ```javascript // src/routes/index.jsx import { createResource, ErrorBoundary, Suspense, For } from "solid-js"; export default function Page() { const [posts] = createResource(async () => { const posts = await fetch("https://my-api.com/posts"); return await posts.json(); }); return (
    Something went wrong!}> Loading...}> {(post) =>
  • {post.title}
  • }
); } ``` -------------------------------- ### Configure Prerendering for All Routes Source: https://docs.solidjs.com/solid-start/building-your-application/route-prerendering Set `crawlLinks` to `true` within the `prerender` configuration to automatically pre-render all links found on your site. This is a convenient option for sites where all pages should be statically generated. ```javascript import { defineConfig } from "@solidjs/start/config"; export default defineConfig({ server: { prerender: { crawlLinks: true, }, }, }); ``` -------------------------------- ### createHandler Parameters Source: https://docs.solidjs.com/solid-start/reference/server/create-handler Details the parameters accepted by the createHandler function: the rendering function `fn`, optional `options`, and the `routerLoad` function. ```APIDOC ## Parameters ### `fn` * **Type:** `(context: PageEvent) => unknown` * **Required:** Yes Function that returns the server-rendered document. ### `options` * **Type:** `HandlerOptions | ((context: PageEvent) => HandlerOptions | Promise)` * **Default:** `{}` * **Required:** No Rendering options or a function that returns rendering options. The supported options are: The `options` object supports these fields: Name| Type| Required| Default| Description ---|---|---|---|--- `mode`| `"sync" | "async" | "stream"`| No| `"stream"`| Rendering mode. `nonce`| `string`| No| None| Nonce assigned to the page event. `renderId`| `string`| No| None| Render identifier passed to the render context. `onCompleteAll`| `(options: { write: (value: any) => void }) => void`| No| None| Callback used when all stream content is ready. `onCompleteShell`| `(options: { write: (value: any) => void }) => void`| No| None| Callback used when the shell stream is ready. ### `routerLoad` * **Type:** `(event: FetchEvent) => Promise` * **Required:** No Function called with the fetch event before API route matching and page rendering. ``` -------------------------------- ### Implementing Redirects with Middleware Source: https://docs.solidjs.com/solid-start/advanced/middleware Use the redirect helper from @solidjs/router to create redirect responses. This is useful for handling legacy routes or directing users to different sections of the application. ```typescript import { createMiddleware } from "@solidjs/start/middleware"; import { redirect } from "@solidjs/router"; const REDIRECT_MAP: Record = { "/signup": "/auth/signup", "/login": "/auth/login", }; export default createMiddleware({ onRequest: (event) => { const { pathname } = new URL(event.request.url); // Redirecting legacy routes permanently to new paths if (pathname in REDIRECT_MAP) { return redirect(REDIRECT_MAP[pathname], 301); } }, }); ``` -------------------------------- ### Organizing Routes with Route Groups Source: https://docs.solidjs.com/solid-start/building-your-application/routing Use parentheses `()` around folder names in the 'routes' directory to create route groups. This helps organize routes without affecting their URL structure. ```directory structure |-- routes/ |-- (static) |-- about-us // example.com/about-us |-- index.tsx |-- contact-us // example.com/contact-us |-- index.tsx ``` -------------------------------- ### createHandler Behavior Source: https://docs.solidjs.com/solid-start/reference/server/create-handler Explains the behavior of the createHandler, including its internal calls, execution order, and response handling for different rendering modes and redirects. ```APIDOC ## Behavior * Calls `createBaseHandler(fn, createPageEvent, options, routerLoad)`. * When `routerLoad` is provided, it runs before API route matching and page rendering. * Matching API routes run before page rendering. For `HEAD` requests, the route `HEAD` export is used, with fallback to `GET`. * Synchronous mode and disabled SSR render with `renderToString` and return the HTML string. * Async mode returns the `renderToStream` result. * Stream mode is the default and returns a readable stream. * If page rendering sets a `Location` response header, the handler sends or writes a redirect response depending on the render phase. ``` -------------------------------- ### Define Server Handler Source: https://docs.solidjs.com/solid-start/reference/entrypoints/entry-server Defines the default server handler using `createHandler` and `StartServer`. ```typescript export default createHandler((event) => ); ``` -------------------------------- ### clientOnly Utility Source: https://docs.solidjs.com/solid-start/reference/client/client-only The `clientOnly` utility wraps an async component import. It returns a component that renders its fallback on the server and loads the component on the client. ```APIDOC ## clientOnly Utility ### Description Wraps an async component import and returns a component that renders its fallback on the server. ### Type Signature ```typescript function clientOnly>( fn: () => Promise<{ default: T }>, options?: { lazy?: boolean } ): (props: ComponentProps & { fallback?: JSX.Element }) => any; ``` ### Parameters #### `fn` * **Type:** `() => Promise<{ default: T }>` * **Required:** Yes Function that imports the client component. #### `options` * **Type:** `{ lazy?: boolean }` * **Default:** `{}` * **Required:** No Loading options with the following properties: ##### `lazy` * **Type:** `boolean` * **Required:** No Controls whether the component import is loaded from inside the returned component. ### Return Value * **Type:** `(props: ComponentProps & { fallback?: JSX.Element }) => any` Returns a component for the imported default export. ### Behavior * On the server, the returned component renders `props.fallback`. * Client rendering loads `fn` immediately unless `options.lazy` is truthy. * `fallback` is split from the remaining props before the loaded component renders. * During hydration, rendering waits until mount. ### Example ```jsx import { clientOnly } from "@solidjs/start"; const Map = clientOnly(() => import("./Map"), { lazy: true, }); export default function Page() { return Loading map...

} />; } ``` ``` -------------------------------- ### Configure Middleware Path in app.config.ts Source: https://docs.solidjs.com/solid-start/advanced/middleware Specify the path to your middleware configuration file in `app.config.ts` to enable SolidStart to recognize and use your middleware. ```typescript import { defineConfig, } from "@solidjs/start/config"; export default defineConfig({ middleware: "src/middleware/index.ts", }); ``` -------------------------------- ### Configure Cloudflare Module Server with Rollup Options Source: https://docs.solidjs.com/solid-start/reference/config/define-config For Cloudflare Workers, specify 'cloudflare_module' as the preset and include `rollupConfig.external` to handle async local storage compatibility. ```typescript import { defineConfig } from "@solidjs/start/config"; export default defineConfig({ server: { preset: "cloudflare_module", rollupConfig: { external: ["__STATIC_CONTENT_MANIFEST", "node:async_hooks"], }, }, }); ``` -------------------------------- ### Update Build and Dev Commands Source: https://docs.solidjs.com/solid-start/migrating-from-v1 Modify the scripts in package.json to use native Vite commands for development, building, and previewing. ```json "scripts": { "dev": "vite dev", "build": "vite build", "start": "vite preview" } ``` -------------------------------- ### Define Middleware with createMiddleware Source: https://docs.solidjs.com/solid-start/advanced/middleware Configure middleware functions for `onRequest` and `onBeforeResponse` events. Use `event.locals` to share request-scoped data. ```typescript import { createMiddleware, } from "@solidjs/start/middleware"; export default createMiddleware({ onRequest: (event) => { console.log("Request received:", event.request.url); event.locals.startTime = Date.now(); }, onBeforeResponse: (event) => { const endTime = Date.now(); const duration = endTime - event.locals.startTime; console.log(`Request took ${duration}ms`); }, }); ```