You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@grails.apache.org by ja...@apache.org on 2026/05/03 22:53:48 UTC

(grails-static-website) branch add-grails-vite-spa-v8 created (now c2dbac8a4f3)

This is an automated email from the ASF dual-hosted git repository.

jamesfredley pushed a change to branch add-grails-vite-spa-v8
in repository https://gitbox.apache.org/repos/asf/grails-static-website.git


      at c2dbac8a4f3 Add grails-vite-spa v8 guide

This branch includes the following new commits:

     new c2dbac8a4f3 Add grails-vite-spa v8 guide

The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.



(grails-static-website) 01/01: Add grails-vite-spa v8 guide

Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

jamesfredley pushed a commit to branch add-grails-vite-spa-v8
in repository https://gitbox.apache.org/repos/asf/grails-static-website.git

commit c2dbac8a4f3d81907c9bf02091b3b353594f7f12
Author: James Fredley <ja...@users.noreply.github.com>
AuthorDate: Sun May 3 18:53:41 2026 -0400

    Add grails-vite-spa v8 guide
    
    Two-tier integration guide: Grails 8 rest_api JSON backend plus a Vite/React SPA frontend in a single Gradle multi-project, packaged into one bootJar with the SPA served from the same origin as the API. Replaces the long-broken Webpack-era React/Vue profiles.
    
    Greenfield - new grails-guides/grails-vite-spa repo created public on the grails8 default branch.
    
    The 14 chapters cover the multi-project layout, the JSON backend (Book + RestfulController + JSON views), the SpaController forwarder for client-side routes, the Vite/React frontend, vite.config.js with /api proxy, the dev mode (two servers behind one origin), the prod build (one bootJar), and why CORS never appears.
    
    Verified locally: validateGuides -PvalidationMode=both returns 86 guides 0 errors; renderGuide_grails_vite_spa_8 --rerun-tasks --no-configuration-cache renders all 14 chapter HTML pages, no Unresolved directive errors.
    
    Assisted-by: claude-code:claude-opus-4-7
---
 conf/guides.yml                                    | 49 +++++++++++++++++++
 guides/grails-vite-spa/v8/guide/backend.adoc       | 29 +++++++++++
 guides/grails-vite-spa/v8/guide/cors.adoc          | 11 +++++
 guides/grails-vite-spa/v8/guide/devMode.adoc       | 23 +++++++++
 guides/grails-vite-spa/v8/guide/frontend.adoc      | 29 +++++++++++
 .../grails-vite-spa/v8/guide/gettingStarted.adoc   |  5 ++
 .../grails-vite-spa/v8/guide/helpWithGrails.adoc   |  1 +
 guides/grails-vite-spa/v8/guide/howto.adoc         | 17 +++++++
 guides/grails-vite-spa/v8/guide/layout.adoc        | 23 +++++++++
 guides/grails-vite-spa/v8/guide/prodBuild.adoc     | 21 ++++++++
 guides/grails-vite-spa/v8/guide/requirements.adoc  |  5 ++
 guides/grails-vite-spa/v8/guide/spaController.adoc | 14 ++++++
 guides/grails-vite-spa/v8/guide/urlMappings.adoc   | 12 +++++
 guides/grails-vite-spa/v8/guide/viteConfig.adoc    | 14 ++++++
 .../grails-vite-spa/v8/guide/whatYouWillBuild.adoc | 25 ++++++++++
 .../controllers/example/BookController.groovy      | 14 ++++++
 .../controllers/example/SpaController.groovy       | 15 ++++++
 .../controllers/example/UrlMappings.groovy         | 17 +++++++
 .../backend/grails-app/domain/example/Book.groovy  | 17 +++++++
 .../backend/grails-app/views/book/_book.gson       | 10 ++++
 .../backend/grails-app/views/book/index.gson       | 11 +++++
 guides/grails-vite-spa/v8/snippets/build.gradle    | 57 ++++++++++++++++++++++
 .../v8/snippets/frontend/index.html                | 12 +++++
 .../v8/snippets/frontend/package.json              | 19 ++++++++
 .../v8/snippets/frontend/src/App.jsx               | 40 +++++++++++++++
 .../v8/snippets/frontend/src/main.jsx              | 10 ++++
 .../v8/snippets/frontend/vite.config.js            | 28 +++++++++++
 guides/grails-vite-spa/v8/snippets/settings.gradle | 16 ++++++
 28 files changed, 544 insertions(+)

diff --git a/conf/guides.yml b/conf/guides.yml
index 9a0bcf68f2c..1bd29553894 100644
--- a/conf/guides.yml
+++ b/conf/guides.yml
@@ -4068,6 +4068,55 @@ guides:
           helpWithGrails:
             title: Do you need help with Grails?  
 
