diff --git a/docs/start/config.json b/docs/start/config.json index 8fa644fc1c..4c7b90db47 100644 --- a/docs/start/config.json +++ b/docs/start/config.json @@ -515,6 +515,53 @@ } ] }, + { + "label": "Learn Start", + "children": [], + "frameworks": [ + { + "label": "react", + "children": [ + { + "label": "Course overview", + "to": "framework/react/tutorial/learn-start" + }, + { + "label": "1. Setup", + "to": "framework/react/tutorial/learn-start/setup" + }, + { + "label": "2. Routes", + "to": "framework/react/tutorial/learn-start/routes" + }, + { + "label": "3. Data", + "to": "framework/react/tutorial/learn-start/data" + }, + { + "label": "4. Forms", + "to": "framework/react/tutorial/learn-start/forms" + }, + { + "label": "5. Authentication", + "to": "framework/react/tutorial/learn-start/authentication" + }, + { + "label": "6. SEO", + "to": "framework/react/tutorial/learn-start/seo" + }, + { + "label": "7. Deployment", + "to": "framework/react/tutorial/learn-start/deployment" + }, + { + "label": "8. Tests", + "to": "framework/react/tutorial/learn-start/tests" + } + ] + } + ] + }, { "label": "Tutorials", "children": [], diff --git a/docs/start/framework/react/tutorial/fetching-external-api.md b/docs/start/framework/react/tutorial/fetching-external-api.md index 8bdb048c88..8d6af3edce 100644 --- a/docs/start/framework/react/tutorial/fetching-external-api.md +++ b/docs/start/framework/react/tutorial/fetching-external-api.md @@ -3,6 +3,8 @@ id: fetching-external-api title: Calling an external API using TanStack Start --- +For a course that adds routing, a database, accounts, SEO, deployment, and tests to one app, see [Learn Start](./learn-start). + This guide demonstrates how to integrate external API calls into your TanStack Start application using route loaders. We will use TMDB API to fetch popular movies using TanStack Start and understand how to fetch data in a TanStack Start app. The complete code for this tutorial is available on [GitHub](https://github.com/shrutikapoor08/tanstack-start-movies). diff --git a/docs/start/framework/react/tutorial/learn-start.md b/docs/start/framework/react/tutorial/learn-start.md new file mode 100644 index 0000000000..ceb9be6f91 --- /dev/null +++ b/docs/start/framework/react/tutorial/learn-start.md @@ -0,0 +1,24 @@ +--- +id: learn-start +title: Learn TanStack Start by Building a Full Stack App +description: Build one TanStack Start app through eight working checkpoints, from routing and PostgreSQL to forms, accounts, SEO, deployment, and tests. +--- + +Build **Field notes**, a notebook with private drafts and published pages. Each chapter adds to the same app and has a runnable checkpoint, so you can inspect working code when you get stuck. + +The course uses React, TanStack Start, PostgreSQL, Prisma, and Better Auth. You should be comfortable with React components, TypeScript, and a terminal. The first two chapters need no database or hosted account. + +| Chapter | What you build | +| ------------------------------------------------- | --------------------------------------------------------------------- | +| [1. Setup](./learn-start/setup) | A server-rendered page, root document, and router. | +| [2. Routes](./learn-start/routes) | Typed links, search parameters, note URLs, and 404s. | +| [3. Data](./learn-start/data) | PostgreSQL reads through server functions and route loaders. | +| [4. Forms](./learn-start/forms) | Validated writes, transaction rollback, and refreshed data. | +| [5. Authentication](./learn-start/authentication) | Accounts, private drafts, ownership checks, and explicit publication. | +| [6. SEO](./learn-start/seo) | Server-rendered metadata, canonical URLs, and a public sitemap. | +| [7. Deployment](./learn-start/deployment) | A standalone Node build, runtime configuration, and readiness checks. | +| [8. Tests](./learn-start/tests) | Browser and production checks against the complete app. | + +Open the [complete example and checkpoints](https://github.com/TanStack/router/tree/main/examples/react/start-learn). + +Each checkpoint has its own source directory within one pnpm package. The anonymous database chapters and the account chapters use separate databases. The deployment chapter explains the remaining hosting and account-service configuration; local production tests do not verify a hosted release. diff --git a/docs/start/framework/react/tutorial/learn-start/authentication.md b/docs/start/framework/react/tutorial/learn-start/authentication.md new file mode 100644 index 0000000000..28eedbf1f2 --- /dev/null +++ b/docs/start/framework/react/tutorial/learn-start/authentication.md @@ -0,0 +1,81 @@ +--- +id: learn-start-authentication +title: Learn Start, Accounts and Private Notes +description: Add Better Auth accounts to TanStack Start, authorize database reads and writes, keep drafts private, and test session renewal and expiry. +--- + +Give each account its own drafts and let the owner choose which notes to publish. The [working checkpoint](https://github.com/TanStack/router/tree/main/examples/react/start-learn/checkpoints/05-authentication) is `checkpoints/05-authentication`. + +## Prepare a separate database + +The earlier checkpoints allow anonymous writes. Do not point them at a database containing private notes. Create a second PostgreSQL database, `learn_start_auth`, and add its connection string to the example's `.env`: + +```dotenv +AUTH_DATABASE_URL="postgresql://start_demo:start_demo@localhost:5433/learn_start_auth" +BETTER_AUTH_SECRET="" +APP_ORIGIN="http://localhost:3144" +``` + +Use your actual database credentials and port. Keep `DATABASE_URL` pointing at the earlier `learn_start` database. Generate a secret with `openssl rand -base64 48` and paste it into `BETTER_AUTH_SECRET`. Keep `.env` out of Git. + +From `examples/react/start-learn`, run: + +```sh +pnpm db:generate:05 +pnpm db:migrate:05 +pnpm db:seed:05 +pnpm exec vite checkpoints/05-authentication --port 3144 +``` + +Open http://localhost:3144 and choose **My notes**. Create an account with a password of at least 12 characters. This checkpoint starts with two public sample notes; it does not transfer notes from the anonymous database. + +## Let the auth library own credentials + +`src/server/auth.server.ts` configures Better Auth with its Prisma adapter and email/password sign-in. The migration adds its user, account, session, and verification tables. `src/routes/api/auth/$.ts` forwards GET and POST requests to the library's handler. + +The login component uses Better Auth's browser client. It does not hash passwords, create session tokens, or store credentials itself. The `tanstackStartCookies()` plugin is last in the server configuration so cookies set during server-side session reads reach the browser, including renewed session cookies. + +The server requires an explicit `APP_ORIGIN` and a secret of at least 32 characters. Changing the port means updating the origin too. Later, use the deployment's HTTPS origin and a secret stored in the host's secret manager. + +## Authorize every data operation + +`currentUser()` reads the incoming session and returns only the user's ID, name, and email. It sets `Cache-Control: private, no-store`; session tokens stay on the server. `requireUser()` rejects unauthenticated requests with HTTP 401. + +The dashboard's `beforeLoad` redirects visitors to `/login`, but that redirect is only a navigation convenience. Each protected server function calls `requireUser()` independently: + +- Creating a note takes its owner ID from the session, never from submitted form data. +- Listing drafts filters by that owner ID. +- Reading a draft filters by both slug and owner ID. +- Publishing or unpublishing updates only a row matching both slug and owner ID. No matching row produces HTTP 404. + +A second signed-in user cannot bypass these checks by copying the first user's request. The public list and detail functions read only rows where `isPublished` is true. New notes default to private. + +## Keep publication explicit + +Create a note from **My notes**. Its body is visible at its private draft URL, but `/notes/your-slug` returns 404 to an anonymous visitor. Choose **Publish**, then open that public URL in another browser session. Choose **Unpublish** and it returns 404 again. + +Private pages use `noindex` and `private, no-store`. Neither directive replaces authorization. The database query is what prevents another account from reading the draft. + +The private dashboard and draft loaders use `staleReloadMode: 'blocking'`. This prevents a previously visited private page from rendering cached data while a different account's request is checked. HTTP cache headers do not clear Router's in-memory loader data. Sign-in and sign-out invalidate the router so these loaders request the current account's data. + +Create, publish, unpublish, and sign-out controls share pending state. This prevents overlapping actions while the route data refreshes. Sign-out clears the session through the auth client, invalidates route data, and returns to the login page. + +## Keep origin checks and account checks separate + +The checkpoint's Start middleware rejects cross-site server-function requests. Better Auth handles its own auth endpoints and origin checks. An authenticated cross-site request still needs to fail: being signed in does not prove that the user intended a write. + +Conversely, an allowed same-origin request still needs an authenticated owner. A CSRF check cannot decide which note an account may edit. + +## Verify two accounts and expired sessions + +Stop the development server and run: + +```sh +COURSE_CHECKPOINT=05-authentication pnpm test:e2e +``` + +The test creates two temporary accounts and checks private reads, public publication, unpublication, another owner's rejected write, authenticated cross-site rejection, and rejected requests after sign-out. It also moves a session near expiry to check cookie renewal, then expires a session to check the login redirect. Test accounts and their notes are removed afterward. + +This course uses local email/password accounts. Email verification, password recovery, mail delivery, and a deployment-wide rate-limit store are not configured here. Configure and test the account lifecycle your public service needs before opening registration to real users. + +Next: [Make published notes discoverable](./seo). diff --git a/docs/start/framework/react/tutorial/learn-start/data.md b/docs/start/framework/react/tutorial/learn-start/data.md new file mode 100644 index 0000000000..7d0d7e3675 --- /dev/null +++ b/docs/start/framework/react/tutorial/learn-start/data.md @@ -0,0 +1,81 @@ +--- +id: learn-start-data +title: Learn Start, Read Notes from PostgreSQL +description: Move the Field notes app from static data to PostgreSQL with Prisma migrations, server-only queries, loader dependencies, and repeatable checks. +--- + +Keep the URLs from the routing chapter and move the data into PostgreSQL. The [working checkpoint](https://github.com/TanStack/router/tree/main/examples/react/start-learn/checkpoints/03-data) is `checkpoints/03-data`. + +## Prepare a dedicated database + +Install PostgreSQL and make its `initdb`, `pg_ctl`, and `createdb` commands available. From `examples/react/start-learn`, create a local development cluster and database: + +```sh +cp .env.example .env +printf '%s\n' 'start_demo' > .postgres-password +initdb -D .postgres -U start_demo --auth-local=trust --auth-host=scram-sha-256 --pwfile=.postgres-password +pg_ctl -D .postgres -l .postgres/server.log -o '-p 5433 -h 127.0.0.1' start +PGPASSWORD=start_demo createdb -h 127.0.0.1 -p 5433 -U start_demo learn_start +``` + +Run initialization once for a new cluster, not every time you open the project. The database listens on localhost:5433. If that port is occupied, choose another port and update `.env` too. If you already run PostgreSQL, create a separate `learn_start` database there and set its connection URL instead. + +These are local demo credentials. `.env`, `.postgres`, and the password file are ignored by Git. Stop this cluster with `pg_ctl -D .postgres stop` when you finish, and restart it with the same `pg_ctl ... start` command. Do not use a production database for course exercises. + +## Apply the schema and sample data + +```sh +pnpm db:generate:03 +pnpm db:migrate:03 +pnpm db:seed:03 +``` + +Generation produces this checkpoint's Prisma client. Migration applies the committed SQL. The seed inserts the two notes from the previous chapter and their category; rerunning it leaves existing records alone. + +Inspect `prisma/schema.prisma` in the checkpoint. `Note` has a unique `slug`, a `title`, a `body`, and a relation to `Category`. The relation keeps category references valid at the database boundary. The next chapter uses it to demonstrate transaction rollback. + +The Prisma configuration loads `DATABASE_URL` from the course environment and points to this checkpoint's schema and migrations. Keep schema changes and migration SQL together. Generating the client updates TypeScript code; it does not apply changes to the database. + +## Make the database module server-only + +`src/server/db.server.ts` imports the server-only marker and creates a Prisma client with the PostgreSQL adapter. It fails clearly if `DATABASE_URL` is missing. The pool is shared by requests within that module instance, while query results are returned per request. + +Import that module only from server implementations. The browser needs the selected note fields, not a database client or connection URL. The complete configuration follows the [PostgreSQL recipe](../../guide/databases). + +## Call server functions from loaders + +A route loader can run during browser navigation, so it must not connect to PostgreSQL directly. `listNotes` and `getNote` are server functions in `src/server/notes.ts`. They validate input and select only the fields the page uses. + +The index route now makes its dependency on search explicit: + +```tsx +validateSearch: z.object({ q: z.string().max(200).catch('') }), +loaderDeps: ({ search }) => ({ q: search.q }), +loader: ({ deps }) => listNotes({ data: deps }), +``` + +Import `z` from `zod` and `listNotes` from `../server/notes`. The component reads `Route.useLoaderData()` instead of filtering a module-level array. PostgreSQL filters titles case-insensitively. An invalid search value falls back to the empty filter. + +The detail loader awaits `getNote({ data: params.slug })`. If no note exists, it throws `notFound()` just as the static version did. The page component still reads the loader result, so the database change does not require a new component data-fetching pattern. + +Both routes use `Cache-Control: no-store` in this checkpoint. `src/start.ts` enables Start's CSRF middleware for requests to server functions. These protections do not authenticate a user; this chapter only reads public sample content. + +## Verify the data path + +```sh +pnpm exec vite checkpoints/03-data --port 3142 +``` + +Open http://localhost:3142 and follow a note link. Reload the detail page. You should see the same content that the earlier chapter served from a file. + +Stop the development server, then run: + +```sh +COURSE_CHECKPOINT=03-data pnpm test:e2e +``` + +The test writes a uniquely named record directly to the dedicated database, checks that its title appears in raw server HTML, opens its detail page, reloads it, and checks an unknown note's 404 response. It deletes only its own test records. That distinguishes a working database loader from an app that still displays its old static array. + +If the database is unavailable, the checkpoint displays a generic recovery page. Inspect the server terminal for connection details. Do not display credentials or raw database errors to a reader. + +Next: [Create notes with a validated form](./forms). diff --git a/docs/start/framework/react/tutorial/learn-start/deployment.md b/docs/start/framework/react/tutorial/learn-start/deployment.md new file mode 100644 index 0000000000..b48d7e6585 --- /dev/null +++ b/docs/start/framework/react/tutorial/learn-start/deployment.md @@ -0,0 +1,85 @@ +--- +id: learn-start-deployment +title: Learn Start, Build and Deploy the Node Server +description: Build a standalone TanStack Start Node server, apply database migrations, configure runtime secrets, and verify readiness and server-rendered pages. +--- + +Build the same notebook as a Node server. The [working checkpoint](https://github.com/TanStack/router/tree/main/examples/react/start-learn/checkpoints/07-deployment) is `checkpoints/07-deployment`. It adds an explicit Node output preset and a database readiness endpoint. + +## Build and run locally + +Keep the account database and secret from the previous chapter. From `examples/react/start-learn`, run: + +```sh +pnpm db:generate:07 +pnpm db:migrate:07 +pnpm build:07 +APP_ORIGIN=http://localhost:3146 PORT=3146 node --env-file=.env checkpoints/07-deployment/.output/server/index.mjs +``` + +If the account database is empty, run `pnpm db:seed:07` before starting. The build runs Vite and TypeScript. The explicit environment variables above override the values in `.env`, while `--env-file` supplies the database connection and auth secret for this local run. + +Open http://localhost:3146 and sign in. Create a note, publish it, and open its public URL in another browser session. Restart the process and verify the note remains. PostgreSQL owns persistence; the build directory does not. + +`/healthz` returns `200 ok` only after a PostgreSQL query succeeds. A failed query returns `503 unavailable` without database details. Use it as a readiness check. A database outage should remove an instance from traffic, not cause an endless process-restart loop. + +## Deploy the complete output directory + +The checkpoint selects Nitro's Node server preset. Its output is `checkpoints/07-deployment/.output`, including the server and public assets. Copy that whole directory to a Node host, then start it with: + +```sh +node .output/server/index.mjs +``` + +If the host runs from the source checkout instead, `pnpm start:07` starts the same entry point. It expects runtime environment variables to already be set. Do not copy your local `.env` into a public directory or bake credentials into the artifact. + +Nitro supports a standalone Node output and uses `PORT` for the listening port. Terminate HTTPS at the host's reverse proxy. See [Nitro's Node deployment reference](https://nitro.build/deploy/runtimes/node). + +Use a Node version supported by the repository's current toolchain and pin it in the host configuration. Match the version used for your build and tests. The repository is a pnpm workspace, so use the installation and package-build steps from the [setup chapter](./setup) before running this checkpoint's build command in a fresh checkout. + +## Configure the runtime and release job + +| Setting | Value | +| -------------------- | --------------------------------------------------------------------------------------- | +| `AUTH_DATABASE_URL` | The production PostgreSQL connection string, with the provider's required TLS settings. | +| `BETTER_AUTH_SECRET` | A stable, random secret of at least 32 characters, stored in the host's secret manager. | +| `APP_ORIGIN` | The public HTTPS origin, without a trailing slash. | +| `PORT` | The port assigned by the Node host. | +| `NODE_ENV` | `production`. | + +Keep the database in a reachable region and size its connection capacity for all instances. Each instance's pool allows up to five connections. Multiple replicas multiply that limit. + +Run `pnpm db:migrate:07` once in the release job, using the source checkout, Prisma configuration, migration files, and production database credentials. The standalone output is the runtime artifact, not a migration runner. Apply migrations before routing traffic to code that needs them. Do not use the sample seed as a production release step. + +Keep the previous artifact available for rollback. Roll back application code only when it remains compatible with the current database schema. Database migrations require their own recovery plan and tested backups. + +## Verify the hosted application + +After deploying, check the actual HTTPS origin: + +1. `/healthz` returns 200, and a public note loads directly with its body and metadata in the HTML. +2. Its canonical URL and `/sitemap.txt` use the production origin, not localhost or a preview hostname. +3. Sign-in survives reload; creating, publishing, and unpublishing a note works. +4. Another account cannot read a draft or change its publication state, and signed-out writes fail. +5. Sign-out returns to the login page, and an unknown public note returns 404. + +These hosted checks are separate from a local production build. The included tests do not provision hosting, configure DNS or TLS, or verify a remote deployment. + +## Finish account operations before public registration + +This checkpoint retains the course's email/password configuration. Email verification and password recovery are not wired to a mail service. Configure and test the flows your service requires before opening registration to real users, or keep the deployed course behind your host's access controls. + +Review rate-limit storage and trusted client-IP handling for your host. Better Auth's default in-memory limits are per process; multiple instances need suitable shared storage and proxy configuration. See [Better Auth's rate-limit documentation](https://better-auth.com/docs/concepts/rate-limit). Check the APIs against the version installed in this example before changing its configuration. + +## Run the deployment checks + +Stop the local server, then run: + +```sh +COURSE_CHECKPOINT=07-deployment pnpm test:e2e +COURSE_PRODUCTION=1 COURSE_CHECKPOINT=07-deployment pnpm test:e2e +``` + +The production run checks readiness and direct server HTML, scans public assets for the configured secrets, and runs a copied artifact outside the repository against an unavailable database. It expects a generic 503 response. Run `pnpm build:07` again after source changes before repeating production tests. + +Next: [Test the complete application](./tests). diff --git a/docs/start/framework/react/tutorial/learn-start/forms.md b/docs/start/framework/react/tutorial/learn-start/forms.md new file mode 100644 index 0000000000..d1df194785 --- /dev/null +++ b/docs/start/framework/react/tutorial/learn-start/forms.md @@ -0,0 +1,62 @@ +--- +id: learn-start-forms +title: Learn Start, Create Notes with a Validated Form +description: Add a TanStack Start form with server validation, pending and error feedback, transaction rollback, CSRF protection, and refreshed loader data. +--- + +Add writes to the same notes database. The [working checkpoint](https://github.com/TanStack/router/tree/main/examples/react/start-learn/checkpoints/04-forms) is `checkpoints/04-forms`. This checkpoint is still a shared local notebook with no accounts. Keep it local until the authentication chapter adds endpoint authorization. + +## Prepare this checkpoint + +Keep the database and `.env` from the previous chapter. Generate the client for the new source directory and apply the same migration history: + +```sh +pnpm db:generate:04 +pnpm db:migrate:04 +pnpm exec vite checkpoints/04-forms --port 3143 +``` + +Open http://localhost:3143. The two seeded notes remain, and the list now has a **Create a note** form. If you started here with a new database, run `pnpm db:seed:04` too. + +## Validate at the endpoint + +The new `createNote` server function uses POST and a Zod validator. It accepts four fields: + +- `slug`: lowercase letters and digits separated by hyphens, at most 80 characters. +- `title`: 1 to 120 characters after trimming. +- `body`: 1 to 5,000 characters after trimming. +- `category`: 1 to 40 characters after trimming. + +The form mirrors these limits where HTML can express them. The server validator remains necessary because callers can bypass the form. A title containing only spaces passes HTML's `required` check but must fail the server validator. + +The checkpoint's `src/start.ts` keeps CSRF middleware enabled for server-function requests. Same-origin form calls work; a replay marked as cross-site receives HTTP 403. Authentication in the next chapter will add a separate check for who may write. + +## Keep related writes in one transaction + +A note needs a category. The handler uses a Prisma transaction to upsert the category and then insert the note. If the note's slug already exists, the database rejects the second write and rolls back the first. + +Try creating a note with an existing slug and a new category name. The UI should say **That slug is already used. Choose another one.** The unused category should not remain in the database. This is why catching the error around two unrelated writes would be insufficient. + +Only the known unique-constraint error becomes that specific response. An unexpected database failure gets generic UI feedback, while the server can retain diagnostic information. Avoid returning raw exception objects to the browser. + +## Keep the form pending through the refresh + +The component calls `createNote` through `useServerFn`. On success it awaits `router.invalidate()` so the route's database loader refreshes before the form becomes available again. A successful request alone does not update Router-owned loader data. + +The handler captures `event.currentTarget` before awaiting anything, reads its `FormData`, and resets the form only after a successful write and refresh. Validation or duplicate-slug errors leave the entered values available for correction. + +The fieldset is disabled until hydration and while the mutation is pending. The form uses `method="post"` so native submission cannot put its values into the URL. This implementation requires JavaScript; a progressively enhanced form needs an explicit native POST response path. + +## Check success and failure + +Create a note, then reload the page and open its detail link. The new body should come from PostgreSQL. Try the same slug again with a different category, and then try a title made of spaces. + +Stop the development server and run: + +```sh +COURSE_CHECKPOINT=04-forms pnpm test:e2e +``` + +The tests check persisted server HTML, reloads, duplicate-slug rollback, server-side whitespace validation, and cross-site rejection. They also check that the HTML does not contain the configured database URL or password. Build-time client asset inspection remains part of the deployment checks. + +Next: [Add accounts and protect writes](./authentication). diff --git a/docs/start/framework/react/tutorial/learn-start/routes.md b/docs/start/framework/react/tutorial/learn-start/routes.md new file mode 100644 index 0000000000..f226509802 --- /dev/null +++ b/docs/start/framework/react/tutorial/learn-start/routes.md @@ -0,0 +1,86 @@ +--- +id: learn-start-routes +title: Learn Start, Give Notes Their Own URLs +description: Add typed note links, route parameters, validated search values, and a real not-found response to the Field notes app. +--- + +This chapter turns the single page into a searchable list and a detail page. Use the [working checkpoint](https://github.com/TanStack/router/tree/main/examples/react/start-learn/checkpoints/02-routes) in `checkpoints/02-routes` as the reference. It still uses static data so you can check routing before introducing database failures. + +From `examples/react/start-learn`, start this checkpoint: + +```sh +pnpm exec vite checkpoints/02-routes --port 3141 +``` + +## Add the note data + +Create `src/notes.ts` with two entries. Each has a stable `slug`, a `title`, and a `body`. The checkpoint uses `first-route` and `server-html` as its slugs. The next chapter will move reads behind a server function; for now this file is safe to include in browser code because every field is public sample content. + +## Match a route parameter + +Add `src/routes/notes.$slug.tsx`. The `$slug` segment matches the part of the URL after `/notes/`. Its loader selects the matching note: + +```tsx +export const Route = createFileRoute('/notes/$slug')({ + loader: ({ params }) => { + const note = notes.find((item) => item.slug === params.slug) + if (!note) { + throw notFound() + } + return note + }, + component: Note, +}) +``` + +Import `createFileRoute` and `notFound` from `@tanstack/react-router` and `notes` from `../notes`. The component reads its result with `Route.useLoaderData()` and renders the note's title and body. The complete route is in the checkpoint. + +Using `notFound()` means `/notes/does-not-exist` returns a missing-resource response. Do not return an ordinary successful page whose text happens to say “not found.” The root route provides the recovery link back to the list. + +## Link with typed parameters + +In the list, use `Link` rather than assembling a path by hand: + +```tsx + + {note.title} + +``` + +The route tree supplies the parameter types. Renaming a route or parameter gives TypeScript a chance to find its callers. + +## Put the filter in the URL + +The index route validates the search value before the component reads it: + +```tsx +validateSearch: (search: Record) => ({ + q: typeof search.q === 'string' ? search.q : '', +}), +``` + +`Route.useSearch()` returns this validated value. Filter the list by title, and render a GET form with an input named `q`. Submitting that form produces a shareable URL such as `/?q=server`, with no custom event handler required. A query value with the wrong type falls back to an empty filter. + +The detail route links back with an explicit empty search value: + +```tsx + + All notes + +``` + +That link intentionally clears the filter. The browser Back button returns to the previous filtered URL instead. + +## Check the result + +Open `/?q=server`, choose **Reading server HTML**, and use Back. The filter should still be `server`. Then request `/notes/does-not-exist` and inspect the HTTP status, which should be 404. + +Stop the development server and run: + +```sh +COURSE_CHECKPOINT=02-routes pnpm test:e2e +``` + +The test covers the filtered list, detail navigation, browser Back, and the raw 404 response. If navigation works but the status is 200, check that the loader throws `notFound()` before returning content. + +Next: [Read notes from PostgreSQL](./data). diff --git a/docs/start/framework/react/tutorial/learn-start/seo.md b/docs/start/framework/react/tutorial/learn-start/seo.md new file mode 100644 index 0000000000..181bf055f4 --- /dev/null +++ b/docs/start/framework/react/tutorial/learn-start/seo.md @@ -0,0 +1,68 @@ +--- +id: learn-start-seo +title: Learn Start, SEO for Published Notes +description: Render titles, descriptions, canonical URLs, and Open Graph tags in TanStack Start server HTML, and build a sitemap that excludes private drafts. +--- + +Add search metadata to published notes without exposing private drafts. The [working checkpoint](https://github.com/TanStack/router/tree/main/examples/react/start-learn/checkpoints/06-seo) is `checkpoints/06-seo`. + +## Run this checkpoint + +Keep the authentication database and secret from the previous chapter. Change `APP_ORIGIN` in `.env` to `http://localhost:3145`, then run: + +```sh +pnpm db:generate:06 +pnpm db:migrate:06 +pnpm exec vite checkpoints/06-seo --port 3145 +``` + +The schema is unchanged, so existing accounts and notes remain. If you started here with an empty account database, run `pnpm db:seed:06` to add the public samples. + +## Build metadata from loader data + +The public note server function still selects only published rows. It now returns a canonical URL alongside the note. The route's `head` function reads that loader data and produces: + +- A title containing the note title and site name. +- A description from the first 160 characters of the note body after whitespace normalization. +- An absolute canonical URL. +- Open Graph title, description, URL, and type. + +The description length is this example's editorial choice, not a search-engine requirement. A larger publishing system can give authors a separate description field. This checkpoint has no preview image, so it does not invent an Open Graph image URL. + +`HeadContent` in the root document renders these tags into the server response. They are available before hydration. React escapes title and description text, including quotes and angle brackets; do not build raw HTML strings from note content. + +## Choose the public origin explicitly + +`src/server/site.server.ts` validates `APP_ORIGIN` as an HTTP or HTTPS origin without a trailing slash. Canonical URLs and the sitemap use that configured origin, rather than copying the incoming host header. + +A published note opened with `?utm_source=newsletter` still points to the clean `/notes/your-slug` canonical URL. Google treats canonical annotations as signals when choosing between duplicate URLs, not as guaranteed indexing instructions. See [Google's canonical URL guidance](https://developers.google.com/search/docs/crawling-indexing/consolidate-duplicate-urls). + +The home page has its own canonical URL. Filtered search pages use `noindex` and omit a canonical annotation because their results can differ from the unfiltered home page. Note links are real anchors and remain usable without JavaScript. + +## List only public URLs + +`src/routes/sitemap[.]txt.ts` serves `/sitemap.txt`. The escaped dot in the filename keeps it a literal dot in the route URL. Its database query selects only published slugs, then writes one absolute URL per line, with the home page first. `/robots.txt` points to that sitemap. + +Google supports plain-text sitemaps for page URLs. A single sitemap is limited to 50,000 URLs or 50 MB uncompressed, so split the output before a larger site reaches either limit. Listing a URL does not guarantee indexing. See [Google's sitemap guidance](https://developers.google.com/search/docs/crawling-indexing/sitemaps/build-sitemap). + +The sitemap excludes account pages, private drafts, and search parameters. It uses `no-store` so a response does not keep advertising a note after unpublication. The public detail query independently checks publication state and returns a real HTTP 404 for a draft, an unpublished note, or an unknown slug. + +## Keep access control in the database query + +Private draft pages and the dashboard retain their session and ownership checks, `noindex`, and `private, no-store` responses. Robots directives do not protect private content. The auth checks from the previous chapter still run for every protected data operation. + +Unpublishing prevents subsequent public reads, but cannot retract copies that someone already downloaded or a search engine cached. Publish only content its owner intends to make public. + +## Inspect the HTML without JavaScript + +Open a published note, use **View Page Source**, and find its title, description, canonical link, and visible note body. Open `/sitemap.txt` and confirm the note is listed. Unpublish it from **My notes**, then verify that its public URL returns 404 and disappears from the sitemap. + +Stop the development server and run: + +```sh +COURSE_CHECKPOINT=06-seo pnpm test:e2e +``` + +The test disables JavaScript, creates one published note and one draft, checks metadata and real links, verifies sitemap exclusions, and checks unpublication. It also checks that the server HTML does not contain the configured database URL or auth secret. + +Next: [Build and deploy the application](./deployment). diff --git a/docs/start/framework/react/tutorial/learn-start/setup.md b/docs/start/framework/react/tutorial/learn-start/setup.md new file mode 100644 index 0000000000..b3de5f6c2c --- /dev/null +++ b/docs/start/framework/react/tutorial/learn-start/setup.md @@ -0,0 +1,108 @@ +--- +id: learn-start-setup +title: Learn Start, Set Up the App +description: Run a small TanStack Start app and understand the router, root document, server HTML, and first route. +--- + +Build Field notes, an app for writing and sharing what you learn. This first checkpoint has one route and no database. Later chapters add URLs, storage, forms, accounts, metadata, deployment, and tests to the same app. + +## Run the first checkpoint + +You need Node.js and pnpm. Clone the [TanStack Router repository](https://github.com/TanStack/router) and complete its [dependency and framework build setup](https://github.com/TanStack/router/blob/main/CONTRIBUTING.md). The course checkpoints use the framework packages in that checkout so the code and APIs stay together. + +```sh +cd examples/react/start-learn +pnpm dev +``` + +Open http://localhost:3140. You should see **Field notes** and **Keep a record of what you learn.** The [working checkpoint](https://github.com/TanStack/router/tree/main/examples/react/start-learn/checkpoints/01-setup) is in `checkpoints/01-setup`. Each checkpoint has its own source directory and Vite configuration; the course directory supplies their shared dependencies. + +## Follow a request through the app + +`src/router.tsx` creates the router from the generated route tree: + +```tsx +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ routeTree }) +} +``` + +Start calls `getRouter` for an incoming server-rendered request and creates a router for the browser. Keep request-specific state inside that lifecycle. Do not edit `routeTree.gen.ts`; the route plugin generates it from your route files. + +`src/routes/__root.tsx` supplies the HTML document. `HeadContent` renders the route metadata, and `Scripts` loads the client code. Both belong in the document: + +```tsx +import { HeadContent, Scripts, createRootRoute } from '@tanstack/react-router' +import type { ReactNode } from 'react' +export const Route = createRootRoute({ + head: () => ({ + meta: [ + { charSet: 'utf-8' }, + { name: 'viewport', content: 'width=device-width, initial-scale=1' }, + { title: 'Field notes | Learn Start' }, + ], + }), + shellComponent: ({ children }: { children: ReactNode }) => ( + + + + + + {children} + + + + ), + notFoundComponent: () => ( +
+

Note not found

+ All notes +
+ ), +}) +``` + +The checkpoint's root route supplies that component through `shellComponent`. Its `head` option sets the character encoding, viewport, and page title. Its not-found component will also provide a recovery page when the next chapter adds note URLs. + +Finally, `src/routes/index.tsx` matches `/`: + +```tsx +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ component: Home }) + +function Home() { + return ( +
+

Field notes

+

Keep a record of what you learn.

+
+ ) +} +``` + +Change the paragraph and watch the page update. There is no manual route registration: the file generates the route entry. + +## Check the server response + +With the development server running: + +```sh +curl http://localhost:3140/ +``` + +The response should contain the paragraph you just edited, not only an empty root element. Browser source inspection shows the same distinction. This verifies server-rendered content; it does not by itself prove every client interaction works. + +Stop the development server before running the checkpoint test, because the test starts its own server: + +```sh +pnpm exec playwright install chromium +COURSE_CHECKPOINT=01-setup pnpm test:e2e +``` + +The test requests the raw HTML and opens the page in a browser. If the page is empty, inspect the terminal first, then check `HeadContent`, `Scripts`, and the generated route tree against the checkpoint. + +Next: [Give notes their own URLs](./routes). diff --git a/docs/start/framework/react/tutorial/learn-start/tests.md b/docs/start/framework/react/tutorial/learn-start/tests.md new file mode 100644 index 0000000000..3400755c36 --- /dev/null +++ b/docs/start/framework/react/tutorial/learn-start/tests.md @@ -0,0 +1,69 @@ +--- +id: learn-start-tests +title: Learn Start, Test the Complete Application +description: Test a complete TanStack Start app with Playwright, covering accounts, ownership, database rollback, server HTML, SEO, and production deployment behavior. +--- + +Run the earlier checks against one complete application. The [working checkpoint](https://github.com/TanStack/router/tree/main/examples/react/start-learn/checkpoints/08-tests) is `checkpoints/08-tests`. It preserves the deployment chapter's app and adds the combined tests in `tests/final-*.spec.ts`. + +## Prepare the final checkpoint + +Keep the account database and secret. Set `APP_ORIGIN` in `.env` to `http://localhost:3147` for manual development, then run: + +```sh +pnpm db:generate:08 +pnpm db:migrate:08 +pnpm db:seed:08 +COURSE_CHECKPOINT=08-tests pnpm test:e2e +pnpm build:08 +COURSE_PRODUCTION=1 COURSE_CHECKPOINT=08-tests pnpm test:e2e +``` + +Run these commands from `examples/react/start-learn`. Install Playwright's Chromium browser with `pnpm exec playwright install chromium` if it is not already installed. Stop any manually started checkpoint server before running tests; Playwright owns the server for each test run. + +The schema is unchanged from the account chapter. The seed adds public sample notes if they are absent. Use a disposable local or test database, not a production database. Tests create and remove temporary records, and they deliberately alter their test accounts' session expiry times. + +## Check boundaries, not only button clicks + +| Test file | What it proves | +| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `final-authentication.spec.ts` | Account creation and sign-in, private drafts, owner-filtered reads and writes, publication, cross-site rejection, sign-out, renewal, expiry, duplicate-slug transaction rollback, and server-side validation. | +| `final-seo.spec.ts` | Titles, descriptions, canonical URLs, links, and content without JavaScript; sitemap exclusions; real 404s; unpublication; private redirect caching. | +| `final-deployment.spec.ts` | Database readiness and direct server HTML; public-asset secret checks and copied-artifact startup in production mode. | + +The account test replays actual browser requests. It sends an authenticated write with cross-site metadata, then repeats an owner's request from another signed-in account. Those checks distinguish CSRF protection from ownership authorization. A test that only checks for a login redirect would miss both failures. + +The duplicate-slug check submits a new category with an existing slug, then queries PostgreSQL to prove the transaction rolled the new category back. A visible error alone would not prove that the database stayed consistent. + +The SEO test disables JavaScript. The deployment test starts the generated Node entry point. Development-only browser success does not prove either server HTML or production behavior. + +## Keep test data separate + +Tests use unique record names and remove their own accounts, notes, and categories in `finally` blocks. Earlier anonymous checkpoints use `DATABASE_URL`; account checkpoints use `AUTH_DATABASE_URL`. Keep those databases separate so an earlier anonymous app cannot expose private data created later. + +Do not point a test suite at a hosted customer database. If a test fails before cleanup completes, use its unique record prefix to inspect and remove its fixtures from the test database. + +## Run an earlier checkpoint independently + +`COURSE_CHECKPOINT` selects one server and its matching test files. It does not start every chapter's app. + +| Checkpoint | Port | Test command | +| ------------------- | ---- | --------------------------------------------------- | +| `01-setup` | 3140 | `COURSE_CHECKPOINT=01-setup pnpm test:e2e` | +| `02-routes` | 3141 | `COURSE_CHECKPOINT=02-routes pnpm test:e2e` | +| `03-data` | 3142 | `COURSE_CHECKPOINT=03-data pnpm test:e2e` | +| `04-forms` | 3143 | `COURSE_CHECKPOINT=04-forms pnpm test:e2e` | +| `05-authentication` | 3144 | `COURSE_CHECKPOINT=05-authentication pnpm test:e2e` | +| `06-seo` | 3145 | `COURSE_CHECKPOINT=06-seo pnpm test:e2e` | +| `07-deployment` | 3146 | `COURSE_CHECKPOINT=07-deployment pnpm test:e2e` | +| `08-tests` | 3147 | `COURSE_CHECKPOINT=08-tests pnpm test:e2e` | + +Before testing a database chapter, run its client generation and migration commands. Before adding `COURSE_PRODUCTION=1`, build that checkpoint. For example, checkpoint 04 uses `pnpm exec vite build checkpoints/04-forms` followed by `pnpm exec tsc -p checkpoints/04-forms`. + +The deployment artifact check also uses port 3148 for its temporary server. It runs only in production mode, so the development suite reports that check as skipped. + +## Make changes with a failing case in mind + +When changing publication rules, add an assertion for a note that must remain private. When changing sessions, check a revoked or expired session. When changing a loader, inspect its direct HTML response as well as client navigation. Add a test because it catches a plausible failure, not because a new function needs a matching test file. + +Return to the [course index](../learn-start) before extending the app for real users. Hosted deployment and account operations still need the checks described in the [deployment chapter](./deployment). diff --git a/docs/start/framework/react/tutorial/reading-writing-file.md b/docs/start/framework/react/tutorial/reading-writing-file.md index f4af4480f1..78e60683d0 100644 --- a/docs/start/framework/react/tutorial/reading-writing-file.md +++ b/docs/start/framework/react/tutorial/reading-writing-file.md @@ -3,6 +3,8 @@ id: reading-and-writing-file title: Building a Full Stack DevJokes App with TanStack Start --- +For a course that adds routing, a database, accounts, SEO, deployment, and tests to one app, see [Learn Start](./learn-start). + This tutorial will guide you through building a complete full-stack application using TanStack Start. You'll create a DevJokes app where users can view and add developer-themed jokes, demonstrating key concepts of TanStack Start including server functions, file-based data storage, and React components. Here's a demo of the app in action: diff --git a/examples/react/start-learn/.env.example b/examples/react/start-learn/.env.example new file mode 100644 index 0000000000..c95fabf1c0 --- /dev/null +++ b/examples/react/start-learn/.env.example @@ -0,0 +1,4 @@ +DATABASE_URL="postgresql://start_demo:start_demo@localhost:5433/learn_start" +AUTH_DATABASE_URL="postgresql://start_demo:start_demo@localhost:5433/learn_start_auth" +BETTER_AUTH_SECRET="" +APP_ORIGIN="http://localhost:3144" diff --git a/examples/react/start-learn/.gitignore b/examples/react/start-learn/.gitignore new file mode 100644 index 0000000000..daeca4bd11 --- /dev/null +++ b/examples/react/start-learn/.gitignore @@ -0,0 +1,9 @@ +node_modules +.env +.output +.tanstack +test-results +playwright-report +**/src/generated/ +.postgres/ +.postgres-password diff --git a/examples/react/start-learn/README.md b/examples/react/start-learn/README.md new file mode 100644 index 0000000000..43e9da408e --- /dev/null +++ b/examples/react/start-learn/README.md @@ -0,0 +1,66 @@ +# Learn Start + +Build Field notes through eight independently runnable checkpoints. The [course](https://tanstack.com/start/latest/docs/framework/react/tutorial/learn-start) explains each change, from a single route to an app with accounts and published notes. + +This example lives in the TanStack Router workspace. Follow the repository's [contribution setup](../../../CONTRIBUTING.md) to install dependencies and build the framework packages first. Run the commands below from `examples/react/start-learn`. + +## Start the course + +```sh +pnpm dev +``` + +Open http://localhost:3140. This first checkpoint needs no database or auth secret. + +| Checkpoint | Source root | Port | +| -------------- | ------------------------------- | ---- | +| Setup | `checkpoints/01-setup` | 3140 | +| Routes | `checkpoints/02-routes` | 3141 | +| Data | `checkpoints/03-data` | 3142 | +| Forms | `checkpoints/04-forms` | 3143 | +| Authentication | `checkpoints/05-authentication` | 3144 | +| SEO | `checkpoints/06-seo` | 3145 | +| Deployment | `checkpoints/07-deployment` | 3146 | +| Tests | `checkpoints/08-tests` | 3147 | + +Select another source root with Vite, for example `pnpm exec vite checkpoints/02-routes --port 3141`. Each source root has its own generated route tree and production output. + +## Run the complete app + +Create a PostgreSQL database for the account checkpoints. Copy `.env.example` to `.env`, set `AUTH_DATABASE_URL`, set `APP_ORIGIN` to `http://localhost:3147`, and generate `BETTER_AUTH_SECRET` with `openssl rand -base64 48`. Keep `.env` private. + +```sh +pnpm db:generate:08 +pnpm db:migrate:08 +pnpm db:seed:08 +pnpm exec vite checkpoints/08-tests --port 3147 +``` + +Create an account from **My notes**. New notes are private until their owner publishes them. The seed adds two public sample notes. + +Checkpoints 03 and 04 are anonymous local demos. They use `DATABASE_URL`, which must point to a separate database from `AUTH_DATABASE_URL`. Do not expose that anonymous app to a database containing private notes. Each database chapter documents its own generation, migration, and seed commands. + +## Build and test + +Stop the development server before running Playwright: + +```sh +pnpm exec playwright install chromium +COURSE_CHECKPOINT=08-tests pnpm test:e2e +pnpm build:08 +COURSE_PRODUCTION=1 COURSE_CHECKPOINT=08-tests pnpm test:e2e +``` + +`COURSE_CHECKPOINT` starts only the selected app and runs its matching tests. Without it, tests select `01-setup`. Generate the selected database checkpoint's client before testing. Production tests require its current build. + +The final suite checks account isolation, session renewal and expiry, protected mutations, validation and rollback, server HTML, canonical URLs, sitemap exclusions, readiness, public-asset secrets, and a copied production artifact. The artifact test uses port 3148 and is skipped in development mode. Use disposable test databases; these tests write and clean up their own fixtures. + +To start the final build locally with `.env`: + +```sh +APP_ORIGIN=http://localhost:3147 PORT=3147 node --env-file=.env checkpoints/08-tests/.output/server/index.mjs +``` + +A host that injects environment variables can use `pnpm start:08` from the checkout, or copy the complete `.output` directory and run `node .output/server/index.mjs`. Apply migrations from the source checkout as a release step. + +Local production checks do not verify hosting, DNS, TLS, mail delivery, or a remote deployment. Configure verification, recovery, rate-limit storage, and trusted proxy handling for your public service before opening registration to real users. See the [deployment chapter](https://tanstack.com/start/latest/docs/framework/react/tutorial/learn-start/deployment). diff --git a/examples/react/start-learn/checkpoints/01-setup/src/routeTree.gen.ts b/examples/react/start-learn/checkpoints/01-setup/src/routeTree.gen.ts new file mode 100644 index 0000000000..dceedffdc1 --- /dev/null +++ b/examples/react/start-learn/checkpoints/01-setup/src/routeTree.gen.ts @@ -0,0 +1,68 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' + fileRoutesByTo: FileRoutesByTo + to: '/' + id: '__root__' | '/' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() + +import type { getRouter } from './router.tsx' +import type { createStart } from '@tanstack/react-start' +declare module '@tanstack/react-start' { + interface Register { + ssr: true + router: Awaited> + } +} diff --git a/examples/react/start-learn/checkpoints/01-setup/src/router.tsx b/examples/react/start-learn/checkpoints/01-setup/src/router.tsx new file mode 100644 index 0000000000..bb899b1fdf --- /dev/null +++ b/examples/react/start-learn/checkpoints/01-setup/src/router.tsx @@ -0,0 +1,5 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' +export function getRouter() { + return createRouter({ routeTree }) +} diff --git a/examples/react/start-learn/checkpoints/01-setup/src/routes/__root.tsx b/examples/react/start-learn/checkpoints/01-setup/src/routes/__root.tsx new file mode 100644 index 0000000000..35c22bc682 --- /dev/null +++ b/examples/react/start-learn/checkpoints/01-setup/src/routes/__root.tsx @@ -0,0 +1,28 @@ +import { HeadContent, Scripts, createRootRoute } from '@tanstack/react-router' +import type { ReactNode } from 'react' +export const Route = createRootRoute({ + head: () => ({ + meta: [ + { charSet: 'utf-8' }, + { name: 'viewport', content: 'width=device-width, initial-scale=1' }, + { title: 'Field notes | Learn Start' }, + ], + }), + shellComponent: ({ children }: { children: ReactNode }) => ( + + + + + + {children} + + + + ), + notFoundComponent: () => ( +
+

