Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ jobs:
run: |
npm i
npm run build
npm run build:example:ssr
- name: Publish package for testing branch
run:
npx pkg-pr-new publish || echo "Have you set up pkg-pr-new for this
Expand Down
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,4 @@ node_modules
next-example/
dist/
example/dist/

.tanstack/
18 changes: 18 additions & 0 deletions INTEGRATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,7 @@ npx @convex-dev/static-hosting upload [options]
-d, --dist <path> Path to dist directory (default: ./dist)
-c, --component <name> Component instance name (default: staticHosting)
--prod Deploy to production deployment
--preview-name <name> Upload to the named preview deployment
-b, --build Run 'npm run build' with VITE_CONVEX_URL set
--build-command <cmd> Override the build command; implies --build
--no-spa Disable SPA fallback (404 instead of /index.html)
Expand Down Expand Up @@ -398,6 +399,23 @@ app routes must remain at the same root. `pathPrefix`, `spaFallback`, and
`cdnBaseUrl` are supported. The component must be installed without an
`httpPrefix` so only the app owns that URL space.

### `serveStaticAsset(ctx, component, request, options?)`

Serves an uploaded file from an app-owned HTTP action, or returns `null` when no
file matches so the action can continue with its own routing (server rendering,
prerendered pages, redirects). Responses match `registerStaticRoutes`. The
lookup is exact: `/` is not mapped to `/index.html`, and `spaFallback` defaults
to `false`. `path` (the decoded file path, defaulting to the decoded request
path, starting with `/` and without your route's prefix), `spaFallback`, and
`cdnBaseUrl` are supported. A request path with malformed percent-encoding
returns `null`. A found file whose storage can't be read gets a 500 response.
The component must be installed without an `httpPrefix`.

### `decodeRequestPath(pathname)`

Decodes a URL pathname the way the static handlers do. Returns `null` for
malformed percent-encoding.

### `exposeDeploymentQuery(component)`

Returns `{ getCurrentDeployment }`: a public query that wraps the component's
Expand Down
81 changes: 80 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,7 @@ npx @convex-dev/static-hosting upload [options]
-d, --dist <path> Path to dist directory (default: ./dist)
-c, --component <name> Component instance name (default: staticHosting)
--prod Deploy to production deployment
--preview-name <name> Upload to the named preview deployment
-b, --build Run 'npm run build' with VITE_CONVEX_URL set
--build-command <cmd> Override the build command; implies --build
--no-spa Disable SPA fallback (404 instead of /index.html)
Expand All @@ -240,6 +241,10 @@ npx @convex-dev/static-hosting upload [options]
-j, --concurrency <n> Parallel upload workers (default: 5)
```

`--preview-name` selects the deployment the same way as
`npx convex run --preview-name`, so a dev or production `CONVEX_DEPLOY_KEY`
takes precedence over it.

Each upload is published atomically, so visitors never see a page that refers to
assets that are not available yet. Failed uploads leave the previous deployment
live, and old files are cleaned up safely. See [INTEGRATION.md](./INTEGRATION.md)
Expand Down Expand Up @@ -355,6 +360,79 @@ The setting is stored with the deployment, so it travels with the code you ship
rather than living in a separate env var. Requests for paths with an extension
(e.g. `/missing.js`) always 404 when not found, regardless of this setting.

## Custom routing (SSR, prerendered pages)

`registerStaticRoutes` decides what every unmatched path returns. When your app
needs to decide instead, for example to server-render pages, serve prerendered
pages next to an SPA shell, or redirect to canonical URLs, write the catch-all
route yourself and call `serveStaticAsset` for uploaded files. Install the
component without `httpPrefix`, as in
[Keep existing HTTP routes at the root](#keep-existing-http-routes-at-the-root).

```ts
import { httpRouter } from "convex/server";
import {
decodeRequestPath,
serveStaticAsset,
} from "@convex-dev/static-hosting";
import { components } from "./_generated/api";
import { httpAction } from "./_generated/server";

const http = httpRouter();

http.route({
pathPrefix: "/",
method: "GET",
handler: httpAction(async (ctx, request) => {
const file = await serveStaticAsset(ctx, components.staticHosting, request);
if (file) return file;

// A missing bundle file is a 404, not a page.
const path = decodeRequestPath(new URL(request.url).pathname);
if (path === null || path.startsWith("/assets/")) {
return new Response("Not Found", {
status: 404,
headers: { "Cache-Control": "no-store" },
});
}
return await renderPage(request);
}),
});

export default http;
```

`serveStaticAsset` returns the file with the same headers as
`registerStaticRoutes`, or `null` when no file matches, including a request path
with malformed percent-encoding. It never returns the setup page or a 404, so
your code decides what happens next. Only a found file whose storage can't be
read gets an error response (500). The lookup is exact: `/` is not mapped to
`/index.html`, and SPA fallback is off unless you pass `spaFallback: true`.

Pass `path` to serve a different file, such as a prerendered page or the SPA
shell. It is the decoded path of the uploaded file, starting with `/`. If your
route has a prefix, remove it from `path`:

```ts
const page = await serveStaticAsset(ctx, components.staticHosting, request, {
path: "/about/index.html",
});
const shell = await serveStaticAsset(ctx, components.staticHosting, request, {
path: "/index.html",
});
```

When the backend renders your pages, pushing the backend and uploading files are
separate steps, so right after a deploy a page can briefly refer to scripts that
are not uploaded yet. That is why the missing-asset response above uses
`Cache-Control: no-store`: a CDN would otherwise keep serving the 404.

Use `decodeRequestPath` for your own path checks, so an encoded request such as
`/%61ssets/app.js` still matches `/assets/`.

See [`example-ssr/`](./example-ssr) for TanStack Start pages rendered in a
Convex HTTP action this way.

## Upgrading from 0.1.x

0.2.0 moves uploads and file storage into the component. You must remove the
Expand Down Expand Up @@ -386,7 +464,8 @@ steps, verification, rollback, and the optional staged cutover.

## Example

See [`example/`](./example) for a complete Vite + React app.
See [`example/`](./example) for a complete Vite + React app, and
[`example-ssr/`](./example-ssr) for server rendering with TanStack Start.

```bash
npm install
Expand Down
23 changes: 20 additions & 3 deletions eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ export default [
".context/**",
"dist/**",
"example/dist/**",
"example-ssr/dist/**",
"example-ssr/src/routeTree.gen.ts",
"next-example/**",
"*.config.{js,mjs,cjs,ts,tsx}",
"example/**/*.config.{js,mjs,cjs,ts,tsx}",
Expand All @@ -19,14 +21,20 @@ export default [
],
},
{
files: ["src/**/*.{js,mjs,cjs,ts,tsx}", "example/**/*.{js,mjs,cjs,ts,tsx}"],
files: [
"src/**/*.{js,mjs,cjs,ts,tsx}",
"example/**/*.{js,mjs,cjs,ts,tsx}",
"example-ssr/**/*.{js,mjs,cjs,ts,tsx}",
],
languageOptions: {
parser: tseslint.parser,
parserOptions: {
project: [
"./tsconfig.json",
"./example/tsconfig.json",
"./example/convex/tsconfig.json",
"./example-ssr/tsconfig.json",
"./example-ssr/convex/tsconfig.json",
],
tsconfigRootDir: import.meta.dirname,
},
Expand All @@ -36,7 +44,12 @@ export default [
...tseslint.configs.recommended,
// Convex code - Worker environment
{
files: ["src/**/*.{ts,tsx}", "example/convex/**/*.{ts,tsx}"],
files: [
"src/**/*.{ts,tsx}",
"example/convex/**/*.{ts,tsx}",
"example-ssr/convex/**/*.{ts,tsx}",
"example-ssr/adapter/server.ts",
],
ignores: ["src/react/**"],
languageOptions: {
globals: globals.worker,
Expand Down Expand Up @@ -68,7 +81,11 @@ export default [
},
// React app code - Browser environment
{
files: ["src/react/**/*.{ts,tsx}", "example/src/**/*.{ts,tsx}"],
files: [
"src/react/**/*.{ts,tsx}",
"example/src/**/*.{ts,tsx}",
"example-ssr/src/**/*.{ts,tsx}",
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
Expand Down
2 changes: 2 additions & 0 deletions example-ssr/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@

.env.local
38 changes: 38 additions & 0 deletions example-ssr/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# TanStack Start SSR example

Renders TanStack Start pages inside a Convex HTTP action. The first HTML
response already contains a count from a Convex query, and after React hydrates,
the count stays live.

## How it works

- `convex/http.ts` has one catch-all route. It serves uploaded files with
`serveStaticAsset`, returns 404 for missing `/assets/` files, and renders
every other path with the TanStack Start server bundle.
- `src/router.tsx` sets up Convex's TanStack Query integration, so data from
`useSuspenseQuery(convexQuery(...))` is in the first HTML and stays live.
- `adapter/` makes TanStack Start run in the Convex runtime. The comments in
`server.ts` and `vite.ts` explain each setting. It doesn't depend on the
example, so it could become its own package.
- `public/index.html` exists only because the uploader requires an `index.html`.

## Run

This example has its own schema, so use a separate Convex project. From the
repository root:

```bash
npm install
cd example-ssr
npm run dev
```

The first run asks you to choose a Convex project. `npm run dev` then keeps the
dev deployment in sync: each change rebuilds the page bundles, pushes the
backend, and uploads the browser files. Open the `.convex.site` URL it prints.
The page source contains the count and the render time. Open the page in two
tabs: a click in one updates both.

Backend pushes and file uploads are separate steps, so right after a change a
page can briefly refer to scripts that are not uploaded yet. Both bundles
contain the deployment URL, so rebuild before pushing to another deployment.
46 changes: 46 additions & 0 deletions example-ssr/adapter/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// TanStack Start server entry for Convex HTTP actions. Nothing here is
// specific to this example, so it could become its own package. Keep it
// self-contained: import only TanStack and React, never app code.
// `src/server.ts` re-exports it as the entry Vite builds.

import { createStartHandler, StartServer } from "@tanstack/react-start/server";
import { renderSsrHtmlResponse } from "@tanstack/react-router/ssr/server";
import { createElement } from "react";
import { renderToReadableStream } from "react-dom/server";

// Convex omits size, which TanStack uses when normalizing query-string URLs.
if (new URLSearchParams().size === undefined) {
Object.defineProperty(URLSearchParams.prototype, "size", {
configurable: true,
get(this: URLSearchParams) {
return Array.from(this).length;
},
});
}

export default {
fetch: createStartHandler((context) => {
const { router, responseHeaders, request } = context;
return renderSsrHtmlResponse({
router,
responseHeaders,
render: async () => {
// Await Suspense with React's Web Stream renderer. TanStack's stream
// handler also imports node:stream, which Convex cannot bundle.
const stream = await renderToReadableStream(
createElement(StartServer, { router }),
{
signal: request.signal,
...(router.options.ssr?.nonce === undefined
? {}
: { nonce: router.options.ssr.nonce }),
},
);
await stream.allReady;
const html = await new Response(stream).text();
// React emits a doctype; TanStack's HTML helper adds its own.
return html.replace(/^<!DOCTYPE html>/i, "");
},
});
}),
};
23 changes: 23 additions & 0 deletions example-ssr/adapter/vite.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Vite settings that let TanStack Start's server build run in Convex HTTP
// actions. Like `server.ts`, this is not specific to the example and could
// move to its own package together with it.

import type { Plugin } from "vite";

export function convexSsr(): Plugin {
return {
name: "convex-tanstack-start",
apply: "build",
config: () => ({
ssr: {
noExternal: true,
resolve: { conditions: ["worker", "browser", "module", "import"] },
},
resolve: {
alias: [
{ find: /^react-dom\/server$/, replacement: "react-dom/server.edge" },
],
},
}),
};
}
4 changes: 4 additions & 0 deletions example-ssr/convex.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"functions": "convex",
"codegen": { "legacyComponentApi": false }
}
53 changes: 53 additions & 0 deletions example-ssr/convex/_generated/api.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/* eslint-disable */
/**
* Generated `api` utility.
*
* THIS CODE IS AUTOMATICALLY GENERATED.
*
* To regenerate, run `npx convex dev`.
* @module
*/

import type * as counter from "../counter.js";
import type * as http from "../http.js";

import type {
ApiFromModules,
FilterApi,
FunctionReference,
} from "convex/server";

declare const fullApi: ApiFromModules<{
counter: typeof counter;
http: typeof http;
}>;

/**
* A utility for referencing Convex functions in your app's public API.
*
* Usage:
* ```js
* const myFunctionReference = api.myModule.myFunction;
* ```
*/
export declare const api: FilterApi<
typeof fullApi,
FunctionReference<any, "public">
>;

/**
* A utility for referencing Convex functions in your app's internal API.
*
* Usage:
* ```js
* const myFunctionReference = internal.myModule.myFunction;
* ```
*/
export declare const internal: FilterApi<
typeof fullApi,
FunctionReference<any, "internal">
>;

export declare const components: {
staticHosting: import("@convex-dev/static-hosting/_generated/component.js").ComponentApi<"staticHosting">;
};
Loading
Loading