+  - name: 'grails-vite-spa'
+    title: 'Vite + React SPA on a Grails 8 Backend'
+    subtitle: 'A Grails 8 rest_api JSON backend plus a Vite/React single-page app frontend in a single Gradle multi-project, packaged into one bootJar with the SPA served from the same origin as the API.'
+    authors:
+      - 'James Fredley'
+    category: 'Web Layer'
+    publicationDate: '2026-05-03'
+    versions:
+      '8':
+        sourcePath: guides/grails-vite-spa/v8
+        publicationDate: '2026-05-03'
+        tags:
+          - 'vite'
+          - 'react'
+          - 'spa'
+          - 'json-views'
+          - 'two-tier'
+          - 'monorepo'
+          - 'grails8'
+        sampleRef:
+          repo: 'grails-guides/grails-vite-spa'
+          branch: 'grails8'
+        toc:
+          gettingStarted:
+            title: Getting Started
+            whatYouWillBuild: What You Will Build
+            requirements: What You Will Need
+            howto: How to Complete the Guide
+          layout:
+            title: Multi-Project Layout
+          backend:
+            title: The Grails 8 JSON Backend
+          urlMappings:
+            title: URL Mappings (/api/** vs SPA)
+          spaController:
+            title: The SpaController Forwarder
+          frontend:
+            title: The Vite/React Frontend
+          viteConfig:
+            title: vite.config.js (Proxy + Build)
+          devMode:
+            title: Dev Mode (Two Servers, One Origin)
+          prodBuild:
+            title: Prod Build (One bootJar, One Origin)
+          cors:
+            title: Why CORS Never Appears
+          helpWithGrails:
+            title: Do you need help with Grails?
+
   - name: 'grails-vs-nodejs'
     title: 'Replacing a Node/Express API with Grails'
     subtitle: 'Learn how to replace a RESTful API in Node/Express with Grails'
diff --git a/guides/grails-vite-spa/v8/guide/backend.adoc b/guides/grails-vite-spa/v8/guide/backend.adoc
new file mode 100644
index 00000000000..4b1a39e15cf
--- /dev/null
+++ b/guides/grails-vite-spa/v8/guide/backend.adoc
@@ -0,0 +1,29 @@
+The backend is a vanilla Grails 8 `rest_api` starter (`postgres`, `testcontainers`, `views-json` features) with a small Book domain and a `RestfulController`:
+
+[source,groovy]
+.backend/grails-app/domain/example/Book.groovy
+----
+include::../snippets/backend/grails-app/domain/example/Book.groovy[]
+----
+
+[source,groovy]
+.backend/grails-app/controllers/example/BookController.groovy
+----
+include::../snippets/backend/grails-app/controllers/example/BookController.groovy[]
+----
+
+The JSON views shape the response:
+
+[source,groovy]
+.backend/grails-app/views/book/_book.gson
+----
+include::../snippets/backend/grails-app/views/book/_book.gson[]
+----
+
+[source,groovy]
+.backend/grails-app/views/book/index.gson
+----
+include::../snippets/backend/grails-app/views/book/index.gson[]
+----
+
+This is exactly the pattern from the link:../grails-rest-library/8/guide/index.html[REST Library] guide, narrowed to a single domain so the Vite-and-React story stays in focus.
diff --git a/guides/grails-vite-spa/v8/guide/cors.adoc b/guides/grails-vite-spa/v8/guide/cors.adoc
new file mode 100644
index 00000000000..527d11b423a
--- /dev/null
+++ b/guides/grails-vite-spa/v8/guide/cors.adoc
@@ -0,0 +1,11 @@
+CORS does not appear in either dev or prod for this layout - and that is the point.
+
+* *In dev*, the browser only ever talks to Vite on `:5173`. Vite forwards `/api/**` to Grails on `:8080` via its server-to-server proxy; the browser never sees a cross-origin request. No CORS preflight, no `Access-Control-Allow-Origin` headers.
+* *In prod*, the browser only ever talks to the bootJar on `:8080`. The SPA's static bundle is served from `/`; the API is served from `/api/**`. Both are the same origin. Same story: no CORS.
+
+For the case where the SPA and the API genuinely live on different origins (e.g. SPA on `app.example.com`, API on `api.example.com`), you would add a `CorsFilter` to the Grails side and configure allowed origins explicitly. The Spring Boot guide on link:https://docs.spring.io/spring-boot/docs/current/reference/html/web.html#web.servlet.spring-mvc.cors[CORS] is the canonical reference; nothing Grails-specific is required.
+
+[NOTE]
+====
+*Auth*: HTTP-only cookie sessions work transparently with this same-origin layout - the browser sends the session cookie on every request without any client-side wiring. JWT in `Authorization` headers is the alternative when the SPA is hosted independently of the API; it requires the SPA to attach the header explicitly on every fetch. The cookie-session path is recommended for browser-only SPAs unless you have a reason to pick JWT.
+====
diff --git a/guides/grails-vite-spa/v8/guide/devMode.adoc b/guides/grails-vite-spa/v8/guide/devMode.adoc
new file mode 100644
index 00000000000..57036f56ef6
--- /dev/null
+++ b/guides/grails-vite-spa/v8/guide/devMode.adoc
@@ -0,0 +1,23 @@
+Dev mode runs both servers in parallel and lets each one own what it is good at:
+
+[source,bash]
+----
+# Shell 1
+./gradlew :backend:bootRun
+# Backend on http://localhost:8080
+# Spring DevTools reloads on Groovy changes
+
+# Shell 2
+cd frontend
+npm install
+npm run dev
+# Vite on http://localhost:5173
+# HMR updates the browser on JSX/CSS changes without losing component state
+----
+
+The browser opens `http://localhost:5173`. Every `fetch('/api/books')` call from the SPA hits Vite first; Vite sees the `/api` prefix in the proxy config and forwards to `http://localhost:8080/api/books`. The response comes back the way it came.
+
+Two things to keep an eye on:
+
+* *Same-origin in dev too.* Because the SPA always calls relative paths and Vite proxies them, the browser never sees a cross-origin request. CORS preflight requests do not happen even in dev.
+* *Spring DevTools for the backend, Vite HMR for the frontend.* Each side reloads independently; you can edit `App.jsx` without restarting Grails, and edit a Groovy controller without losing your SPA state.
diff --git a/guides/grails-vite-spa/v8/guide/frontend.adoc b/guides/grails-vite-spa/v8/guide/frontend.adoc
new file mode 100644
index 00000000000..8534cfafd24
--- /dev/null
+++ b/guides/grails-vite-spa/v8/guide/frontend.adoc
@@ -0,0 +1,29 @@
+The frontend is a stock `npm create vite@latest -- --template react` scaffold, simplified:
+
+[source,json]
+.frontend/package.json
+----
+include::../snippets/frontend/package.json[]
+----
+
+[source,html]
+.frontend/index.html
+----
+include::../snippets/frontend/index.html[]
+----
+
+[source,jsx]
+.frontend/src/main.jsx
+----
+include::../snippets/frontend/src/main.jsx[]
+----
+
+[source,jsx]
+.frontend/src/App.jsx
+----
+include::../snippets/frontend/src/App.jsx[]
+----
+
+The single `fetch('/api/books')` call is the only contract between the two halves. The relative path means the same code runs in dev (where Vite proxies to `:8080`) and in prod (where the SPA is served from the bootJar at `:8080` already).
+
+To use Vue 3 instead of React, swap the dependency to `vue` + `@vitejs/plugin-vue` and replace `App.jsx` with an `App.vue` single-file component. The Gradle wiring, Vite proxy, and backend never change.
diff --git a/guides/grails-vite-spa/v8/guide/gettingStarted.adoc b/guides/grails-vite-spa/v8/guide/gettingStarted.adoc
new file mode 100644
index 00000000000..52f0f417f39
--- /dev/null
+++ b/guides/grails-vite-spa/v8/guide/gettingStarted.adoc
@@ -0,0 +1,5 @@
+In this guide you will build a two-tier application: an Apache Grails 8 `rest_api` backend that exposes JSON over `/api/**`, plus a link:https://vitejs.dev[Vite] + link:https://react.dev[React] single-page app that consumes it. Both halves live in one Gradle multi-project build and ship as a single `bootJar` so the SPA serves from the same origin as the API in production - no CORS, no two-deployment dance.
+
+This guide replaces the long-broken Webpack-era `react` and `vue` profiles with a modern Vite-based pipeline. The pattern works identically for Vue 3 (substitute `@vitejs/plugin-vue` for `@vitejs/plugin-react` and an equivalent `App.vue`).
+
+This guide targets Apache Grails 8 / Spring Boot 4 / Vite 5 / Node 20+.
diff --git a/guides/grails-vite-spa/v8/guide/helpWithGrails.adoc b/guides/grails-vite-spa/v8/guide/helpWithGrails.adoc
new file mode 100644
index 00000000000..e062f614b1a
--- /dev/null
+++ b/guides/grails-vite-spa/v8/guide/helpWithGrails.adoc
@@ -0,0 +1 @@
+include::{commondir}/common-helpWithGrails.adoc[]
diff --git a/guides/grails-vite-spa/v8/guide/howto.adoc b/guides/grails-vite-spa/v8/guide/howto.adoc
new file mode 100644
index 00000000000..fa3e9ca2a21
--- /dev/null
+++ b/guides/grails-vite-spa/v8/guide/howto.adoc
@@ -0,0 +1,17 @@
+Clone the finished sample and run it:
+
+[source,bash]
+----
+git clone -b grails8 https://github.com/grails-guides/grails-vite-spa.git
+cd grails-vite-spa/complete
+
+# Dev (two shells):
+./gradlew :backend:bootRun                  # http://localhost:8080
+cd frontend && npm install && npm run dev   # http://localhost:5173
+
+# Prod (one bootJar packages both halves):
+./gradlew :backend:bootJar
+java -jar backend/build/libs/backend-0.1.jar  # http://localhost:8080
+----
+
+`initial/` contains just the vanilla Grails 8 `rest_api` starter. `complete/` is the assembled two-tier setup this guide builds.
diff --git a/guides/grails-vite-spa/v8/guide/layout.adoc b/guides/grails-vite-spa/v8/guide/layout.adoc
new file mode 100644
index 00000000000..2f08b7f7d11
--- /dev/null
+++ b/guides/grails-vite-spa/v8/guide/layout.adoc
@@ -0,0 +1,23 @@
+A root `settings.gradle` includes only the backend; the frontend is a plain npm directory:
+
+[source,groovy]
+.settings.gradle
+----
+include::../snippets/settings.gradle[]
+----
+
+The two-shell-of-control choice is deliberate. Making `frontend` a Gradle subproject would force you to find or write a Vite Gradle plugin, deal with version drift, and introduce a layer that adds nothing the npm CLI does not already do. Letting Gradle drive `npm` via `Exec` tasks keeps each tool in its lane and lets you `cd frontend && npm install` exactly the way every JS dev expects.
+
+The root `build.gradle` adds three tasks that bridge the two halves:
+
+[source,groovy]
+.build.gradle
+----
+include::../snippets/build.gradle[]
+----
+
+Three patterns:
+
+* `npmInstall` -> `frontendBuild` -> `copyFrontendToBackend` is a chain. Each task declares its `inputs`/`outputs` so Gradle's up-to-date check skips the chain when nothing has changed.
+* `copyFrontendToBackend` writes into `backend/src/main/resources/public/`. Spring Boot serves anything under that directory at `/` automatically; no further wiring needed.
+* The `afterEvaluate { tasks.named('processResources').configure { dependsOn ... } }` line is what makes plain `./gradlew :backend:bootJar` (or `bootRun`) trigger the SPA build. Readers never type the frontend tasks directly.
diff --git a/guides/grails-vite-spa/v8/guide/prodBuild.adoc b/guides/grails-vite-spa/v8/guide/prodBuild.adoc
new file mode 100644
index 00000000000..7fcdcf5f31f
--- /dev/null
+++ b/guides/grails-vite-spa/v8/guide/prodBuild.adoc
@@ -0,0 +1,21 @@
+Production packaging is one Gradle command:
+
+[source,bash]
+----
+./gradlew :backend:bootJar
+----
+
+Behind the scenes, that command:
+
+1. `:npmInstall` runs `npm install` in `frontend/` (skipped if `node_modules/` is up-to-date).
+2. `:frontendBuild` runs `npm run build`, which is `vite build`, which produces `frontend/dist/index.html` plus a hashed JS+CSS bundle in `frontend/dist/assets/`.
+3. `:copyFrontendToBackend` copies `frontend/dist/*` into `backend/src/main/resources/public/`.
+4. `:backend:processResources` (which `:backend:bootJar` depends on) picks up the new `public/` tree and includes it in the bootJar.
+5. `:backend:bootJar` writes `backend/build/libs/backend-0.1.jar`.
+
+The resulting jar serves the SPA from `/` and the API from `/api/**`, both from the same origin. CORS is a non-issue. The deployment artifact is one file.
+
+[TIP]
+====
+The matching link:../grails-docker-bootbuildimage/8/guide/index.html[Docker bootBuildImage] guide turns this exact bootJar into an OCI image. Combined, the two guides give you `git push` -> tagged GHCR image -> single-container deploy.
+====
diff --git a/guides/grails-vite-spa/v8/guide/requirements.adoc b/guides/grails-vite-spa/v8/guide/requirements.adoc
new file mode 100644
index 00000000000..81bc103ec36
--- /dev/null
+++ b/guides/grails-vite-spa/v8/guide/requirements.adoc
@@ -0,0 +1,5 @@
+To complete this guide you will need:
+
+* JDK 21
+* link:https://nodejs.org[Node.js] 20+ and a recent npm
+* About 45 minutes
diff --git a/guides/grails-vite-spa/v8/guide/spaController.adoc b/guides/grails-vite-spa/v8/guide/spaController.adoc
new file mode 100644
index 00000000000..86b2bdfdde1
--- /dev/null
+++ b/guides/grails-vite-spa/v8/guide/spaController.adoc
@@ -0,0 +1,14 @@
+The `SpaController` is one action that hands every non-`/api/**` request to the SPA's bundled `index.html`:
+
+[source,groovy]
+.backend/grails-app/controllers/example/SpaController.groovy
+----
+include::../snippets/backend/grails-app/controllers/example/SpaController.groovy[]
+----
+
+`forward url: '/index.html'` re-dispatches inside the same servlet container; the response status, content type, and caching headers all come from the static-resource handler that serves `index.html`. No HTML duplication, no template engine in the loop.
+
+[NOTE]
+====
+*Why not a wildcard URL mapping like `'/$path**'(controller: 'spa', action: 'index')`?* Because URL mappings resolve before static resources. A wildcard mapping would intercept `/favicon.ico` and `/assets/main-abc123.js`, returning the SPA's `index.html` instead of the asset. Letting Spring Boot's static-resource handler claim everything except `/api/**` and `/` is the simplest correct shape.
+====
diff --git a/guides/grails-vite-spa/v8/guide/urlMappings.adoc b/guides/grails-vite-spa/v8/guide/urlMappings.adoc
new file mode 100644
index 00000000000..5960a728685
--- /dev/null
+++ b/guides/grails-vite-spa/v8/guide/urlMappings.adoc
@@ -0,0 +1,12 @@
+URL mappings split the application surface in two:
+
+[source,groovy]
+.backend/grails-app/controllers/example/UrlMappings.groovy
+----
+include::../snippets/backend/grails-app/controllers/example/UrlMappings.groovy[]
+----
+
+* `/api/books` (and any other future `/api/**` route) hits the JSON controllers.
+* Everything else - `/`, `/books/42`, `/about` - resolves to `SpaController.index`, which forwards to the bundled `index.html`. The SPA's client-side router takes over from there.
+
+The forward (rather than a redirect) is what makes deep links survive a browser refresh: a hard reload on `/books/42` returns the same `index.html` payload, the SPA boots, and React Router parses the URL.
diff --git a/guides/grails-vite-spa/v8/guide/viteConfig.adoc b/guides/grails-vite-spa/v8/guide/viteConfig.adoc
new file mode 100644
index 00000000000..f695d3e0602
--- /dev/null
+++ b/guides/grails-vite-spa/v8/guide/viteConfig.adoc
@@ -0,0 +1,14 @@
+`vite.config.js` is the bridge between dev and prod:
+
+[source,javascript]
+.frontend/vite.config.js
+----
+include::../snippets/frontend/vite.config.js[]
+----
+
+Two pieces are doing the work:
+
+* `server.proxy['/api']` is the dev-mode connector. Vite's dev server runs on `:5173`; any request the SPA makes to `/api/**` is transparently forwarded to the Grails app on `:8080`. The SPA never knows there are two ports - `fetch('/api/books')` Just Works. `changeOrigin: true` rewrites the `Host` header so the Grails side sees a same-origin request.
+* `build.outDir = 'dist'` controls where `npm run build` writes the static bundle. Our root `build.gradle`'s `copyFrontendToBackend` task reads from this exact path.
+
+`emptyOutDir: true` makes a clean rebuild every time, so a renamed asset does not leave a stale predecessor in `dist/`.
diff --git a/guides/grails-vite-spa/v8/guide/whatYouWillBuild.adoc b/guides/grails-vite-spa/v8/guide/whatYouWillBuild.adoc
new file mode 100644
index 00000000000..8be6550058e
--- /dev/null
+++ b/guides/grails-vite-spa/v8/guide/whatYouWillBuild.adoc
@@ -0,0 +1,25 @@
+By the end of the guide your repository will look like:
+
+[source,text]
+----
+grails-vite-spa/
+|-- settings.gradle              # include ':backend' (frontend is npm-only)
+|-- build.gradle                 # npmInstall, frontendBuild, copyFrontendToBackend
+|-- backend/                     # Grails 8 rest_api
+|   `-- grails-app/
+|       |-- domain/example/Book.groovy
+|       |-- controllers/example/BookController.groovy        # /api/books
+|       |-- controllers/example/SpaController.groovy         # forwards / -> SPA
+|       |-- controllers/example/UrlMappings.groovy
+|       `-- views/book/{_book,index,show}.gson
+`-- frontend/                    # Vite + React (NOT a Gradle subproject)
+    |-- package.json
+    |-- vite.config.js           # proxy /api/** -> http://localhost:8080
+    |-- index.html
+    `-- src/{main.jsx, App.jsx, index.css}
+----
+
+Two run-modes:
+
+* *Dev*: `./gradlew :backend:bootRun` in one shell, `cd frontend && npm run dev` in another. Vite serves the SPA on `:5173` with HMR; the proxy forwards `/api/**` to the Grails app on `:8080`.
+* *Prod*: `./gradlew :backend:bootJar`. Gradle runs `npm run build`, copies `frontend/dist/` into `backend/src/main/resources/public/`, and packages everything into one bootJar. The SPA serves from `/` and `/api/**` from the same origin - CORS irrelevant.
diff --git a/guides/grails-vite-spa/v8/snippets/backend/grails-app/controllers/example/BookController.groovy b/guides/grails-vite-spa/v8/snippets/backend/grails-app/controllers/example/BookController.groovy
new file mode 100644
index 00000000000..8f7137b7c4c
--- /dev/null
+++ b/guides/grails-vite-spa/v8/snippets/backend/grails-app/controllers/example/BookController.groovy
@@ -0,0 +1,14 @@
+package example
+
+import grails.rest.RestfulController
+
+class BookController extends RestfulController<Book> {
+    static responseFormats = ['json']
+    BookController() { super(Book) }
+
+    @Override
+    protected List<Book> listAllResources(Map params) {
+        params.max = Math.min(params.int('max', 25), 100)
+        Book.list(params)
+    }
+}
diff --git a/guides/grails-vite-spa/v8/snippets/backend/grails-app/controllers/example/SpaController.groovy b/guides/grails-vite-spa/v8/snippets/backend/grails-app/controllers/example/SpaController.groovy
new file mode 100644
index 00000000000..290e190891f
--- /dev/null
+++ b/guides/grails-vite-spa/v8/snippets/backend/grails-app/controllers/example/SpaController.groovy
@@ -0,0 +1,15 @@
+package example
+
+class SpaController {
+    static responseFormats = ['html']
+
+    /**
+     * Forwards any non-/api request to the SPA's bundled index.html
+     * (which Vite produced into src/main/resources/public/index.html).
+     * Spring Boot auto-serves that file at /; we forward here so client-
+     * side routes like /books/42 survive a browser refresh.
+     */
+    def index() {
+        forward url: '/index.html'
+    }
+}
diff --git a/guides/grails-vite-spa/v8/snippets/backend/grails-app/controllers/example/UrlMappings.groovy b/guides/grails-vite-spa/v8/snippets/backend/grails-app/controllers/example/UrlMappings.groovy
new file mode 100644
index 00000000000..939288ea6b4
--- /dev/null
+++ b/guides/grails-vite-spa/v8/snippets/backend/grails-app/controllers/example/UrlMappings.groovy
@@ -0,0 +1,17 @@
+package example
+
+class UrlMappings {
+
+    static mappings = {
+
+        // SPA routes resolved here so client-side routing survives
+        // a hard reload to any deep link.
+        '/' (controller: 'spa', action: 'index')
+
+        // JSON API surface consumed by the Vite/React frontend.
+        '/api/books'(resources: 'book')
+
+        '500'(view: '/error')
+        '404'(view: '/notFound')
+    }
+}
diff --git a/guides/grails-vite-spa/v8/snippets/backend/grails-app/domain/example/Book.groovy b/guides/grails-vite-spa/v8/snippets/backend/grails-app/domain/example/Book.groovy
new file mode 100644
index 00000000000..f96d1e5080b
--- /dev/null
+++ b/guides/grails-vite-spa/v8/snippets/backend/grails-app/domain/example/Book.groovy
@@ -0,0 +1,17 @@
+package example
+
+import grails.persistence.Entity
+
+@Entity
+class Book {
+
+    String  title
+    String  author
+    String  isbn
+
+    static constraints = {
+        title  blank: false, maxSize: 255
+        author blank: false, maxSize: 255
+        isbn   blank: false, unique: true, matches: /^(97(8|9))?\d{9}(\d|X)$/
+    }
+}
diff --git a/guides/grails-vite-spa/v8/snippets/backend/grails-app/views/book/_book.gson b/guides/grails-vite-spa/v8/snippets/backend/grails-app/views/book/_book.gson
new file mode 100644
index 00000000000..f3e36fbac09
--- /dev/null
+++ b/guides/grails-vite-spa/v8/snippets/backend/grails-app/views/book/_book.gson
@@ -0,0 +1,10 @@
+import example.Book
+
+model { Book book }
+
+json {
+    id     book.id
+    title  book.title
+    author book.author
+    isbn   book.isbn
+}
diff --git a/guides/grails-vite-spa/v8/snippets/backend/grails-app/views/book/index.gson b/guides/grails-vite-spa/v8/snippets/backend/grails-app/views/book/index.gson
new file mode 100644
index 00000000000..fab1f823029
--- /dev/null
+++ b/guides/grails-vite-spa/v8/snippets/backend/grails-app/views/book/index.gson
@@ -0,0 +1,11 @@
+import example.Book
+
+model {
+    Iterable<Book> bookList
+    Long           bookCount
+}
+
+json {
+    total   bookCount
+    items   bookList.collect { Book b -> g.render(template: 'book', model: [book: b]) }
+}
diff --git a/guides/grails-vite-spa/v8/snippets/build.gradle b/guides/grails-vite-spa/v8/snippets/build.gradle
new file mode 100644
index 00000000000..379bf313dea
--- /dev/null
+++ b/guides/grails-vite-spa/v8/snippets/build.gradle
@@ -0,0 +1,57 @@
+/*
+ * Root build script.
+ *
+ * The frontend module is NOT a Gradle subproject - it lives as a plain
+ * npm directory at frontend/ with its own package.json. Three Gradle
+ * tasks bridge the two halves:
+ *
+ *   npmInstall              -> npm install in frontend/
+ *   frontendBuild           -> npm run build (writes frontend/dist/)
+ *   copyFrontendToBackend   -> copies dist/ into backend/src/main/
+ *                              resources/public/ so bootJar packages it
+ *
+ * The backend's processResources task depends on copyFrontendToBackend
+ * so a plain `./gradlew :backend:bootJar` (or :backend:bootRun) builds
+ * the SPA and copies it into the right place automatically.
+ */
+
+def npxCmd = org.gradle.internal.os.OperatingSystem.current().isWindows() ? 'npx.cmd' : 'npx'
+def npmCmd = org.gradle.internal.os.OperatingSystem.current().isWindows() ? 'npm.cmd' : 'npm'
+
+// tag::frontendTasks[]
+tasks.register('npmInstall', Exec) {
+    description = 'Install npm dependencies for the frontend SPA'
+    group = 'frontend'
+    workingDir = file('frontend')
+    inputs.file('frontend/package.json')
+    outputs.dir('frontend/node_modules')
+    commandLine npmCmd, 'install', '--no-fund', '--no-audit'
+}
+
+tasks.register('frontendBuild', Exec) {
+    description = 'Build the Vite/React SPA into frontend/dist/'
+    group = 'frontend'
+    dependsOn 'npmInstall'
+    workingDir = file('frontend')
+    inputs.dir('frontend/src')
+    inputs.file('frontend/index.html')
+    inputs.file('frontend/vite.config.js')
+    inputs.file('frontend/package.json')
+    outputs.dir('frontend/dist')
+    commandLine npmCmd, 'run', 'build'
+}
+
+tasks.register('copyFrontendToBackend', Copy) {
+    description = 'Copy the built SPA into backend/src/main/resources/public/'
+    group = 'frontend'
+    dependsOn 'frontendBuild'
+    from file('frontend/dist')
+    into file('backend/src/main/resources/public')
+}
+// end::frontendTasks[]
+
+project(':backend') {
+    afterEvaluate {
+        tasks.named('processResources').configure { dependsOn rootProject.tasks.named('copyFrontendToBackend') }
+    }
+}
diff --git a/guides/grails-vite-spa/v8/snippets/frontend/index.html b/guides/grails-vite-spa/v8/snippets/frontend/index.html
new file mode 100644
index 00000000000..33f1afbda99
--- /dev/null
+++ b/guides/grails-vite-spa/v8/snippets/frontend/index.html
@@ -0,0 +1,12 @@
+<!doctype html>
+<html lang="en">
+  <head>
+    <meta charset="UTF-8"/>
+    <meta name="viewport" content="width=device-width, initial-scale=1"/>
+    <title>Grails + Vite + React</title>
+  </head>
+  <body>
+    <div id="root"></div>
+    <script type="module" src="/src/main.jsx"></script>
+  </body>
+</html>
diff --git a/guides/grails-vite-spa/v8/snippets/frontend/package.json b/guides/grails-vite-spa/v8/snippets/frontend/package.json
new file mode 100644
index 00000000000..689f291e40b
--- /dev/null
+++ b/guides/grails-vite-spa/v8/snippets/frontend/package.json
@@ -0,0 +1,19 @@
+{
+  "name": "grails-vite-spa-frontend",
+  "version": "1.0.0",
+  "private": true,
+  "type": "module",
+  "scripts": {
+    "dev": "vite",
+    "build": "vite build",
+    "preview": "vite preview"
+  },
+  "dependencies": {
+    "react": "^18.3.1",
+    "react-dom": "^18.3.1"
+  },
+  "devDependencies": {
+    "@vitejs/plugin-react": "^4.3.0",
+    "vite": "^5.4.0"
+  }
+}
diff --git a/guides/grails-vite-spa/v8/snippets/frontend/src/App.jsx b/guides/grails-vite-spa/v8/snippets/frontend/src/App.jsx
new file mode 100644
index 00000000000..c5929c99574
--- /dev/null
+++ b/guides/grails-vite-spa/v8/snippets/frontend/src/App.jsx
@@ -0,0 +1,40 @@
+import { useEffect, useState } from 'react'
+
+/**
+ * Single-screen SPA: lists books from the Grails backend's /api/books
+ * and lets the user add a new one.
+ *
+ * fetch('/api/books') resolves through the Vite proxy in dev and
+ * directly (same-origin) from the bundled SPA in prod.
+ */
+export default function App() {
+  const [books, setBooks] = useState([])
+  const [loading, setLoading] = useState(true)
+  const [error, setError] = useState(null)
+
+  useEffect(() => {
+    fetch('/api/books')
+      .then((r) => (r.ok ? r.json() : Promise.reject(r.statusText)))
+      .then((data) => setBooks(data.items || []))
+      .catch((e) => setError(String(e)))
+      .finally(() => setLoading(false))
+  }, [])
+
+  return (
+    <main className="container">
+      <h1>Library</h1>
+      {loading && <p>Loading...</p>}
+      {error && <p className="error">Error: {error}</p>}
+      {!loading && !error && (
+        <ul>
+          {books.map((b) => (
+            <li key={b.id}>
+              <strong>{b.title}</strong> by {b.author} ({b.isbn})
+            </li>
+          ))}
+          {books.length === 0 && <li>No books yet.</li>}
+        </ul>
+      )}
+    </main>
+  )
+}
diff --git a/guides/grails-vite-spa/v8/snippets/frontend/src/main.jsx b/guides/grails-vite-spa/v8/snippets/frontend/src/main.jsx
new file mode 100644
index 00000000000..89f91e54dc6
--- /dev/null
+++ b/guides/grails-vite-spa/v8/snippets/frontend/src/main.jsx
@@ -0,0 +1,10 @@
+import { StrictMode } from 'react'
+import { createRoot } from 'react-dom/client'
+import App from './App.jsx'
+import './index.css'
+
+createRoot(document.getElementById('root')).render(
+  <StrictMode>
+    <App />
+  </StrictMode>,
+)
diff --git a/guides/grails-vite-spa/v8/snippets/frontend/vite.config.js b/guides/grails-vite-spa/v8/snippets/frontend/vite.config.js
new file mode 100644
index 00000000000..b1fe8b822b0
--- /dev/null
+++ b/guides/grails-vite-spa/v8/snippets/frontend/vite.config.js
@@ -0,0 +1,28 @@
+import { defineConfig } from 'vite'
+import react from '@vitejs/plugin-react'
+
+/**
+ * In dev: `npm run dev` starts Vite on :5173 with HMR.
+ *   - Requests to /api/** get proxied to the Grails backend on :8080,
+ *     so the SPA can fetch('/api/books') without dealing with CORS.
+ * In prod: `npm run build` writes a static bundle to ./dist/.
+ *   - The root build.gradle copies dist/ into
+ *     backend/src/main/resources/public/ so Spring Boot serves the
+ *     SPA from the same origin as the API. Still no CORS.
+ */
+export default defineConfig({
+  plugins: [react()],
+  server: {
+    port: 5173,
+    proxy: {
+      '/api': {
+        target: 'http://localhost:8080',
+        changeOrigin: true,
+      },
+    },
+  },
+  build: {
+    outDir: 'dist',
+    emptyOutDir: true,
+  },
+})
diff --git a/guides/grails-vite-spa/v8/snippets/settings.gradle b/guides/grails-vite-spa/v8/snippets/settings.gradle
new file mode 100644
index 00000000000..0b49a24797a
--- /dev/null
+++ b/guides/grails-vite-spa/v8/snippets/settings.gradle
@@ -0,0 +1,16 @@
+/*
+ * Two-tier multi-project build.
+ *
+ *   backend/    Grails 8 rest_api - JSON over /api/**
+ *   frontend/   Vite + React - NOT a Gradle subproject; driven by npm
+ *               via the npmInstall + frontendBuild + copyFrontendToBackend
+ *               tasks in the root build.gradle.
+ *
+ * A single bootJar produced by `./gradlew :backend:bootJar` ships both
+ * halves: the SPA's static bundle is copied into backend/src/main/
+ * resources/public/ before bootJar packages it.
+ */
+
+rootProject.name = 'grails-vite-spa'
+
+include ':backend'