Note not found

+ All notes +
+ ), +}) diff --git a/examples/react/start-learn/checkpoints/01-setup/src/routes/index.tsx b/examples/react/start-learn/checkpoints/01-setup/src/routes/index.tsx new file mode 100644 index 0000000000..9bce218b85 --- /dev/null +++ b/examples/react/start-learn/checkpoints/01-setup/src/routes/index.tsx @@ -0,0 +1,10 @@ +import { createFileRoute } from '@tanstack/react-router' +export const Route = createFileRoute('/')({ component: Home }) +function Home() { + return ( +
+

Field notes

+

Keep a record of what you learn.

+
+ ) +} diff --git a/examples/react/start-learn/checkpoints/01-setup/tsconfig.json b/examples/react/start-learn/checkpoints/01-setup/tsconfig.json new file mode 100644 index 0000000000..3d61827d71 --- /dev/null +++ b/examples/react/start-learn/checkpoints/01-setup/tsconfig.json @@ -0,0 +1,4 @@ +{ + "extends": "../../tsconfig.base.json", + "include": ["src", "vite.config.ts"] +} diff --git a/examples/react/start-learn/checkpoints/01-setup/vite.config.ts b/examples/react/start-learn/checkpoints/01-setup/vite.config.ts new file mode 100644 index 0000000000..195c5224e2 --- /dev/null +++ b/examples/react/start-learn/checkpoints/01-setup/vite.config.ts @@ -0,0 +1,7 @@ +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import { defineConfig } from 'vite' +import viteReact from '@vitejs/plugin-react' +import { nitro } from 'nitro/vite' +export default defineConfig({ + plugins: [tanstackStart(), viteReact(), nitro()], +}) diff --git a/examples/react/start-learn/checkpoints/02-routes/src/notes.ts b/examples/react/start-learn/checkpoints/02-routes/src/notes.ts new file mode 100644 index 0000000000..11b2e90778 --- /dev/null +++ b/examples/react/start-learn/checkpoints/02-routes/src/notes.ts @@ -0,0 +1,12 @@ +export const notes = [ + { + slug: 'first-route', + title: 'My first route', + body: 'A route connects a URL to the content it displays.', + }, + { + slug: 'server-html', + title: 'Reading server HTML', + body: 'A direct request can contain useful content before JavaScript runs.', + }, +] diff --git a/examples/react/start-learn/checkpoints/02-routes/src/routeTree.gen.ts b/examples/react/start-learn/checkpoints/02-routes/src/routeTree.gen.ts new file mode 100644 index 0000000000..816f25acfb --- /dev/null +++ b/examples/react/start-learn/checkpoints/02-routes/src/routeTree.gen.ts @@ -0,0 +1,86 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as NotesSlugRouteImport } from './routes/notes.$slug' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const NotesSlugRoute = NotesSlugRouteImport.update({ + id: '/notes/$slug', + path: '/notes/$slug', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/notes/$slug': typeof NotesSlugRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/notes/$slug': typeof NotesSlugRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/notes/$slug': typeof NotesSlugRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/notes/$slug' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/notes/$slug' + id: '__root__' | '/' | '/notes/$slug' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + NotesSlugRoute: typeof NotesSlugRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/notes/$slug': { + id: '/notes/$slug' + path: '/notes/$slug' + fullPath: '/notes/$slug' + preLoaderRoute: typeof NotesSlugRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + NotesSlugRoute: NotesSlugRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() + +import type { getRouter } from './router.tsx' +import type { createStart } from '@tanstack/react-start' +declare module '@tanstack/react-start' { + interface Register { + ssr: true + router: Awaited> + } +} diff --git a/examples/react/start-learn/checkpoints/02-routes/src/router.tsx b/examples/react/start-learn/checkpoints/02-routes/src/router.tsx new file mode 100644 index 0000000000..bb899b1fdf --- /dev/null +++ b/examples/react/start-learn/checkpoints/02-routes/src/router.tsx @@ -0,0 +1,5 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' +export function getRouter() { + return createRouter({ routeTree }) +} diff --git a/examples/react/start-learn/checkpoints/02-routes/src/routes/__root.tsx b/examples/react/start-learn/checkpoints/02-routes/src/routes/__root.tsx new file mode 100644 index 0000000000..35c22bc682 --- /dev/null +++ b/examples/react/start-learn/checkpoints/02-routes/src/routes/__root.tsx @@ -0,0 +1,28 @@ +import { HeadContent, Scripts, createRootRoute } from '@tanstack/react-router' +import type { ReactNode } from 'react' +export const Route = createRootRoute({ + head: () => ({ + meta: [ + { charSet: 'utf-8' }, + { name: 'viewport', content: 'width=device-width, initial-scale=1' }, + { title: 'Field notes | Learn Start' }, + ], + }), + shellComponent: ({ children }: { children: ReactNode }) => ( + + + + + + {children} + + + + ), + notFoundComponent: () => ( +
+

Note not found

+ All notes +
+ ), +}) diff --git a/examples/react/start-learn/checkpoints/02-routes/src/routes/index.tsx b/examples/react/start-learn/checkpoints/02-routes/src/routes/index.tsx new file mode 100644 index 0000000000..db31c799b6 --- /dev/null +++ b/examples/react/start-learn/checkpoints/02-routes/src/routes/index.tsx @@ -0,0 +1,35 @@ +import { createFileRoute, Link } from '@tanstack/react-router' +import { notes } from '../notes' +export const Route = createFileRoute('/')({ + validateSearch: (search: Record) => ({ + q: typeof search.q === 'string' ? search.q : '', + }), + component: Home, +}) +function Home() { + const { q } = Route.useSearch() + const matches = notes.filter((note) => + note.title.toLowerCase().includes(q.toLowerCase()), + ) + return ( +
+

Field notes

+
+ + +
+
    + {matches.map((note) => ( +
  • + + {note.title} + +
  • + ))} +
+ {matches.length === 0 ?

No matching notes.

: null} +
+ ) +} diff --git a/examples/react/start-learn/checkpoints/02-routes/src/routes/notes.$slug.tsx b/examples/react/start-learn/checkpoints/02-routes/src/routes/notes.$slug.tsx new file mode 100644 index 0000000000..d7b36c8fa0 --- /dev/null +++ b/examples/react/start-learn/checkpoints/02-routes/src/routes/notes.$slug.tsx @@ -0,0 +1,24 @@ +import { createFileRoute, Link, notFound } from '@tanstack/react-router' +import { notes } from '../notes' +export const Route = createFileRoute('/notes/$slug')({ + loader: ({ params }) => { + const note = notes.find((item) => item.slug === params.slug) + if (!note) { + throw notFound() + } + return note + }, + component: Note, +}) +function Note() { + const note = Route.useLoaderData() + return ( +
+ + All notes + +

{note.title}

+

{note.body}

+
+ ) +} diff --git a/examples/react/start-learn/checkpoints/02-routes/tsconfig.json b/examples/react/start-learn/checkpoints/02-routes/tsconfig.json new file mode 100644 index 0000000000..3d61827d71 --- /dev/null +++ b/examples/react/start-learn/checkpoints/02-routes/tsconfig.json @@ -0,0 +1,4 @@ +{ + "extends": "../../tsconfig.base.json", + "include": ["src", "vite.config.ts"] +} diff --git a/examples/react/start-learn/checkpoints/02-routes/vite.config.ts b/examples/react/start-learn/checkpoints/02-routes/vite.config.ts new file mode 100644 index 0000000000..195c5224e2 --- /dev/null +++ b/examples/react/start-learn/checkpoints/02-routes/vite.config.ts @@ -0,0 +1,7 @@ +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import { defineConfig } from 'vite' +import viteReact from '@vitejs/plugin-react' +import { nitro } from 'nitro/vite' +export default defineConfig({ + plugins: [tanstackStart(), viteReact(), nitro()], +}) diff --git a/examples/react/start-learn/checkpoints/03-data/prisma.config.ts b/examples/react/start-learn/checkpoints/03-data/prisma.config.ts new file mode 100644 index 0000000000..0daa8973bf --- /dev/null +++ b/examples/react/start-learn/checkpoints/03-data/prisma.config.ts @@ -0,0 +1,7 @@ +import 'dotenv/config' +import { defineConfig, env } from 'prisma/config' +export default defineConfig({ + schema: './prisma/schema.prisma', + migrations: { path: './prisma/migrations' }, + datasource: { url: env('DATABASE_URL') }, +}) diff --git a/examples/react/start-learn/checkpoints/03-data/prisma/migrations/20260911000000_notes/migration.sql b/examples/react/start-learn/checkpoints/03-data/prisma/migrations/20260911000000_notes/migration.sql new file mode 100644 index 0000000000..52a674f82c --- /dev/null +++ b/examples/react/start-learn/checkpoints/03-data/prisma/migrations/20260911000000_notes/migration.sql @@ -0,0 +1,12 @@ +CREATE TABLE "Category" ( + "name" TEXT NOT NULL, + CONSTRAINT "Category_pkey" PRIMARY KEY ("name") +); +CREATE TABLE "Note" ( + "slug" TEXT NOT NULL, + "title" TEXT NOT NULL, + "body" TEXT NOT NULL, + "categoryName" TEXT NOT NULL, + CONSTRAINT "Note_pkey" PRIMARY KEY ("slug") +); +ALTER TABLE "Note" ADD CONSTRAINT "Note_categoryName_fkey" FOREIGN KEY ("categoryName") REFERENCES "Category"("name") ON DELETE RESTRICT ON UPDATE CASCADE; diff --git a/examples/react/start-learn/checkpoints/03-data/prisma/migrations/migration_lock.toml b/examples/react/start-learn/checkpoints/03-data/prisma/migrations/migration_lock.toml new file mode 100644 index 0000000000..2fe25d87cc --- /dev/null +++ b/examples/react/start-learn/checkpoints/03-data/prisma/migrations/migration_lock.toml @@ -0,0 +1 @@ +provider = "postgresql" diff --git a/examples/react/start-learn/checkpoints/03-data/prisma/schema.prisma b/examples/react/start-learn/checkpoints/03-data/prisma/schema.prisma new file mode 100644 index 0000000000..fc70787077 --- /dev/null +++ b/examples/react/start-learn/checkpoints/03-data/prisma/schema.prisma @@ -0,0 +1,18 @@ +generator client { + provider = "prisma-client" + output = "../src/generated/prisma" +} +datasource db { + provider = "postgresql" +} +model Category { + name String @id + notes Note[] +} +model Note { + slug String @id + title String + body String + categoryName String + category Category @relation(fields: [categoryName], references: [name]) +} diff --git a/examples/react/start-learn/checkpoints/03-data/prisma/seed.sql b/examples/react/start-learn/checkpoints/03-data/prisma/seed.sql new file mode 100644 index 0000000000..32401cee94 --- /dev/null +++ b/examples/react/start-learn/checkpoints/03-data/prisma/seed.sql @@ -0,0 +1,5 @@ +INSERT INTO "Category" ("name") VALUES ('Routing') ON CONFLICT DO NOTHING; +INSERT INTO "Note" ("slug", "title", "body", "categoryName") VALUES +('first-route', 'My first route', 'A route connects a URL to the content it displays.', 'Routing'), +('server-html', 'Reading server HTML', 'A direct request can contain useful content before JavaScript runs.', 'Routing') +ON CONFLICT DO NOTHING; diff --git a/examples/react/start-learn/checkpoints/03-data/src/routeTree.gen.ts b/examples/react/start-learn/checkpoints/03-data/src/routeTree.gen.ts new file mode 100644 index 0000000000..a8c21a8b9e --- /dev/null +++ b/examples/react/start-learn/checkpoints/03-data/src/routeTree.gen.ts @@ -0,0 +1,87 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as NotesSlugRouteImport } from './routes/notes.$slug' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const NotesSlugRoute = NotesSlugRouteImport.update({ + id: '/notes/$slug', + path: '/notes/$slug', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/notes/$slug': typeof NotesSlugRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/notes/$slug': typeof NotesSlugRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/notes/$slug': typeof NotesSlugRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/notes/$slug' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/notes/$slug' + id: '__root__' | '/' | '/notes/$slug' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + NotesSlugRoute: typeof NotesSlugRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/notes/$slug': { + id: '/notes/$slug' + path: '/notes/$slug' + fullPath: '/notes/$slug' + preLoaderRoute: typeof NotesSlugRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + NotesSlugRoute: NotesSlugRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() + +import type { getRouter } from './router.tsx' +import type { startInstance } from './start.ts' +declare module '@tanstack/react-start' { + interface Register { + ssr: true + router: Awaited> + config: Awaited> + } +} diff --git a/examples/react/start-learn/checkpoints/03-data/src/router.tsx b/examples/react/start-learn/checkpoints/03-data/src/router.tsx new file mode 100644 index 0000000000..bb899b1fdf --- /dev/null +++ b/examples/react/start-learn/checkpoints/03-data/src/router.tsx @@ -0,0 +1,5 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' +export function getRouter() { + return createRouter({ routeTree }) +} diff --git a/examples/react/start-learn/checkpoints/03-data/src/routes/__root.tsx b/examples/react/start-learn/checkpoints/03-data/src/routes/__root.tsx new file mode 100644 index 0000000000..9a21c3c91a --- /dev/null +++ b/examples/react/start-learn/checkpoints/03-data/src/routes/__root.tsx @@ -0,0 +1,34 @@ +import { HeadContent, Scripts, createRootRoute } from '@tanstack/react-router' +import type { ReactNode } from 'react' +export const Route = createRootRoute({ + head: () => ({ + meta: [ + { charSet: 'utf-8' }, + { name: 'viewport', content: 'width=device-width, initial-scale=1' }, + { title: 'Field notes | Learn Start' }, + ], + }), + shellComponent: ({ children }: { children: ReactNode }) => ( + + + + + + {children} + + + + ), + errorComponent: () => ( +
+

Could not load notes

+ Try again +
+ ), + notFoundComponent: () => ( +
+

Note not found

+ All notes +
+ ), +}) diff --git a/examples/react/start-learn/checkpoints/03-data/src/routes/index.tsx b/examples/react/start-learn/checkpoints/03-data/src/routes/index.tsx new file mode 100644 index 0000000000..e1e7dba030 --- /dev/null +++ b/examples/react/start-learn/checkpoints/03-data/src/routes/index.tsx @@ -0,0 +1,36 @@ +import { createFileRoute, Link } from '@tanstack/react-router' +import { z } from 'zod' +import { listNotes } from '../server/notes' +export const Route = createFileRoute('/')({ + validateSearch: z.object({ q: z.string().max(200).catch('') }), + loaderDeps: ({ search }) => ({ q: search.q }), + loader: ({ deps }) => listNotes({ data: deps }), + headers: () => ({ 'Cache-Control': 'no-store' }), + component: Home, +}) +function Home() { + const { q } = Route.useSearch() + const notes = Route.useLoaderData() + return ( +
+

Field notes

+
+ + +
+
    + {notes.map((note) => ( +
  • + + {note.title} + {' '} + ({note.categoryName}) +
  • + ))} +
+ {notes.length === 0 ?

No matching notes.

: null} +
+ ) +} diff --git a/examples/react/start-learn/checkpoints/03-data/src/routes/notes.$slug.tsx b/examples/react/start-learn/checkpoints/03-data/src/routes/notes.$slug.tsx new file mode 100644 index 0000000000..683f524721 --- /dev/null +++ b/examples/react/start-learn/checkpoints/03-data/src/routes/notes.$slug.tsx @@ -0,0 +1,28 @@ +import { createFileRoute, Link, notFound } from '@tanstack/react-router' +import { getNote } from '../server/notes' +export const Route = createFileRoute('/notes/$slug')({ + loader: async ({ params }) => { + if (params.slug.length > 80) { + throw notFound() + } + const note = await getNote({ data: params.slug }) + if (!note) { + throw notFound() + } + return note + }, + headers: () => ({ 'Cache-Control': 'no-store' }), + component: Note, +}) +function Note() { + const note = Route.useLoaderData() + return ( +
+ + All notes + +

{note.title}

+

{note.body}

+
+ ) +} diff --git a/examples/react/start-learn/checkpoints/03-data/src/server/db.server.ts b/examples/react/start-learn/checkpoints/03-data/src/server/db.server.ts new file mode 100644 index 0000000000..19959c5a2e --- /dev/null +++ b/examples/react/start-learn/checkpoints/03-data/src/server/db.server.ts @@ -0,0 +1,10 @@ +import '@tanstack/react-start/server-only' +import { PrismaPg } from '@prisma/adapter-pg' +import { PrismaClient } from '../generated/prisma/client' +const connectionString = process.env.DATABASE_URL +if (!connectionString) { + throw new Error('Set DATABASE_URL before starting the server') +} +export const db = new PrismaClient({ + adapter: new PrismaPg({ connectionString, max: 5 }), +}) diff --git a/examples/react/start-learn/checkpoints/03-data/src/server/notes.ts b/examples/react/start-learn/checkpoints/03-data/src/server/notes.ts new file mode 100644 index 0000000000..6ad79632fa --- /dev/null +++ b/examples/react/start-learn/checkpoints/03-data/src/server/notes.ts @@ -0,0 +1,25 @@ +import { createServerFn } from '@tanstack/react-start' +import { setResponseHeader } from '@tanstack/react-start/server' +import { z } from 'zod' +import { db } from './db.server' + +export const listNotes = createServerFn({ method: 'GET' }) + .validator(z.object({ q: z.string().max(200) })) + .handler(async ({ data }) => { + setResponseHeader('Cache-Control', 'no-store') + return db.note.findMany({ + where: { title: { contains: data.q, mode: 'insensitive' } }, + select: { slug: true, title: true, categoryName: true }, + orderBy: { slug: 'asc' }, + }) + }) + +export const getNote = createServerFn({ method: 'GET' }) + .validator(z.string().min(1).max(80)) + .handler(async ({ data }) => { + setResponseHeader('Cache-Control', 'no-store') + return db.note.findUnique({ + where: { slug: data }, + select: { slug: true, title: true, body: true, categoryName: true }, + }) + }) diff --git a/examples/react/start-learn/checkpoints/03-data/src/start.ts b/examples/react/start-learn/checkpoints/03-data/src/start.ts new file mode 100644 index 0000000000..5fb1e247fb --- /dev/null +++ b/examples/react/start-learn/checkpoints/03-data/src/start.ts @@ -0,0 +1,9 @@ +import { createCsrfMiddleware, createStart } from '@tanstack/react-start' + +export const startInstance = createStart(() => ({ + requestMiddleware: [ + createCsrfMiddleware({ + filter: (ctx) => ctx.handlerType === 'serverFn', + }), + ], +})) diff --git a/examples/react/start-learn/checkpoints/03-data/tsconfig.json b/examples/react/start-learn/checkpoints/03-data/tsconfig.json new file mode 100644 index 0000000000..3d61827d71 --- /dev/null +++ b/examples/react/start-learn/checkpoints/03-data/tsconfig.json @@ -0,0 +1,4 @@ +{ + "extends": "../../tsconfig.base.json", + "include": ["src", "vite.config.ts"] +} diff --git a/examples/react/start-learn/checkpoints/03-data/vite.config.ts b/examples/react/start-learn/checkpoints/03-data/vite.config.ts new file mode 100644 index 0000000000..e7dc90847a --- /dev/null +++ b/examples/react/start-learn/checkpoints/03-data/vite.config.ts @@ -0,0 +1,8 @@ +import 'dotenv/config' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import { defineConfig } from 'vite' +import viteReact from '@vitejs/plugin-react' +import { nitro } from 'nitro/vite' +export default defineConfig({ + plugins: [tanstackStart(), viteReact(), nitro()], +}) diff --git a/examples/react/start-learn/checkpoints/04-forms/prisma.config.ts b/examples/react/start-learn/checkpoints/04-forms/prisma.config.ts new file mode 100644 index 0000000000..0daa8973bf --- /dev/null +++ b/examples/react/start-learn/checkpoints/04-forms/prisma.config.ts @@ -0,0 +1,7 @@ +import 'dotenv/config' +import { defineConfig, env } from 'prisma/config' +export default defineConfig({ + schema: './prisma/schema.prisma', + migrations: { path: './prisma/migrations' }, + datasource: { url: env('DATABASE_URL') }, +}) diff --git a/examples/react/start-learn/checkpoints/04-forms/prisma/migrations/20260911000000_notes/migration.sql b/examples/react/start-learn/checkpoints/04-forms/prisma/migrations/20260911000000_notes/migration.sql new file mode 100644 index 0000000000..52a674f82c --- /dev/null +++ b/examples/react/start-learn/checkpoints/04-forms/prisma/migrations/20260911000000_notes/migration.sql @@ -0,0 +1,12 @@ +CREATE TABLE "Category" ( + "name" TEXT NOT NULL, + CONSTRAINT "Category_pkey" PRIMARY KEY ("name") +); +CREATE TABLE "Note" ( + "slug" TEXT NOT NULL, + "title" TEXT NOT NULL, + "body" TEXT NOT NULL, + "categoryName" TEXT NOT NULL, + CONSTRAINT "Note_pkey" PRIMARY KEY ("slug") +); +ALTER TABLE "Note" ADD CONSTRAINT "Note_categoryName_fkey" FOREIGN KEY ("categoryName") REFERENCES "Category"("name") ON DELETE RESTRICT ON UPDATE CASCADE; diff --git a/examples/react/start-learn/checkpoints/04-forms/prisma/migrations/migration_lock.toml b/examples/react/start-learn/checkpoints/04-forms/prisma/migrations/migration_lock.toml new file mode 100644 index 0000000000..2fe25d87cc --- /dev/null +++ b/examples/react/start-learn/checkpoints/04-forms/prisma/migrations/migration_lock.toml @@ -0,0 +1 @@ +provider = "postgresql" diff --git a/examples/react/start-learn/checkpoints/04-forms/prisma/schema.prisma b/examples/react/start-learn/checkpoints/04-forms/prisma/schema.prisma new file mode 100644 index 0000000000..fc70787077 --- /dev/null +++ b/examples/react/start-learn/checkpoints/04-forms/prisma/schema.prisma @@ -0,0 +1,18 @@ +generator client { + provider = "prisma-client" + output = "../src/generated/prisma" +} +datasource db { + provider = "postgresql" +} +model Category { + name String @id + notes Note[] +} +model Note { + slug String @id + title String + body String + categoryName String + category Category @relation(fields: [categoryName], references: [name]) +} diff --git a/examples/react/start-learn/checkpoints/04-forms/prisma/seed.sql b/examples/react/start-learn/checkpoints/04-forms/prisma/seed.sql new file mode 100644 index 0000000000..32401cee94 --- /dev/null +++ b/examples/react/start-learn/checkpoints/04-forms/prisma/seed.sql @@ -0,0 +1,5 @@ +INSERT INTO "Category" ("name") VALUES ('Routing') ON CONFLICT DO NOTHING; +INSERT INTO "Note" ("slug", "title", "body", "categoryName") VALUES +('first-route', 'My first route', 'A route connects a URL to the content it displays.', 'Routing'), +('server-html', 'Reading server HTML', 'A direct request can contain useful content before JavaScript runs.', 'Routing') +ON CONFLICT DO NOTHING; diff --git a/examples/react/start-learn/checkpoints/04-forms/src/routeTree.gen.ts b/examples/react/start-learn/checkpoints/04-forms/src/routeTree.gen.ts new file mode 100644 index 0000000000..a8c21a8b9e --- /dev/null +++ b/examples/react/start-learn/checkpoints/04-forms/src/routeTree.gen.ts @@ -0,0 +1,87 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as NotesSlugRouteImport } from './routes/notes.$slug' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const NotesSlugRoute = NotesSlugRouteImport.update({ + id: '/notes/$slug', + path: '/notes/$slug', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/notes/$slug': typeof NotesSlugRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/notes/$slug': typeof NotesSlugRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/notes/$slug': typeof NotesSlugRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/notes/$slug' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/notes/$slug' + id: '__root__' | '/' | '/notes/$slug' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + NotesSlugRoute: typeof NotesSlugRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/notes/$slug': { + id: '/notes/$slug' + path: '/notes/$slug' + fullPath: '/notes/$slug' + preLoaderRoute: typeof NotesSlugRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + NotesSlugRoute: NotesSlugRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() + +import type { getRouter } from './router.tsx' +import type { startInstance } from './start.ts' +declare module '@tanstack/react-start' { + interface Register { + ssr: true + router: Awaited> + config: Awaited> + } +} diff --git a/examples/react/start-learn/checkpoints/04-forms/src/router.tsx b/examples/react/start-learn/checkpoints/04-forms/src/router.tsx new file mode 100644 index 0000000000..bb899b1fdf --- /dev/null +++ b/examples/react/start-learn/checkpoints/04-forms/src/router.tsx @@ -0,0 +1,5 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' +export function getRouter() { + return createRouter({ routeTree }) +} diff --git a/examples/react/start-learn/checkpoints/04-forms/src/routes/__root.tsx b/examples/react/start-learn/checkpoints/04-forms/src/routes/__root.tsx new file mode 100644 index 0000000000..9a21c3c91a --- /dev/null +++ b/examples/react/start-learn/checkpoints/04-forms/src/routes/__root.tsx @@ -0,0 +1,34 @@ +import { HeadContent, Scripts, createRootRoute } from '@tanstack/react-router' +import type { ReactNode } from 'react' +export const Route = createRootRoute({ + head: () => ({ + meta: [ + { charSet: 'utf-8' }, + { name: 'viewport', content: 'width=device-width, initial-scale=1' }, + { title: 'Field notes | Learn Start' }, + ], + }), + shellComponent: ({ children }: { children: ReactNode }) => ( + + + + + + {children} + + + + ), + errorComponent: () => ( +
+

Could not load notes

+ Try again +
+ ), + notFoundComponent: () => ( +
+

Note not found

+ All notes +
+ ), +}) diff --git a/examples/react/start-learn/checkpoints/04-forms/src/routes/index.tsx b/examples/react/start-learn/checkpoints/04-forms/src/routes/index.tsx new file mode 100644 index 0000000000..bd1e014062 --- /dev/null +++ b/examples/react/start-learn/checkpoints/04-forms/src/routes/index.tsx @@ -0,0 +1,114 @@ +import { useState } from 'react' +import { useServerFn } from '@tanstack/react-start' +import { + createFileRoute, + Link, + useHydrated, + useRouter, +} from '@tanstack/react-router' +import { z } from 'zod' +import { createNote, listNotes } from '../server/notes' +export const Route = createFileRoute('/')({ + validateSearch: z.object({ q: z.string().max(200).catch('') }), + loaderDeps: ({ search }) => ({ q: search.q }), + loader: ({ deps }) => listNotes({ data: deps }), + headers: () => ({ 'Cache-Control': 'no-store' }), + component: Home, +}) +function Home() { + const { q } = Route.useSearch() + const notes = Route.useLoaderData() + const save = useServerFn(createNote) + const router = useRouter() + const hydrated = useHydrated() + const [pending, setPending] = useState(false) + const [error, setError] = useState('') + return ( +
+

Field notes

+

+ This checkpoint is a shared local notebook. Accounts come in the next + chapter. +

+
{ + event.preventDefault() + const form = event.currentTarget + const fields = new FormData(form) + setPending(true) + setError('') + try { + const result = await save({ + data: { + slug: String(fields.get('slug') ?? ''), + title: String(fields.get('title') ?? ''), + body: String(fields.get('body') ?? ''), + category: String(fields.get('category') ?? ''), + }, + }) + if (result.error) { + setError(result.error) + } else { + await router.invalidate() + form.reset() + } + } catch { + setError('Could not save. Check your input and try again.') + } finally { + setPending(false) + } + }} + > +
+ Create a note +

+ +

+

+ +

+

+