W↓
All docs
🔑
Sign Up/Sign In
docs.solidjs.com/solid-start/reference/
Public Link
Apr 8, 2025, 10:22:46 AM - complete - 19.5 kB
Starting URLs:
https://docs.solidjs.com/solid-start/reference/entrypoints/app-config
Crawl Prefixes:
https://docs.solidjs.com/solid-start/reference/
## Page: https://docs.solidjs.com/solid-start/reference/entrypoints/app-config The `app.config.ts` is the root of every SolidStart app and the main point of configuration. This file exports a configuration for SolidStart, Vinxi, Vite and Nitro. The easiest way to generate a configuration is to use the `defineConfig` helper. Here `defineConfig` is used to create a minimal configuration with default settings. import { defineConfig } from "@solidjs/start/config";export default defineConfig({}); To see more configuration options, see `defineConfig`. --- ## Page: https://docs.solidjs.com/solid-start/reference/entrypoints/app The `App` component is the isomorphic (shared on server and browser) entry point into your application. This is where the code runs on both sides. This is like the classic entry point where you can define your router, and other top level components. This is where routers setup navigation between the pages discovered by the `FileRouter`. import { A, Router } from "@solidjs/router";import { FileRoutes } from "@solidjs/start/router";import { Suspense } from "solid-js";export default function App() { return ( <Router root={(props) => ( <A href="/">Index</A> <A href="/about">About</A> <Suspense>{props.children}</Suspense> )} > <FileRoutes /> </Router> );} Since SolidStart does not come packaged with a router, you can simply return your template of choice: --- ## Page: https://docs.solidjs.com/solid-start/reference/entrypoints/entry-client `entry-client.tsx` is where an application starts in the browser. It does this by passing `<StartClient>` and a DOM Element (the mounting point), to the `mount` function. import { mount, StartClient } from "@solidjs/start/client";mount(() => <StartClient />, document.getElementById("app")!); This file is an ideal place to run any client specific code that is needed on startup, such as registering service workers. This is important if you are performing client-only rendering or using other modes of server-side rendering. --- ## Page: https://docs.solidjs.com/solid-start/reference/entrypoints/entry-server `entry-server.tsx` is where an application starts on the server. This happens by `entry-server.tsx` providing a document component to `<StartServer>` and passing it into `createHandler` for server side rendering. A typical `entry-server.tsx` for a new project looks like this: import { createHandler, StartServer } from "@solidjs/start/server";export default createHandler(() => ( <StartServer document={({ assets, children, scripts }) => ( <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="icon" href="/favicon.ico" /> {assets} </head> <body> <div id="app">{children}</div> {scripts} </body> </html> )} />)); --- ## Page: https://docs.solidjs.com/solid-start/reference/config/define-config The `defineConfig` helper is from `@solidjs/start/config` and is used within `app.config.ts`. It takes a configuration object with settings for SolidStart, Vite, and Nitro. * * * SolidStart supports most Vite options, including plugins via the `vite` option: import { defineConfig } from "@solidjs/start/config";export default defineConfig({ vite: { // vite options plugins: [], },}); The `vite` option can also be a function that can be customized for each Vinxi router. In SolidStart, 3 routers are used: * `server` - server-side routing * `client` - for the client-side routing * `server-function` - server functions. import { defineConfig } from "@solidjs/start/config";export default defineConfig({ vite({ router }) { if (router === "server") { } else if (router === "client") { } else if (router === "server-function") { } return { plugins: [] }; },}); * * * SolidStart uses Nitro to run on a number of platforms. The `server` option exposes some Nitro options including the build and deployment presets. An overview of all available presets is available in the Deploy section of the Nitro documentation. Some common ones include: **Servers** * Node.js Server (`node`) (Default) * Deno Server (`deno_server`) * Bun Server (`bun`) **Providers** * Netlify Functions and Edge (`netlify`, `netlify-edge`) * Vercel Functions and Edge (`vercel`, `vercel-edge`) * AWS Lambda and Lambda@Edge (`aws_lambda`) * Cloudflare Workers and Pages (`cloudflare`, `cloudflare_pages`, `cloudflare_module`) * Deno Deploy (`deno_deploy`) **Static site generation** * Route pre-rendering By passing no arguments, the default will be the Node preset. Other presets may be automatically detected by the provider, however, if not, they must be added to the configuration within the `server-preset` option. For example, using Netlify Edge would look like the following: import { defineConfig } from "@solidjs/start/config";export default defineConfig({ server: { preset: "netlify_edge", },}); #### Special note SolidStart uses async local storage. Netlify, Vercel, and Deno support this out of the box but if you're using Cloudflare you will need to specify the following: import { defineConfig } from "@solidjs/start/config";export default defineConfig({ server: { preset: "cloudflare_module", rollupConfig: { external: ["__STATIC_CONTENT_MANIFEST", "node:async_hooks"], }, },}); Within `wrangler.toml` you will need to enable node compatibility: compatibility_flags = [ "nodejs_compat" ] * * * | Property | Type | Default | Description | | --- | --- | --- | --- | | ssr | boolean | true | Toggle between client and server rendering. | | solid | object | | Configuration object for vite-plugin-solid | | extensions | string\[\] | \["js", "jsx", "ts", "tsx"\] | Array of file extensions to be treated as routes. | | server | object | | Nitro server config options | | appRoot | string | "./src" | The path to the root of the application. | | routeDir | string | "./routes" | The path to where the routes are located. | | middleware | string | | The path to an optional middleware file. | | devOverlay | boolean | true | Toggle the dev overlay. | | experimental.islands | boolean | false | Enable "islands" mode. | | vite | `ViteConfig` or `({ router })=>ViteConfig` | | Vite config object. Can be configured for each `router` which has the string value "server", "client" or "server-function"\` | --- ## Page: https://docs.solidjs.com/solid-start/reference/routing/file-routes `FileRoutes` is a component that creates a `Route` for each file in the `/src/routes` directory. This creates a `route` export to define the route configuration for the router of your choice. import { Suspense } from "solid-js";import { Router } from "@solidjs/router";import { FileRoutes } from "@solidjs/start/router";export default function App() { return ( <Router root={(props) => <Suspense>{props.children}</Suspense>}> <FileRoutes /> </Router> );} caution If removing the `FileRoutes` component from your `app.tsx` file, you will need to manually add all of your routes. While this is possible it does come with tradeoffs. For example, optimizations such as preloaded script tags will no longer be available. --- ## Page: https://docs.solidjs.com/solid-start/reference/client/client-only ClientEdit this page Wrapping components in `clientOnly` will cause them render _only_ in the client. This can useful for components that interact directly with the DOM, such as jQuery, since they can not render on the server. It works similar to `lazy` but will only render _after hydration_ and will never load on the server. To use `clientOnly`, isolate the desired component with DOM interactions in a file: const location = window.document.location;export default function ClientOnlyComponent() { return <div>{location.href}</div>;} Once isolated, it can then be imported dynamically using `clientOnly`: import { clientOnly } from "@solidjs/start";const ClientOnlyComp = clientOnly(() => import("../ClientOnlyComp"));function IsomorphicComp() { return <ClientOnlyComp />;} **Note:** The `<ClientOnlyComp />` can take a fallback prop for when it is loading. * * * | Argument | Type | Description | | --- | --- | --- | | fn | `() => Promise` | Function to be run client-side only. | Report an issue with this page --- ## Page: https://docs.solidjs.com/solid-start/reference/client/mount `mount` is a method that calls either `hydrate` (server rendering) or `render` (client rendering) depending on the configuration. It is used in `entry-client.tsx` to bootstrap an application. import { mount, StartClient } from "@solidjs/start/client";mount(() => <StartClient />, document.getElementById("app")!); If you set `{ ssr: false }` in the `defineConfig`, effectively deactivating hydration, then `mount` becomes the same as `render`. * * * ## Parameters | Prop | type | description | | --- | --- | --- | | fn | () => JSX.Element | Function that returns the application code. | | el | MountableElement | DOM Element to mount the application to | --- ## Page: https://docs.solidjs.com/solid-start/reference/client/start-client `StartClient` is a component that wraps the application root. It can be passed to `mount` in the `entry-client.tsx`. import { StartClient } from "@solidjs/start/client"; --- ## Page: https://docs.solidjs.com/solid-start/reference/server/use-server `"use server"` will enable functions that only run on the server. const logHello = async (message: string) => { "use server"; console.log(message);}; **Note:** `"use server"` functions must be marked async or at least return a promise. * * * When using `"use server"`, regardless of whether server rendering is enabled, the functions it apply to will only run on the server. To do this, compilation is used to transform the `"use server"` function into an RPC call to the server. If `"use server"` is inserted as the first line in a file, the entire file will become server-only. "use server";const logHello = async (message: string) => { console.log(message);}; However, if `"use server"` is inserted as the first line of a function, only that function will be server-only: const logHello = async (message: string) => { "use server"; console.log(message);};logHello("Hello"); In both of these examples, the `logHello` function, it would only show in the server console regardless of whether rendering was on the server or in the browser. * * * Server functions can be used for fetching data and performing actions on the server. The following examples show how to use server functions alongside solid-router's data APIs. const getUser = query((id) => { "use server"; return db.getUser(id);}, "users");const updateUser = action(async (id, data) => { "use server" await db.setUser(id, data); throw redirect("/", { revalidate: getUser.keyFor(id) });}); When `getUser` or `updateUser` are invoked on the client, an http request will be made to the server, which calls the corresponding server function. * * * In the above example, when the `updateUser` action is called, a redirect is thrown on the server. Solid Start can handle this redirect on the server instead of propagating it to the client. The data for the redirected page is fetched and streamed to the client in the same http request as the `updateUser` action, rather than the client requiring a separate http request for the redirected page. * * * Server functions allow the serialization of many different data types in the response, using the Seroval serializer. The full list is available in Seroval's source code. * * * To get a stable function-specific identifier, even for parallel processes or multiple cpu cores or workers, use the `getServerFunctionMeta` --- ## Page: https://docs.solidjs.com/solid-start/reference/server/create-handler The `createHandler` is used to start the server in `entry-server.tsx`. It takes a function that returns a static document (often created with `<StartServer>`), and serves it using one of the three function for server side rendering (SSR): * `renderToString` - "sync" * `renderToStringAsync` - "async" * `renderToStream` - "stream" The SSR mode can be configured through the `mode` property on the options object: import { createHandler, StartServer } from "@solidjs/start/server";export default createHandler(() => ( <StartServer document={...} />), { mode: "async"}); * * * ## Parameters | Argument | Type | Default | Description | | --- | --- | --- | --- | | fn | fn: (context: PageEvent) | | A function that returns the static document for your application. | | options.mode | string | "stream" | The SSR mode. Options are 'sync', 'async' and 'stream'. | --- ## Page: https://docs.solidjs.com/solid-start/reference/server/create-middleware `createMiddleware` creates a configuration object for SolidStart that specifies when middleware functions are executed during the request lifecycle. There are two lifecycle events available: `onRequest` and `onBeforeResponse`. import { createMiddleware } from "@solidjs/start/middleware";export default createMiddleware({ onRequest: (event) => { console.log("Request received:", event.request.url); }, onBeforeResponse: (event) => { console.log("Sending response:", event.response.status); },}); import { defineConfig } from "@solidjs/start/config";export default defineConfig({ middleware: "src/middleware/index.ts",}); --- ## Page: https://docs.solidjs.com/solid-start/reference/server/get `GET` helps to create a server function which is accessed via an HTTP GET request. When this function is called, arguments are serialized into the URL, thus allowing the use of HTTP cache-control headers. For example, `GET` can be used to make a streaming promise with a 60 second cache life: import { json } from "@solidjs/router";import { GET } from "@solidjs/start";const hello = GET(async (name: string) => { "use server"; return json( { hello: new Promise<string>((r) => setTimeout(() => r(name), 1000)) }, { headers: { "cache-control": "max-age=60" } } );}); `GET<T extends (...args: any[]) => any>(fn: T): (...args: Parameters<T>) => ReturnType<T>` --- ## Page: https://docs.solidjs.com/solid-start/reference/server/get-server-function-meta `getServerFunctionMeta` returns a function-specific id string, that is stable across all instances when server functions are run in parallel on multiple CPU cores or workers. This `id` property can and _will_ change between builds. import { getServerFunctionMeta } from "@solidjs/start";// or some in-memory dbconst appCache: any = globalThis;const counter = async () => { "use server"; const { id } = getServerFunctionMeta()!; const key = `counter_${id}`; appCache[key] = appCache[key] ?? 0; appCache[key]++; return appCache[key] as number;}; --- ## Page: https://docs.solidjs.com/solid-start/reference/server/http-header ServerEdit this page `HttpHeader` provides a way to set headers on HTTPs response sent by the server. import { HttpHeader } from "@solidjs/start";<HttpHeader name="x-robots-tag" value="noindex" />; * * * import { HttpHeader, HttpStatusCode } from "@solidjs/start";export default function NotFound() { return ( <div> <HttpStatusCode code={404} /> <HttpHeader name="my-header" value="header-value" /> </div> );} As a page is rendered, you may want to add additional HTTP headers to the response and the `HttpHeader` component will do that for you. By passing it a `name` and `value`, they will get added to the `Response` headers sent back to the browser. When streaming responses with `renderToStream`, HTTP headers can only be added before the stream is first flushed. This requires adding `deferStream` to any resources that need to be loaded before responding. * * * | Property | Type | Description | | --- | --- | --- | | name | string | The name of the header to set | | value | string | The value of the header to set | Report an issue with this page --- ## Page: https://docs.solidjs.com/solid-start/reference/server/http-status-code `HttpStatusCode` sets the HTTP status code for the page response while server-side rendering. import { HttpStatusCode } from "@solidjs/start";<HttpStatusCode code={404} />; * * * As a page is rendered, you may want to set the status code to the `Response` depending on what happens. The `HttpStatusCode` component does this for you by taking the `code` passed in and setting it to the `Response` status in the browser. Since `HttpStatusCode` is just a component, it can be used with `ErrorBoundary`, `Show`, `Switch` or any of the other JSX control-flow components. This means the same logic used when deciding what to render can inform what status code you are setting, allowing that logic to sit together. Status codes are important tools for things like caching and SEO, so it is a good practice to send meaningful status codes. For example, for a `NotFound` page, you should send a `404` status code. import { HttpStatusCode } from "@solidjs/start";export default function NotFound() { return ( <div> <HttpStatusCode code={404} /> <h1>Page not found</h1> </div> );} * * * ## Setting a 404 status code for missing pages for dynamic routes When using dynamic params in routes, setting a 404 status code if the given parameter for a segment points to a missing resource is important. Usually, the param is discovered to be missing when doing an async request with that parameter. Errors can be thrown from inside these fetchers and caught by the nearest `<ErrorBoundary>` component from where the data is accessed. `<HttpStatusCode>` pairs very well with error boundaries because you can inspect the error in the ErrorBoundary's fallback. If the fetcher throws an error indicating the data was not found, you can render `<HttpStatusCode code={404} />`. Note that when streaming responses `renderStream`, the HTTP Status can only be included if added _before_ the stream first flushed. It is important to add `deferStream` to any resources calls that need to be loaded before responding. import { Show, ErrorBoundary } from "solid-js";import { query, createAsync } from "@solidjs/router";import { HttpStatusCode } from "@solidjs/start";const getHouse = query(async (house: string) => { if (house != "gryffindor") { throw new Error("House not found"); } return house;}, "house");export default function House(props: { name: string }) { const house = createAsync(() => getHouse(props.name), { deferStream: true }); return ( <ErrorBoundary fallback={(e) => ( <Show when={e.message === "House not found"}> <HttpStatusCode code={404} /> </Show> )} > <div>{house()}</div> </ErrorBoundary> );} * * * | Property | Type | Description | | --- | --- | --- | | code | number | The HTTP status code | --- ## Page: https://docs.solidjs.com/solid-start/reference/server/start-server `StartServer` takes a function returning a document component and converts it to a static document which can be used in `createHandler` to bootstrap the server. import { StartServer } from "@solidjs/start/server"; * * * ## Parameters | Property | Type | Description | | --- | --- | --- | | document | Function | A function that returns the static document for your application. |