### Install project dependencies
Source: https://docs.solidjs.com/solid-start/v2/getting-started
Install the necessary packages after project creation.
```bash
npm i
```
```bash
pnpm i
```
```bash
yarn i
```
```bash
bun i
```
```bash
deno i
```
--------------------------------
### Import GET from SolidStart
Source: https://docs.solidjs.com/solid-start/v2/reference/server/get
Import the GET utility from the @solidjs/start package.
```typescript
import { GET } from "@solidjs/start";
```
--------------------------------
### Start the development server
Source: https://docs.solidjs.com/solid-start/v2/getting-started
Launch the local development environment.
```bash
npm run dev
```
```bash
pnpm dev
```
```bash
yarn dev
```
```bash
bun run dev
```
```bash
deno run dev
```
--------------------------------
### Basic Usage of StartServer
Source: https://docs.solidjs.com/solid-start/v2/reference/server/start-server
Example showing how to define a document component and use it with createHandler and StartServer.
```typescript
import { createHandler, StartServer } from "@solidjs/start/server";
function Document(props) {
return (
{props.assets}
{props.children}
{props.scripts}
);
}
export default createHandler((event) => );
```
--------------------------------
### Install and configure Temporal polyfill
Source: https://docs.solidjs.com/solid-start/v2/advanced/serialization
Install the polyfill and import it globally in entrypoints to support Temporal values if the runtime lacks native support.
```bash
pnpm add temporal-polyfill
```
```typescript
import "temporal-polyfill/global";
```
```typescript
import "./temporal";
```
--------------------------------
### Install @solidjs/meta
Source: https://docs.solidjs.com/solid-start/v2/building-your-application/head-and-metadata
Commands to install the @solidjs/meta package using various package managers.
```bash
npm i @solidjs/meta
```
```bash
pnpm i @solidjs/meta
```
```bash
yarn add @solidjs/meta
```
```bash
bun i @solidjs/meta
```
```bash
deno add npm:@solidjs/meta
```
--------------------------------
### Install SolidStart v2 dependencies
Source: https://docs.solidjs.com/solid-start/v2/migrating-from-v1
Commands to install the required versions of SolidStart, Nitro, and Vite using various package managers.
```bash
npm i @solidjs/start@2.0.0 nitro@3.0.260610-beta vite@8
```
```bash
pnpm i @solidjs/start@2.0.0 nitro@3.0.260610-beta vite@8
```
```bash
yarn add @solidjs/start@2.0.0 nitro@3.0.260610-beta vite@8
```
```bash
bun i @solidjs/start@2.0.0 nitro@3.0.260610-beta vite@8
```
```bash
deno add npm:@solidjs/start@2.0.0 nitro@3.0.260610-beta vite@8
```
--------------------------------
### Basic server entry configuration
Source: https://docs.solidjs.com/solid-start/v2/reference/entrypoints/entry-server
A complete example showing the Document component definition and the default handler export.
```typescript
import { createHandler, StartServer } from "@solidjs/start/server";
function Document(props) {
return (
{props.assets}
{props.children}
{props.scripts}
);
}
export default createHandler((event) => );
```
--------------------------------
### Install Netlify Vite Plugin
Source: https://docs.solidjs.com/solid-start/v2/guides/deployment-plugins
Install the Netlify Vite plugin as a development dependency.
```bash
npm i @netlify/vite-plugin -D
```
```bash
pnpm i @netlify/vite-plugin -D
```
```bash
yarn add @netlify/vite-plugin -D
```
```bash
bun i @netlify/vite-plugin -d
```
```bash
deno add npm:@netlify/vite-plugin -D
```
--------------------------------
### Basic usage of createMiddleware
Source: https://docs.solidjs.com/solid-start/v2/reference/server/create-middleware
Example showing how to compose middleware that checks the response from the next handler.
```typescript
import { createMiddleware } from "@solidjs/start/middleware";
export default createMiddleware([
async (event, next) => {
const response = await next();
if (response instanceof Response) return response;
return new Response("Not found", { status: 404 });
},
]);
```
--------------------------------
### Basic GET Usage
Source: https://docs.solidjs.com/solid-start/v2/reference/server/get
Demonstrates how to use GET to extract the GET property from an object-assigned function.
```typescript
import { GET } from "@solidjs/start";
const getMessage = Object.assign(async () => "hello", {
GET: async () => "hello",
});
const handler = GET(getMessage);
```
--------------------------------
### Advanced Vite Configuration with Nitro Settings
Source: https://docs.solidjs.com/solid-start/v2/reference/entrypoints/vite-config
An extended configuration example demonstrating how to pass middleware and serialization options to solidStart, and server/prerendering settings to the nitro property.
```typescript
import { nitro } from "nitro/vite";
import { defineConfig } from "vite";
import { solidStart } from "@solidjs/start/config";
export default defineConfig({
plugins: [
solidStart({
middleware: "./src/middleware/index.ts",
serialization: { mode: "json" },
}),
nitro(),
],
nitro: {
preset: "node_server",
prerender: {
routes: ["/"],
},
},
});
```
--------------------------------
### Install Nitro
Source: https://docs.solidjs.com/solid-start/v2/guides/deployment-plugins
Install the Nitro package using your preferred package manager.
```bash
npm i nitro
```
```bash
pnpm i nitro
```
```bash
yarn add nitro
```
```bash
bun i nitro
```
```bash
deno add npm:nitro
```
--------------------------------
### Basic usage of clientOnly
Source: https://docs.solidjs.com/solid-start/v2/reference/client/client-only
Example demonstrating how to wrap a component import with clientOnly and provide a fallback component.
```typescript
import { clientOnly } from "@solidjs/start";
const Map = clientOnly(() => import("./Map"), { lazy: true });
export default function Page() {
return Loading map...} />;
}
```
--------------------------------
### Install Cloudflare Vite Plugin
Source: https://docs.solidjs.com/solid-start/v2/guides/deployment-plugins
Install the Cloudflare Vite plugin and wrangler as development dependencies.
```bash
npm i @cloudflare/vite-plugin wrangler -D
```
```bash
pnpm i @cloudflare/vite-plugin wrangler -D
```
```bash
yarn add @cloudflare/vite-plugin wrangler -D
```
```bash
bun i @cloudflare/vite-plugin wrangler -d
```
```bash
deno add npm:@cloudflare/vite-plugin wrangler -D
```
--------------------------------
### GET(fn)
Source: https://docs.solidjs.com/solid-start/v2/reference/server/get
The GET function takes a function as an argument and returns its .GET property.
```APIDOC
## GET(fn)
### Description
Extracts the .GET property from a provided function.
### Parameters
- **fn** (function) - Required - A function that contains a .GET property.
### Return Value
- **Returns** (function) - The .GET property of the provided function.
### Example
```javascript
import { GET } from "@solidjs/start";
const getMessage = Object.assign(async () => "hello", {
GET: async () => "hello",
});
const handler = GET(getMessage);
```
```
--------------------------------
### Basic usage of HttpStatusCode
Source: https://docs.solidjs.com/solid-start/v2/reference/server/http-status-code
Example showing how to use the component to return a 404 status code.
```typescript
import { HttpStatusCode } from "@solidjs/start";
export default function NotFound() {
return ;
}
```
--------------------------------
### Importing Assets with Vite
Source: https://docs.solidjs.com/solid-start/v2/building-your-application/static-assets
Example of importing an asset directly into a component, which results in a hashed filename for cache busting.
```jsx
import logo from "./solid.png";
export default function About() {
return (
<>
About
// Renders
>
);
}
```
--------------------------------
### Referencing Public Assets
Source: https://docs.solidjs.com/solid-start/v2/building-your-application/static-assets
Example of using an absolute path to reference an asset stored in the public directory.
```jsx
export default function About() {
return (
<>
About
>
);
}
```
--------------------------------
### Triggering an action with useAction
Source: https://docs.solidjs.com/solid-start/v2/guides/data-mutation
This example demonstrates defining an action and invoking it via a button click using the useAction hook.
```TypeScript
// src/routes/index.tsx
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)} />
addPostAction(title())}>Add Post
);
}
```
```JavaScript
// src/routes/index.jsx
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)} />
addPostAction(title())}>Add Post
);
}
```
--------------------------------
### Basic HttpHeader Usage
Source: https://docs.solidjs.com/solid-start/v2/reference/server/http-header
Example of using HttpHeader to set a cache-control header in a page component.
```typescript
import { HttpHeader } from "@solidjs/start";
export default function Page() {
return ;
}
```
--------------------------------
### GET Type Definition
Source: https://docs.solidjs.com/solid-start/v2/reference/server/get
The type signature for the GET function.
```typescript
function GET any>(
fn: T
): (...args: Parameters) => ReturnType;
```
--------------------------------
### Initialize a new SolidStart project
Source: https://docs.solidjs.com/solid-start/v2/getting-started
Use the scaffolding tool to create a new application. Requires Node.js 24 or newer.
```bash
npm init solid
```
```bash
pnpm create solid
```
```bash
yarn create solid
```
```bash
bun create solid
```
```bash
deno init --npm solid
```
--------------------------------
### StartClient()
Source: https://docs.solidjs.com/solid-start/v2/reference/client/start-client
The StartClient component renders the generated solid-start:app module wrapped in a shared ErrorBoundary.
```APIDOC
## StartClient()
### Description
Renders the generated application inside the client error boundary. This component is typically used in the client-side entry point.
### Signature
`function StartClient(): JSX.Element`
### Parameters
- None
### Return Value
- **Type:** `JSX.Element` - The client app element.
### Example
```javascript
import { mount, StartClient } from "@solidjs/start/client";
mount(() => , document.getElementById("app")!);
```
```
--------------------------------
### StartServer(props: { document: Component })
Source: https://docs.solidjs.com/solid-start/v2/reference/server/start-server
The StartServer component renders the application inside a specified document component. It automatically registers assets, renders the DOCTYPE, and injects the application content.
```APIDOC
## StartServer
### Description
`StartServer` is a component that renders the generated app inside the provided document component. It reads the current request event, registers page assets, and wraps the app with error boundaries.
### Signature
`function StartServer(props: { document: Component }): JSX.Element;`
### Props
- **document** (Component) - Required - The document component rendered around the app.
### DocumentComponentProps
- **assets** (JSX.Element) - Optional - Assets to be rendered in the head.
- **scripts** (JSX.Element) - Required - Scripts to be rendered in the document.
- **children** (JSX.Element) - Optional - The application content.
### Example
```javascript
import { createHandler, StartServer } from "@solidjs/start/server";
function Document(props) {
return (
{props.assets}
{props.children}
{props.scripts}
);
}
export default createHandler((event) => );
```
```
--------------------------------
### solidStart(options?: SolidStartOptions)
Source: https://docs.solidjs.com/solid-start/v2/reference/config/solid-start
Initializes the SolidStart Vite plugin. This function should be included in the plugins array of your Vite configuration.
```APIDOC
## solidStart
### Description
Returns the Vite plugins required to build and run a SolidStart application with Vite's Environment API.
### Signature
`function solidStart(options?: SolidStartOptions): PluginOption[];`
### Usage
```javascript
import { nitro } from "nitro/vite";
import { defineConfig } from "vite";
import { solidStart } from "@solidjs/start/config";
export default defineConfig({
plugins: [solidStart(), nitro()],
});
```
```
--------------------------------
### Importing mount and StartClient
Source: https://docs.solidjs.com/solid-start/v2/reference/entrypoints/entry-client
Required imports for initializing the client-side application.
```typescript
import { mount, StartClient } from "@solidjs/start/client";
```
--------------------------------
### Import StartClient
Source: https://docs.solidjs.com/solid-start/v2/reference/client/start-client
Import the StartClient component from the @solidjs/start/client package.
```typescript
import { StartClient } from "@solidjs/start/client";
```
--------------------------------
### Import StartServer
Source: https://docs.solidjs.com/solid-start/v2/reference/server/start-server
Import the StartServer component from the server package.
```typescript
import { StartServer } from "@solidjs/start/server";
```
--------------------------------
### solidStart Configuration
Source: https://docs.solidjs.com/solid-start/v2/reference/config/solid-start
The solidStart function accepts an options object to configure the behavior of the SolidStart framework, including routing, server functions, and environment variables.
```APIDOC
## solidStart(options)
### Description
Configures the SolidStart framework via the `solidStart` function, typically used in the Vite configuration file.
### Parameters
- **appRoot** (string) - Optional - Path to the directory containing app.tsx or app.jsx. Default: "./src"
- **ssr** (boolean) - Optional - Enables server-side rendering. Default: true
- **devOverlay** (boolean) - Optional - Controls the development toolbar. Default: true
- **experimental.islands** (false) - Optional - Reserved for islands architecture support. Default: false
- **routeDir** (string) - Optional - Route directory relative to appRoot. Default: "./routes"
- **extensions** (string[]) - Optional - Additional file extensions for the router and compiler. Default: []
- **middleware** (string) - Optional - Path to the module that default-exports middleware.
- **serialization** (object) - Optional - Controls server-function argument and result serialization. { mode?: "json" | "js"; plugins?: string }
- **solid** (Partial) - Optional - Options forwarded to vite-plugin-solid.
- **serverFunctions.filter** (object) - Optional - Customizes which files the "use server" compiler scans. { include?: FilterPattern; exclude?: FilterPattern }
- **serverFunctions.onError** (string) - Optional - Path to a module whose default export handles values thrown by server functions.
- **env** (object) - Optional - Configures environment-variable virtual modules.
```
--------------------------------
### Run production build
Source: https://docs.solidjs.com/solid-start/v2/migrating-from-v1
Commands to build the application for production across different package managers.
```bash
npm run build
```
```bash
pnpm build
```
```bash
yarn build
```
```bash
bun run build
```
```bash
deno run build
```
--------------------------------
### Basic usage of StartClient
Source: https://docs.solidjs.com/solid-start/v2/reference/client/start-client
Mount the StartClient component to a DOM element using the mount function.
```typescript
import { mount, StartClient } from "@solidjs/start/client";
mount(() => , document.getElementById("app")!);
```
--------------------------------
### Implement Server Function Error Handler
Source: https://docs.solidjs.com/solid-start/v2/reference/config/solid-start
Example implementation of a server function error handler that captures exceptions and returns a sanitized error.
```typescript
import type { ServerFunctionErrorHandler } from "@solidjs/start/server";
import { captureException } from "./your-monitoring-client";
const onServerFunctionError: ServerFunctionErrorHandler = (thrown) => {
// redirect() throws a Response, so returning it preserves that control flow.
if (thrown instanceof Response) {
return thrown;
}
captureException(thrown); // or console.error, or any reporter
return new Error("The server function failed.");
};
export default onServerFunctionError;
```
--------------------------------
### Import getServerFunctionMeta
Source: https://docs.solidjs.com/solid-start/v2/reference/server/get-server-function-meta
Import the function from the @solidjs/start package.
```typescript
import { getServerFunctionMeta } from "@solidjs/start";
```
--------------------------------
### Import createMiddleware
Source: https://docs.solidjs.com/solid-start/v2/reference/server/create-middleware
Import the function from the @solidjs/start/middleware package.
```typescript
import { createMiddleware } from "@solidjs/start/middleware";
```
--------------------------------
### Use request helpers
Source: https://docs.solidjs.com/solid-start/v2/building-your-application/api-routes
Import helpers from @solidjs/start/http to manage cookies, sessions, and headers within an API route.
```typescript
import { getCookie } from "@solidjs/start/http";
import type { APIEvent } from "@solidjs/start/server";
export function GET(_event: APIEvent) {
const userId = getCookie("userId");
if (!userId) {
return new Response("Not logged in", { status: 401 });
}
return Response.json({ userId });
}
```
--------------------------------
### Importing solidStart
Source: https://docs.solidjs.com/solid-start/v2/reference/config/solid-start
Import the solidStart function from the @solidjs/start/config package.
```typescript
import { solidStart } from "@solidjs/start/config";
```
--------------------------------
### Import clientOnly
Source: https://docs.solidjs.com/solid-start/v2/reference/client/client-only
Import the clientOnly utility from the @solidjs/start package.
```typescript
import { clientOnly } from "@solidjs/start";
```
--------------------------------
### Importing mount
Source: https://docs.solidjs.com/solid-start/v2/reference/client/mount
Import the mount function from the @solidjs/start/client package.
```typescript
import { mount } from "@solidjs/start/client";
```
--------------------------------
### mount(callback, element)
Source: https://docs.solidjs.com/solid-start/v2/reference/entrypoints/entry-client
Mounts the SolidStart application to a specified DOM element.
```APIDOC
## mount(callback, element)
### Description
Initializes the client-side application by mounting the StartClient component into the provided DOM element.
### Parameters
- **callback** (function) - Required - A function that returns the StartClient component.
- **element** (HTMLElement) - Required - The DOM element where the application will be mounted.
### Example
```javascript
import { mount, StartClient } from "@solidjs/start/client";
mount(() => , document.getElementById("app")!);
```
```
--------------------------------
### Configure Vite for SolidStart
Source: https://docs.solidjs.com/solid-start/v2/getting-started
Basic Vite configuration using the solidStart plugin.
```typescript
import { defineConfig } from "vite";
import { solidStart } from "@solidjs/start/config";
export default defineConfig({
plugins: [solidStart()],
});
```
--------------------------------
### Configure Netlify Plugin
Source: https://docs.solidjs.com/solid-start/v2/guides/deployment-plugins
Enable build support in the Netlify plugin within the Vite configuration.
```javascript
import netlify from "@netlify/vite-plugin";
import { defineConfig } from "vite";
import { solidStart } from "@solidjs/start/config";
export default defineConfig({
plugins: [solidStart(), netlify({ build: { enabled: true } })],
});
```
--------------------------------
### StartServer Type Definitions
Source: https://docs.solidjs.com/solid-start/v2/reference/server/start-server
Type definitions for the DocumentComponentProps and the StartServer component signature.
```typescript
type DocumentComponentProps = {
assets?: JSX.Element;
scripts: JSX.Element;
children?: JSX.Element;
};
function StartServer(props: {
document: Component;
}): JSX.Element;
```
--------------------------------
### Importing server utilities
Source: https://docs.solidjs.com/solid-start/v2/reference/entrypoints/entry-server
Required imports for configuring the server entry point.
```typescript
import { createHandler, StartServer } from "@solidjs/start/server";
```
--------------------------------
### Configure Middleware
Source: https://docs.solidjs.com/solid-start/v2/advanced/middleware
Define a middleware function using createMiddleware and register it in the SolidStart configuration.
```typescript
import { createMiddleware } from "@solidjs/start/middleware";
export default createMiddleware([
async (event, next) => {
console.log("Request received:", event.req.url);
const startedAt = Date.now();
const response = await next();
console.log(`Request took ${Date.now() - startedAt}ms`);
return response;
},
]);
```
```typescript
import { nitro } from "nitro/vite";
import { defineConfig } from "vite";
import { solidStart } from "@solidjs/start/config";
export default defineConfig({
plugins: [solidStart({ middleware: "./src/middleware/index.ts" }), nitro()],
});
```
--------------------------------
### Import HttpHeader
Source: https://docs.solidjs.com/solid-start/v2/reference/server/http-header
Import the HttpHeader component from the @solidjs/start package.
```typescript
import { HttpHeader } from "@solidjs/start";
```
--------------------------------
### Import HttpStatusCode
Source: https://docs.solidjs.com/solid-start/v2/reference/server/http-status-code
Import the component from the @solidjs/start package.
```typescript
import { HttpStatusCode } from "@solidjs/start";
```
--------------------------------
### Configure Vite with middleware
Source: https://docs.solidjs.com/solid-start/v2/getting-started
Pass a middleware path to the solidStart plugin configuration.
```typescript
import { defineConfig } from "vite";
import { solidStart } from "@solidjs/start/config";
export default defineConfig({
plugins: [solidStart({ middleware: "./src/middleware/index.ts" })],
});
```
--------------------------------
### Basic usage of createHandler
Source: https://docs.solidjs.com/solid-start/v2/reference/server/create-handler
Standard implementation of createHandler using the StartServer component.
```typescript
import { createHandler, StartServer } from "@solidjs/start/server";
export default createHandler((event) => );
```
--------------------------------
### Update HTTP helper imports
Source: https://docs.solidjs.com/solid-start/v2/migrating-from-v1
Replace imports from vinxi/http with @solidjs/start/http.
```typescript
import { getCookie, setCookie, useSession } from "@solidjs/start/http";
```
--------------------------------
### Import createHandler
Source: https://docs.solidjs.com/solid-start/v2/reference/server/create-handler
Import the createHandler function from the @solidjs/start/server package.
```typescript
import { createHandler } from "@solidjs/start/server";
```
--------------------------------
### Configure MetaProvider in Root
Source: https://docs.solidjs.com/solid-start/v2/building-your-application/head-and-metadata
Wrap the application router with MetaProvider to enable metadata collection during server rendering and client navigation.
```javascript
import { MetaProvider } from "@solidjs/meta";
import { Router } from "@solidjs/router";
import { FileRoutes } from "@solidjs/start/router";
import { Suspense } from "solid-js";
export default function App() {
return (
(
{props.children}
)}
>
);
}
```
--------------------------------
### Import FileRoutes
Source: https://docs.solidjs.com/solid-start/v2/reference/routing/file-routes
Import the FileRoutes component from the @solidjs/start/router package.
```typescript
import { FileRoutes } from "@solidjs/start/router";
```
--------------------------------
### Configure middleware in solidStart
Source: https://docs.solidjs.com/solid-start/v2/migrating-from-v1
Pass the middleware path to the solidStart plugin configuration.
```typescript
import { defineConfig } from "vite";
import { nitro } from "nitro/vite";
import { solidStart } from "@solidjs/start/config";
export default defineConfig({
plugins: [solidStart({ middleware: "./src/middleware/index.ts" }), nitro()],
});
```
--------------------------------
### StartClient Type Definition
Source: https://docs.solidjs.com/solid-start/v2/reference/client/start-client
The function signature for the StartClient component.
```typescript
function StartClient(): JSX.Element;
```
--------------------------------
### Register custom Seroval plugins
Source: https://docs.solidjs.com/solid-start/v2/advanced/serialization
Point to a module containing custom Seroval plugins in the solidStart configuration.
```typescript
import { defineConfig } from "vite";
import { solidStart } from "@solidjs/start/config";
export default defineConfig({
plugins: [
solidStart({
serialization: {
plugins: "src/seroval-plugins.ts",
},
}),
],
});
```
--------------------------------
### mount(fn, el)
Source: https://docs.solidjs.com/solid-start/v2/reference/client/mount
Hydrates the client application into the provided DOM element.
```APIDOC
## mount(fn, el)
### Description
Mounts the client application by hydrating the provided element. This function is equivalent to the standard Solid `hydrate` function.
### Signature
`function mount(fn: () => JSX.Element, el: MountableElement): (() => void) | undefined;`
### Parameters
- **fn** (() => JSX.Element) - Required - A function that returns the client app element.
- **el** (MountableElement) - Required - The DOM element used as the hydration root.
### Return Value
- **(() => void) | undefined** - Returns the result of the hydration process.
### Example
```javascript
import { mount, StartClient } from "@solidjs/start/client";
mount(() => , document.getElementById("app")!);
```
```
--------------------------------
### Importing Global CSS
Source: https://docs.solidjs.com/solid-start/v2/building-your-application/css-and-styling
Use standard ESM syntax to import CSS files for global application styling.
```tsx
import "./Card.css";
const Card = (props) => {
return (
{props.title}
{props.text}
);
};
```
```css
.card {
background-color: #446b9e;
}
h1 {
font-size: 1.5em;
font-weight: bold;
}
p {
font-size: 1em;
font-weight: normal;
}
```
--------------------------------
### Defining solidStart Type
Source: https://docs.solidjs.com/solid-start/v2/reference/config/solid-start
The solidStart function accepts optional configuration and returns an array of Vite PluginOptions.
```typescript
function solidStart(options?: SolidStartOptions): PluginOption[];
```
--------------------------------
### Create a basic API route
Source: https://docs.solidjs.com/solid-start/v2/building-your-application/api-routes
Define an API route by exporting an HTTP method function from a file in the src/routes directory.
```typescript
export function GET() {
return new Response("pong");
}
```
--------------------------------
### Implementing Protected Routes with Solid Router
Source: https://docs.solidjs.com/solid-start/v2/advanced/auth
Redirects unauthenticated users to a login page during data fetching. Requires deferStream: true to handle redirects before streaming begins.
```javascript
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 });
}
```
--------------------------------
### Configure Environment Variable Modules
Source: https://docs.solidjs.com/solid-start/v2/reference/config/solid-start
Customizes the prefixes and runtime environments for virtual environment modules.
```javascript
solidStart({
env: {
server: { prefix: "PRIVATE_", runtime: "node" },
client: { prefix: "PUBLIC_" },
},
});
```
--------------------------------
### createHandler(fn, options?, routerLoad?)
Source: https://docs.solidjs.com/solid-start/v2/reference/server/create-handler
Creates the handler used by the server entry to render the application.
```APIDOC
## createHandler(fn, options?, routerLoad?)
### Description
Creates the handler used by the server entry. This function defines how the application is rendered on the server.
### Parameters
- **fn** ((context: PageEvent) => JSX.Element) - Required - Function that returns the server-rendered document.
- **options** (HandlerOptions | (context: PageEvent) => HandlerOptions | Promise) - Optional - Rendering options or a function that returns rendering options.
- **routerLoad** ((event: FetchEvent) => Promise) - Optional - Optional setup function for a custom router.
### HandlerOptions Fields
- **mode** ("sync" | "async" | "stream") - Optional - Rendering mode (default: "stream").
- **nonce** (string) - Optional - Nonce assigned to the page event.
- **renderId** (string) - Optional - Render identifier passed to the render context.
- **onCompleteAll** ((options: { write: (value: any) => void }) => void) - Optional - Callback used when all stream content is ready.
- **onCompleteShell** ((options: { write: (value: any) => void }) => void) - Optional - Callback used when the shell stream is ready.
### Return Value
- **StartHandler** - Returns the H3 application used by the server entry.
```
--------------------------------
### Handle Headers and Cookies
Source: https://docs.solidjs.com/solid-start/v2/advanced/middleware
Access and set cookies or headers using SolidStart's HTTP helpers within middleware.
```typescript
import { getCookie, setCookie } from "@solidjs/start/http";
import { createMiddleware } from "@solidjs/start/middleware";
export default createMiddleware([
async (event, next) => {
const theme = getCookie("theme") ?? "system";
setCookie("theme", theme, {
httpOnly: true,
secure: true,
sameSite: "lax",
});
const response = await next();
event.res.headers.set("x-theme", theme);
return response;
},
]);
```
--------------------------------
### Pre-render specific routes
Source: https://docs.solidjs.com/solid-start/v2/building-your-application/route-prerendering
Explicitly define a list of routes to be pre-rendered during the build process.
```javascript
import { nitro } from "nitro/vite";
import { defineConfig } from "vite";
import { solidStart } from "@solidjs/start/config";
export default defineConfig({
plugins: [solidStart(), nitro()],
nitro: {
prerender: {
routes: ["/", "/about"],
},
},
});
```
--------------------------------
### createMiddleware(args: Middleware[])
Source: https://docs.solidjs.com/solid-start/v2/reference/server/create-middleware
Composes an array of H3 middleware. Middleware can execute logic before or after the next handler in the chain by awaiting the next() function.
```APIDOC
## createMiddleware(args)
### Description
Composes an array of H3 middleware for handling requests and responses. Each middleware receives the event and a next function.
### Parameters
- **args** (Middleware[]) - Required - An array of H3 middleware to be composed.
### Return Value
- **Returns** (Middleware[]) - The composed middleware array.
### Usage Example
```javascript
import { createMiddleware } from "@solidjs/start/middleware";
export default createMiddleware([
async (event, next) => {
const response = await next();
if (response instanceof Response) return response;
return new Response("Not found", { status: 404 });
},
]);
```
```
--------------------------------
### Using CSS Modules
Source: https://docs.solidjs.com/solid-start/v2/building-your-application/css-and-styling
Apply locally scoped styles by using files with .module.css extensions and referencing the imported object.
```tsx
import styles from "./Card.module.css";
const Card = (props) => {
return (
{props.title}
{props.text}
);
};
```
```css
.card {
background-color: #446b9e;
}
div.card > h1 {
font-size: 1.5em;
font-weight: bold;
}
div.card > p {
font-size: 1em;
font-weight: normal;
}
```
--------------------------------
### Configure Cloudflare Plugin
Source: https://docs.solidjs.com/solid-start/v2/guides/deployment-plugins
Map the Worker to the ssr environment using the cloudflare plugin.
```javascript
import { cloudflare } from "@cloudflare/vite-plugin";
import { defineConfig } from "vite";
import { solidStart } from "@solidjs/start/config";
export default defineConfig({
plugins: [cloudflare({ viteEnvironment: { name: "ssr" } }), solidStart()],
});
```
--------------------------------
### Apply "use server" as a file directive
Source: https://docs.solidjs.com/solid-start/v2/reference/server/use-server
Place the directive at the top of a file to mark all exported async functions as server functions.
```typescript
"use server";
export async function logMessage(message: string) {
console.log(message);
}
```
--------------------------------
### clientOnly(fn, options)
Source: https://docs.solidjs.com/solid-start/v2/reference/client/client-only
Wraps an async component import to ensure it only renders on the client, with support for a fallback component during server-side rendering.
```APIDOC
## clientOnly(fn, options)
### Description
Wraps an async component import and renders a fallback on the server. The client loads the component immediately unless lazy loading is enabled.
### Parameters
- **fn** (() => Promise<{ default: T }>) - Required - Function that imports the client component.
- **options** ({ lazy?: boolean }) - Optional - Loading options. A truthy lazy defers the import to the returned component.
### Return Value
- Returns a component that accepts props and an optional fallback JSX element.
### Example
```javascript
import { clientOnly } from "@solidjs/start";
const Map = clientOnly(() => import("./Map"), { lazy: true });
export default function Page() {
return Loading map...} />;
}
```
```
--------------------------------
### createHandler
Source: https://docs.solidjs.com/solid-start/v2/reference/entrypoints/entry-server
The createHandler function is used to define the server entry point, receiving a PageEvent and returning a handler for the application.
```APIDOC
## createHandler
### Description
Creates an event handler for the server entry point, typically used to render the StartServer component.
### Parameters
- **callback** (function) - Required - A function that receives a `PageEvent` and returns the JSX to be rendered, usually containing the `StartServer` component.
### Example
```typescript
import { createHandler, StartServer } from "@solidjs/start/server";
export default createHandler((event) => );
```
```
--------------------------------
### Configure Middleware
Source: https://docs.solidjs.com/solid-start/v2/reference/config/solid-start
Sets the path to the module that default-exports middleware.
```javascript
solidStart({ middleware: "./src/middleware/index.ts" });
```
--------------------------------
### Configuring TypeScript types for environment
Source: https://docs.solidjs.com/solid-start/v2/advanced/request-events
Include the @solidjs/start/env type entry in tsconfig.json to provide the base namespace for request locals.
```json
{
"compilerOptions": {
"types": ["@solidjs/start/env"]
}
}
```
--------------------------------
### Apply Nonce in entry-server.tsx
Source: https://docs.solidjs.com/solid-start/v2/guides/security
Passes the nonce from the request locals to the StartServer component.
```typescript
// src/entry-server.tsx
// @refresh reload
import { createHandler, StartServer } from "@solidjs/start/server";
export default createHandler(
() => ,
(event) => ({ nonce: event.locals.nonce })
);
```
--------------------------------
### Remove legacy dependencies
Source: https://docs.solidjs.com/solid-start/v2/migrating-from-v1
Commands to remove deprecated packages used in SolidStart v1.
```bash
npm remove vinxi @solidjs/vite-plugin-nitro-2 nitropack
```
```bash
pnpm remove vinxi @solidjs/vite-plugin-nitro-2 nitropack
```
```bash
yarn remove vinxi @solidjs/vite-plugin-nitro-2 nitropack
```
```bash
bun remove vinxi @solidjs/vite-plugin-nitro-2 nitropack
```
```bash
deno remove npm:vinxi @solidjs/vite-plugin-nitro-2 nitropack
```
--------------------------------
### Importing CSS via URL
Source: https://docs.solidjs.com/solid-start/v2/building-your-application/css-and-styling
Mount complex global CSS files specifically for a route using the ?url import suffix and the Link component.
```tsx
import { Link } from "@solidjs/meta";
import styleUrl from "./about.css?url";
export default function About() {
return (
About us
);
}
```
```css
@import "tailwindcss";
```
--------------------------------
### Enable link crawling for pre-rendering
Source: https://docs.solidjs.com/solid-start/v2/building-your-application/route-prerendering
Configure the crawler to automatically discover and pre-render routes by following links found in the generated HTML.
```javascript
export default defineConfig({
plugins: [solidStart(), nitro()],
nitro: {
prerender: {
crawlLinks: true,
failOnError: true,
},
},
});
```
--------------------------------
### Import using path alias
Source: https://docs.solidjs.com/solid-start/v2/getting-started
Use the built-in ~ alias to import files from the application root.
```typescript
import { db } from "~/lib/db";
```
--------------------------------
### Configure Nitro Plugin
Source: https://docs.solidjs.com/solid-start/v2/guides/deployment-plugins
Add the nitro plugin to the Vite configuration after the solidStart plugin.
```javascript
import { nitro } from "nitro/vite";
import { defineConfig } from "vite";
import { solidStart } from "@solidjs/start/config";
export default defineConfig({
plugins: [solidStart(), nitro()],
});
```
--------------------------------
### Update package.json scripts
Source: https://docs.solidjs.com/solid-start/v2/migrating-from-v1
Replace Vinxi scripts with standard Vite scripts.
```json
{
"scripts": {
"dev": "vite dev",
"build": "vite build",
"preview": "vite preview"
}
}
```
--------------------------------
### Define and consume a basic query
Source: https://docs.solidjs.com/solid-start/v2/building-your-application/data-fetching
Use query to define a cached data fetcher and createAsync to access the data within a component.
```typescript
import { For } from "solid-js";
import { createAsync, query } from "@solidjs/router";
const getPosts = query(async () => {
const response = await fetch("https://example.com/api/posts");
return response.json() as Promise>;
}, "posts");
export default function PostsPage() {
const posts = createAsync(() => getPosts());
return {(post) => {post.title} } ;
}
```
--------------------------------
### Fetch data with query and createAsync
Source: https://docs.solidjs.com/solid-start/v2/guides/data-fetching
Use the query primitive to define a data fetcher and createAsync to consume the result in a component.
```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 (
);
}
```
```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 (
);
}
```
--------------------------------
### Prefill action arguments
Source: https://docs.solidjs.com/solid-start/v2/building-your-application/data-mutation
Uses the .with() method to bind specific arguments to an action before it is triggered by a form.
```typescript
import { action } from "@solidjs/router";
const archiveProject = action(async (projectId: string, formData: FormData) => {
"use server";
return {
projectId,
reason: formData.get("reason")?.toString() ?? null,
};
}, "archiveProject");
export default function ProjectPage(props: { params: { id: string } }) {
return (
);
}
```
--------------------------------
### Connect to WebSocket from Browser
Source: https://docs.solidjs.com/solid-start/v2/advanced/websocket
Use the standard browser WebSocket API to connect to the defined server endpoint.
```javascript
const protocol = location.protocol === "https:" ? "wss:" : "ws:";
const socket = new WebSocket(`${protocol}//${location.host}/ws`);
socket.addEventListener("open", () => socket.send("Hello"));
socket.addEventListener("message", (event) => console.log(event.data));
```
--------------------------------
### Define a Background Task
Source: https://docs.solidjs.com/solid-start/v2/guides/background-tasks
Create a task by exporting a defineTask object in a file within the server/tasks directory.
```typescript
import { defineTask } from "nitro/task";
export default defineTask({
meta: {
name: "db:cleanup",
description: "Remove expired sessions",
},
async run({ payload, context }) {
const cleanup = deleteExpiredSessions();
context.waitUntil?.(cleanup);
const deleted = await cleanup;
return {
result: { deleted, requestedBy: payload.requestedBy },
};
},
});
```
--------------------------------
### Basic app.tsx usage
Source: https://docs.solidjs.com/solid-start/v2/reference/entrypoints/app
Standard implementation of the root component using the Router and FileRoutes components.
```tsx
import { Router } from "@solidjs/router";
import { FileRoutes } from "@solidjs/start/router";
export default function App() {
return (
);
}
```
--------------------------------
### Implement loading UI with Suspense
Source: https://docs.solidjs.com/solid-start/v2/guides/data-fetching
Wrap data-dependent components in a Suspense boundary with a fallback prop to display loading states.
```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} }
);
}
```
--------------------------------
### Configure CSP without Nonce
Source: https://docs.solidjs.com/solid-start/v2/guides/security
Sets a static Content-Security-Policy header after the downstream handler returns.
```typescript
import { createMiddleware } from "@solidjs/start/middleware";
export default createMiddleware([
async (event, next) => {
const response = await next();
const csp = `
default-src 'self';
font-src 'self' ;
object-src 'none';
base-uri 'none';
frame-ancestors 'none';
form-action 'self';
`.replace(/\s+/g, " ");
event.res.headers.set("Content-Security-Policy", csp);
return response;
},
]);
```
--------------------------------
### Define a WebSocket Server Handler
Source: https://docs.solidjs.com/solid-start/v2/advanced/websocket
Create a server route using defineWebSocketHandler to manage connection lifecycles and messaging.
```typescript
import { defineWebSocketHandler } from "nitro";
export default defineWebSocketHandler({
open(peer) {
console.log("open", peer.id);
peer.send("Connected");
},
message(peer, message) {
console.log("message", peer.id, message.text());
peer.send(message.text());
},
close(peer, details) {
console.log("close", peer.id, details.code, details.reason);
},
error(peer, error) {
console.error("websocket error", peer.id, error);
},
});
```
--------------------------------
### Define the "use server" directive constant
Source: https://docs.solidjs.com/solid-start/v2/reference/server/use-server
Represents the directive string used by the compiler.
```typescript
const DIRECTIVE = "use server";
```
--------------------------------
### Configure serialization mode in Vite
Source: https://docs.solidjs.com/solid-start/v2/advanced/serialization
Set the serialization mode in the solidStart plugin configuration within vite.config.ts.
```typescript
import { defineConfig } from "vite";
import { solidStart } from "@solidjs/start/config";
export default defineConfig({
plugins: [
solidStart({
serialization: { mode: "json" },
}),
],
});
```
--------------------------------
### Implement middleware using createMiddleware
Source: https://docs.solidjs.com/solid-start/v2/migrating-from-v1
Define middleware using the createMiddleware function with an array of H3 v2 handlers.
```typescript
import { createMiddleware } from "@solidjs/start/middleware";
export default createMiddleware([
async (event, next) => {
event.context.startedAt = Date.now();
const response = await next();
console.log(`Request took ${Date.now() - event.context.startedAt}ms`);
return response;
},
]);
```
--------------------------------
### Configure Server Function Error Handling
Source: https://docs.solidjs.com/solid-start/v2/reference/config/solid-start
Sets the path to a module that handles errors thrown by server functions before serialization.
```javascript
solidStart({
serverFunctions: {
onError: "src/server-function-error.ts",
},
});
```