Colmena Bookings is an SPA (Single Page Application): the server sends an index.html with an empty <div id="app"> and some JavaScript files, and it is the browser that runs Vue, requests the data and renders the interface. For an internal tool with a sign-in, it is the right choice. But the coworking space also needs a public website: a home page and a room catalogue that anyone can find in a search engine, share on a social network and see instantly from a phone with a poor connection. For that, the HTML must arrive already rendered from the server. In this lesson you will compare rendering strategies (CSR, SSR, SSG and the hybrid ones), understand hydration and its mismatches, learn what code cannot run on the server, and decide why Colmena Bookings remains an SPA while the public website does not. Then you will create a second project, colmena-web, with Nuxt, the go-to framework for SSR with Vue: file-based routing, layouts, auto-imports, data fetching with useFetch, server routes that serve the catalogue, SEO with useSeoMeta and per-route rendering rules.

Contents

  1. Rendering strategies
  2. Hydration
  3. Hydration mismatches
  4. Universal code: what cannot be done on the server
  5. SPA or SSR? The decision in Colmena
  6. Nuxt: creating colmena-web
  7. The structure of a Nuxt project
  8. File-based routing
  9. Layouts
  10. Auto-importing components and composables
  11. Server routes: the catalogue API
  12. Data fetching: useFetch and useAsyncData
  13. SEO with useSeoMeta and useHead
  14. Per-route rendering rules: routeRules
  15. State, Pinia and internationalisation in Nuxt
  16. Building and generating
  17. Try it

  1. Rendering strategies

The underlying question is: who turns the components into HTML, and when?

Strategy Who generates the HTML When Example
CSR (Client-Side Rendering) The browser, with JavaScript On every visit, after downloading and running the code Colmena Bookings
SSR (Server-Side Rendering) The server, with Node On every request A room's spec sheet with prices that change often
SSG (Static Site Generation), or prerendering The server... just once When the application is built The public website's home page
ISR / hybrid The server, with a cache On the first request, and it is regenerated every so often or on demand The room catalogue, which changes from time to time

Their consequences, compared:

CSR SSR SSG Hybrid (SSR + cache)
SEO Worse: the initial HTML is empty; the main search engines run JavaScript, but with a delay and with limits, and social networks do not Excellent Excellent Excellent
First paint (FCP, LCP) Slow: download the JS, run it, request the data, render Fast: the HTML arrives with the content The fastest: a static file from a CDN Fast (from the cache)
Interactivity When the JS runs When it is hydrated (section 2) When it is hydrated When it is hydrated
Server cost Minimal: static files High: Node does work on every request Minimal at runtime; the build takes longer if there are many pages Medium
Fresh data Always (it is requested in the browser) Always Only as of build time With a controlled delay
Complexity Low High: universal code, a server to maintain Medium Medium-high
Suitable for Applications with a session, dashboards, internal tools Public content that changes frequently or per user Stable public content: home pages, documentation, blogs Catalogues, shops

It is not a choice for the whole application: modern frameworks let you choose per route, as we will do in section 14.

  1. Hydration

With SSR, the server runs the Vue components, obtains the HTML and sends it. The browser displays it immediately, but that HTML is inert: the buttons do not respond, because there is no Vue listening. For the page to become interactive, the browser downloads the same application code and runs it, and Vue, instead of creating the DOM from scratch, adopts the one that already exists: it walks through the server's HTML, checks that it matches what it would have rendered and attaches the event listeners and reactivity to it. This process is called hydration.

sequenceDiagram
    participant N as Browser
    participant S as Server (Node)
    N->>S: GET /rooms/nectar
    S->>S: Runs the components' setup and requests the data
    S->>S: Renders to HTML (renderToString)
    S-->>N: Complete HTML + serialised state (payload) + links to the JS
    Note over N: The user can ALREADY see the Néctar Room's spec sheet (not interactive)
    N->>S: Downloads the JS files
    N->>N: Runs the application with the state received (without requesting the data again)
    N->>N: Hydrates: walks through the existing DOM and attaches events and reactivity
    Note over N: Now the page is interactive
    N->>N: From here on, it behaves like an SPA (client-side navigation)

Three key ideas:

  • The code runs twice: on the server to produce the HTML, and in the browser to hydrate it. That is why it is called universal (or isomorphic) code.
  • The state travels with the HTML: the data the server obtained is serialised into the page (the payload), so that the browser does not have to request it again and renders exactly the same thing.
  • After hydration, it is an SPA: when an internal link is clicked, the next page is rendered in the browser, without requesting HTML from the server again.

  1. Hydration mismatches

During hydration, Vue expects the server's DOM to match exactly what the client renders. If it does not, there is a hydration mismatch: Vue warns in the development console ("Hydration text content mismatch...") and corrects the DOM, which can cause flickering, duplicated elements or listeners attached to the wrong element.

The typical causes, and how to avoid them:

Cause Example Why it fails Solution
Dates and times "from now" {{ new Date().toLocaleTimeString() }}, the reception clock The server renders at 10:00:01; the browser hydrates at 10:00:03 Show it only on the client (<ClientOnly>, or assign it in onMounted)
Time zone and language date.toLocaleDateString() without options The server is in UTC and in English; the user is in Madrid and uses Spanish Format with Intl, specifying an explicit timeZone and locale
Random values :id="Math.random()", crypto.randomUUID() in the template Each run gives a different value useId() (stable between server and client) or generate the value on the server and transfer it with the state
Browser APIs window.innerWidth, localStorage.getItem(...) in setup They do not exist on the server (an error) or give a different value Read them in onMounted, which only runs in the browser
Invalid HTML A <div> inside a <p>, a <table> without a <tbody> The browser "fixes" the HTML when parsing it and the DOM no longer matches Write valid HTML
Content that depends on the user "Hello, Laura" based on a cookie that only the client reads The server does not know who they are Read the cookie on the server too, or render it only on the client

In Nuxt, the <ClientOnly> component renders its content only in the browser, after hydration; on the server it renders its #fallback slot (or nothing):

<ClientOnly>
  <ColmenaClock />
  <template #fallback>
    <span class="clock">--:--</span>
  </template>
</ClientOnly>

And if a difference is expected and harmless (a timestamp in a footer), Vue 3.5 lets you mark the element with the data-allow-mismatch attribute (for example, data-allow-mismatch="text") so that it does not warn. Use it sparingly: the warnings exist to catch bugs.

  1. Universal code: what cannot be done on the server

On the server, Vue runs setup and the render, but it does not mount anything into a real DOM. That changes the rules:

On the server... Consequence What to do
There is no window, document, localStorage or navigator Accessing them in setup or at module level throws a ReferenceError Use them in onMounted or check import.meta.client (in Nuxt)
onMounted, onUpdated and onUnmounted do not run Whatever you put there only happens in the browser That is exactly where code that needs the browser should go
Timers in setup are never cleaned up A setInterval in setup stays alive on the server forever: one leak per request Create timers in onMounted and clean them up in onUnmounted
Reactivity has nobody to notify watches have no useful effect after rendering Fetch the data before rendering (useFetch)
A single process serves every user Module state (a ref outside a component, 09-01) is shared between requests from different users Per-request state: useState or a Pinia store (section 15)
Custom directives have no element The mounted hook of v-focus does not run For them to generate attributes in the server's HTML there is the getSSRProps hook (06-02)

The penultimate point is the most dangerous, because it gives no error at all: it works perfectly in development, with a single user, and in production it makes one visitor see data that belonged to another. It is the ultimate reason why in 09-01 we recommended stores over module state.

If you go through Colmena Bookings with this table, you will see why it would not work with SSR as it is: ReceptionClock creates its interval in onMounted (good), but src/i18n.js reads localStorage and navigator.languages when deciding the initial language, the Pinia persistence plugin reads localStorage and sessionStorage, BaseModal uses document.body... Every piece would have to be reviewed. An application designed from the outset for SSR avoids those accesses or isolates them.

  1. SPA or SSR? The decision in Colmena

Criterion Colmena Bookings (internal application) The coworking space's public website
Who uses it? Members who are signed in Anyone: future customers
Must it appear in search engines? No: it is behind a sign-in Yes: it is its raison d'être
Is it shared on social networks? No Yes: it needs a title, a description and an image in the HTML
First paint It is loaded once and used for hours Every visit may be the first and only one
Data Personal and changing (bookings, session) Public and stable (the catalogue)
Infrastructure Static files on any server or CDN A Node server (or serverless functions) for SSR
Decision SPA with Vite (what we already have) SSR / hybrid with Nuxt

That is why we will not convert Colmena Bookings: we will create a second project, colmena-web, with the public home page and catalogue. To book, the website will link to the SPA. It is a common architecture: the public part optimised for discovery and the application optimised for work.

  1. Nuxt: creating colmena-web

Nuxt is the go-to application framework built on Vue. It adds to Vue what is needed for SSR and more: a server (Nitro) that renders the pages and serves an API, file-based routing on top of Vue Router, auto-imports, data fetching that works on both server and client, <head> management, and per-route rendering rules. What you already know about Vue (components, <script setup>, reactivity, composables) applies unchanged.

Create the project outside the Colmena Bookings folder, next to it:

npm create nuxt@latest colmena-web

The scaffolding tool asks which template to use (choose the minimal one), the package manager (npm), whether you want to initialise a Git repository and whether you want to add official modules (none for now). Nuxt requires a recent LTS version of Node: if the tool warns that yours is not compatible, upgrade it with nvm (01-02). Then:

cd colmena-web
npm run dev

The development server starts at http://localhost:3000 (Vite is still serving Colmena Bookings on 5173, so you can have both running). The scripts in package.json:

Script Command What it does
dev nuxt dev Development server with SSR and hot reloading
build nuxt build Builds the application with its server for production (section 16)
generate nuxt generate Prerenders every route as static files
preview nuxt preview Serves the result of build locally
postinstall nuxt prepare Generates the types and the .nuxt folder after installing

  1. The structure of a Nuxt project

Current versions of Nuxt (since Nuxt 4) separate the application's code, in app/, from the server's code, in server/. This is what colmena-web will look like at the end of the lesson:

colmena-web/
├── app/                         ← the Vue application (runs on server and browser)
│   ├── app.vue                  ← root component
│   ├── layouts/
│   │   └── default.vue          ← common frame: header and footer
│   ├── pages/                   ← each file is a route
│   │   ├── index.vue            ← /
│   │   └── rooms/
│   │       ├── index.vue        ← /rooms
│   │       └── [id].vue         ← /rooms/:id
│   ├── components/              ← auto-imported
│   │   ├── ColmenaClock.vue
│   │   └── PublicRoomCard.vue
│   └── composables/             ← auto-imported
│       ├── useRoomFilters.js
│       └── usePrice.js
├── server/                      ← server only (Nitro): it never reaches the browser
│   ├── api/
│   │   ├── rooms.get.js         ← GET /api/rooms
│   │   └── rooms/
│   │       └── [id].get.js      ← GET /api/rooms/:id
│   └── data/
│       └── rooms.js
├── public/                      ← static files as they are (favicon, robots.txt, images)
├── nuxt.config.ts               ← configuration
├── .nuxt/                       ← generated in development (not edited or versioned)
└── .output/                     ← generated on building (not versioned)
Folder Content Equivalent in Colmena Bookings
app/pages/ Routes, by file name src/views/ + src/router/index.js
app/layouts/ Page frames App.vue with the header and <RouterView>
app/components/ Components, with no need to import them src/components/
app/composables/ Composables, with no need to import them src/composables/
app/plugins/, app/middleware/ Vue plugins and navigation guards main.js, the router's guards
server/ API and server logic src/api/ (there, simulated in the browser)
shared/ Code common to the application and the server (utilities, types) Does not exist
nuxt.config.ts Configuration vite.config.js + main.js

  1. File-based routing

In Nuxt you do not write a src/router/index.js: each file in app/pages/ is a route, and the folder structure is the URL structure.

File Route Equivalent in Vue Router
pages/index.vue / { path: '/' }
pages/rooms/index.vue /rooms { path: '/rooms' }
pages/rooms/[id].vue /rooms/:id { path: '/rooms/:id' } (04-03)
pages/[...path].vue Anything else { path: '/:pathMatch(.*)*' }
pages/dashboard.vue + pages/dashboard/profile.vue /dashboard with the child /dashboard/profile Nested routes (04-04)

Under the hood, Nuxt generates Vue Router routes: useRoute(), useRouter(), params, the query and guards work as you already know. What changes is the component for linking: <NuxtLink>, which wraps <RouterLink> and also prefetches the code (and the data) of the linked page when the link appears on screen, so that navigation is instantaneous.

The root component, app/app.vue, renders the layout and, inside it, the current page with <NuxtPage> (the equivalent of <RouterView>):

<!-- app/app.vue -->
<template>
  <NuxtRouteAnnouncer />
  <NuxtLayout>
    <NuxtPage />
  </NuxtLayout>
</template>

<NuxtRouteAnnouncer> announces the new page's title to screen readers on every navigation: in an SPA, unlike a traditional website, changing page reloads nothing and the screen reader does not find out unless someone tells it.

  1. Layouts

A layout is the frame that surrounds the pages. Create app/layouts/default.vue, which Nuxt uses for every page unless it specifies another one:

<!-- app/layouts/default.vue -->
<template>
  <div class="frame">
    <header class="header">
      <NuxtLink to="/" class="header__brand">Coworking Colmena</NuxtLink>
      <nav aria-label="Main">
        <NuxtLink to="/">Home</NuxtLink>
        <NuxtLink to="/rooms">Rooms</NuxtLink>
      </nav>
      <ClientOnly>
        <ColmenaClock />
        <template #fallback><span class="clock">--:--</span></template>
      </ClientOnly>
    </header>

    <main class="content">
      <slot />
    </main>

    <footer class="footer">© Coworking Colmena · Fictitious data</footer>
  </div>
</template>

The clock is the textbook case from section 3: the server's time would never match the browser's. With <ClientOnly>, the server renders --:-- and the browser replaces it with the clock when hydrating. The component is a simplified version of ReceptionClock:

<!-- app/components/ColmenaClock.vue -->
<script setup>
const now = ref(new Date())
let timer

// Only in the browser: on the server, onMounted does not run and no interval is left alive
onMounted(() => {
  timer = setInterval(() => (now.value = new Date()), 1000)
})
onUnmounted(() => clearInterval(timer))
</script>

<template>
  <span class="clock">{{ now.toLocaleTimeString('en-GB') }}</span>
</template>

Notice that there is no import at all: ref, onMounted and onUnmounted are auto-imported (section 10). A page can choose another layout with definePageMeta({ layout: 'no-header' }), which would look for app/layouts/no-header.vue.

  1. Auto-importing components and composables

Nuxt automatically imports:

What From where Example
Vue's APIs vue ref, computed, watch, onMounted, toValue
Nuxt's composables Nuxt useFetch, useRoute, useRouter, useState, useSeoMeta, useRuntimeConfig
Your components app/components/ <PublicRoomCard />; in subfolders, the name includes the folder: components/base/Button.vue → <BaseButton />
Your composables and utilities app/composables/, app/utils/ (top-level files) usePrice(), useRoomFilters()

Explicit imports still work, and they are advisable when they make it clear where something comes from. But the important thing is that Nuxt only includes in the bundle what is actually used, and generates the types so that the editor can autocomplete them.

10.1 A composable of our own: usePrice

// app/composables/usePrice.js
// Price formatting for the public website (always in British English and in euros)
const euroFormatter = new Intl.NumberFormat('en-GB', { style: 'currency', currency: 'EUR' })

export function usePrice() {
  return (amount) => euroFormatter.format(amount)
}

The locale is fixed ('en-GB'): if it depended on the browser, the server and the client could format differently and cause a hydration mismatch. The public website is only in English for now (section 15).

10.2 The card

<!-- app/components/PublicRoomCard.vue -->
<script setup>
const { room } = defineProps({ room: { type: Object, required: true } })
const price = usePrice()
</script>

<template>
  <article class="card">
    <h2>
      <NuxtLink :to="`/rooms/${room.id}`">{{ room.name }}</NuxtLink>
    </h2>
    <p>Floor {{ room.floor }} · up to {{ room.capacity }} people · {{ price(room.hourlyPrice) }}/h</p>
    <p v-if="!room.available" class="card__notice">Temporarily out of service</p>
  </article>
</template>

10.3 Reusing useRoomFilters

In 09-01 we designed useRoomFilters(rooms) to receive the catalogue as an argument, and we said that this would allow it to be used in other contexts. Here is the proof: copy src/composables/useRoomFilters.js from Colmena Bookings to app/composables/useRoomFilters.js in colmena-web and delete the line import { useRoute, useRouter } from 'vue-router'. Nuxt auto-imports its own versions of useRoute and useRouter, which are the recommended ones within Nuxt (they are coordinated with page loading). Everything else works unchanged, on the server too: the filters are read from the URL's query, so /rooms?floor=2&sort=price-asc arrives already filtered from the server.

Copying the file between two projects is acceptable for a course. In a real project, the shared code would go in a package of its own (in a monorepo, for example) that both projects would depend on, so that a fix does not have to be made twice.

  1. Server routes: the catalogue API

Nitro, Nuxt's server, turns each file in server/api/ into an API endpoint. The file name indicates the route and, optionally, the HTTP method.

First, the data. In Colmena Bookings, the catalogue is in src/data/rooms.js and the "API" is a simulation that runs in the browser. In colmena-web, the API is real: it runs on the server. Copy src/data/rooms.js to server/data/rooms.js: it is the same data model (id, name, floor, capacity, hourlyPrice, equipment, available) and the same five rooms.

// server/api/rooms.get.js → GET /api/rooms (accepts ?floor=N)
import { rooms } from '../data/rooms.js'

export default defineEventHandler((event) => {
  const { floor } = getQuery(event)
  const number = Number(floor)
  return Number.isInteger(number) && number > 0
    ? rooms.filter((room) => room.floor === number)
    : rooms
})
// server/api/rooms/[id].get.js → GET /api/rooms/:id
import { rooms } from '../../data/rooms.js'

export default defineEventHandler((event) => {
  const id = getRouterParam(event, 'id')
  const room = rooms.find((r) => r.id === id)
  if (!room) {
    throw createError({ statusCode: 404, statusMessage: `No room exists with the id "${id}"` })
  }
  return room
})
  • defineEventHandler declares a request handler; whatever it returns is sent as JSON.
  • .get.js restricts the file to the GET method; a rooms.post.js would respond to POST.
  • getQuery(event) and getRouterParam(event, 'id') read the query and the params. They are utilities from h3, Nitro's HTTP library, auto-imported in server/.
  • createError with statusCode: 404 produces an error response with that code, like the errorWithStatus(..., 404) in our simulated API.
  • Nothing in server/ reaches the browser: it is the place for secrets, database queries or calls to other services. In a real version, these handlers would query the same database as Colmena Bookings' backend.

With npm run dev, open http://localhost:3000/api/rooms?floor=2: JSON with Néctar and Celda.

  1. Data fetching: useFetch and useAsyncData

12.1 Why not fetch directly in setup

In Colmena Bookings we request data from setup or from the stores. In an application with SSR, doing that with fetch has two problems:

  1. A double request: setup runs on the server (which requests the data and renders) and again in the browser when hydrating, which requests it again.
  2. A hydration mismatch: until the second request responds, the client has no data and renders something different from what arrived from the server.

Nuxt's data composables solve both: on the server, they fetch the data and store it in the page's payload; in the browser, when hydrating, they read it from the payload instead of requesting it again.

12.2 useFetch

<!-- app/pages/rooms/index.vue -->
<script setup>
const { data: rooms, status, error, refresh } = await useFetch('/api/rooms')

const {
  floorFilter, minCapacity, sort, visibleRooms, clearFilters
} = useRoomFilters(() => rooms.value ?? [])

useSeoMeta({
  title: 'Rooms · Coworking Colmena',
  description: 'Five meeting rooms by the hour, from a single-person booth to an auditorium for 40 people.'
})
</script>

<template>
  <section>
    <h1>Our rooms</h1>

    <nav class="filters" aria-label="Filter by floor">
      <button type="button" :aria-pressed="floorFilter === null" @click="floorFilter = null">All</button>
      <button
        v-for="n in 3"
        :key="n"
        type="button"
        :aria-pressed="floorFilter === n"
        @click="floorFilter = n"
      >
        Floor {{ n }}
      </button>
    </nav>

    <label>
      Sort
      <select v-model="sort">
        <option value="none">Unsorted</option>
        <option value="price-asc">Cheapest first</option>
        <option value="price-desc">Most expensive first</option>
      </select>
    </label>

    <div v-if="error" class="notice" role="alert">
      <p>We could not load the rooms.</p>
      <button type="button" @click="refresh()">Retry</button>
    </div>
    <p v-else-if="status === 'pending'">Loading the rooms…</p>
    <template v-else>
      <PublicRoomCard v-for="room in visibleRooms" :key="room.id" :room="room" />
      <p v-if="visibleRooms.length === 0">
        No room matches those criteria. <button type="button" @click="clearFilters">See all</button>
      </p>
    </template>
  </section>
</template>
  • await useFetch(url) returns refs: data, status ('idle', 'pending', 'success', 'error'), error and refresh() (plus clear and execute). It will look familiar: it is the same shape as useRequest (09-01), with SSR taken care of.
  • The await means that, on the server, Nuxt waits for the data before rendering, so that the HTML includes it. Nuxt wraps every page in a <Suspense> (09-05): that is how it can wait for an async setup.
  • The URL /api/rooms is relative: on the server, Nuxt calls the Nitro handler directly, without going through the network.
  • The whole catalogue is requested and filtered on the client with useRoomFilters, the same decision we made in 05-02 for the store: with five rooms, changing floor does not need a new request.

useFetch accepts options; some useful ones:

Option What for
query: { floor } Query parameters; if floor is a ref or a getter, the request is repeated when it changes (like useRequest's source)
key The data's identifier in the payload; it is generated automatically from the URL and the options
lazy: true Does not block navigation: the page is shown and the data arrives afterwards (you have to handle the pending status)
server: false Requests the data only in the browser (for personal data, or data that must not be indexed)
pick: ['id', 'name'] Stores only those fields in the payload, so that it weighs less
transform: (data) => ... Transforms the response before storing it
default: () => [] Initial value of data instead of undefined

12.3 A room's spec sheet

<!-- app/pages/rooms/[id].vue -->
<script setup>
const route = useRoute()
const price = usePrice()
const requestUrl = useRequestURL() // the request's URL, on the server too
const { public: { bookingsUrl } } = useRuntimeConfig()

const { data: room, error } = await useFetch(() => `/api/rooms/${route.params.id}`)

if (error.value) {
  // Nuxt shows its error page with this code (and responds with a 404 to search engines)
  throw createError({ statusCode: 404, statusMessage: 'Room not found', fatal: true })
}

useSeoMeta({
  title: () => `${room.value.name} · Coworking Colmena`,
  description: () =>
    `${room.value.name}: up to ${room.value.capacity} people on floor ${room.value.floor}, ${price(room.value.hourlyPrice)} an hour.`,
  ogTitle: () => room.value.name,
  ogImage: () => new URL(`/img/rooms/${room.value.id}.webp`, requestUrl.origin).href
})
</script>

<template>
  <article class="spec-sheet">
    <NuxtLink to="/rooms">← All rooms</NuxtLink>
    <h1>{{ room.name }}</h1>
    <img :src="`/img/rooms/${room.id}.webp`" :alt="`Photo of the ${room.name}`" width="800" height="500" />
    <dl>
      <dt>Floor</dt>
      <dd>{{ room.floor }}</dd>
      <dt>Capacity</dt>
      <dd>{{ room.capacity }} people</dd>
      <dt>Price per hour</dt>
      <dd>{{ price(room.hourlyPrice) }}</dd>
    </dl>
    <a v-if="room.available" class="button" :href="`${bookingsUrl}/book/${room.id}`">
      Book in Colmena Bookings
    </a>
  </article>
</template>
  • ogImage must be an absolute address: social networks download the image from their own servers, without knowing which domain the page was on. useRequestURL() gives the request's origin both on the server and in the browser.
  • The URL is a getter (() => `/api/rooms/${route.params.id}`): when navigating from one spec sheet to another, useFetch requests the data again. It is the view-reuse problem from 04-03, solved with a reactive source, as in useRequest.
  • throw createError({ ..., fatal: true }) in a page's setup shows Nuxt's error page (customisable with app/error.vue) and, on the server, responds with the 404 code. For a search engine, it is the difference between "this page does not exist" and a blank page with a 200.
  • The link to the SPA: the button leads to Colmena Bookings' booking form, on the /book/:roomId route we created in 04-03. If the visitor has no session, the SPA's guards will ask them to sign in and will bring them back to the form (04-06).
  • useRuntimeConfig() reads the runtime configuration. Declare it in nuxt.config.ts (section 14) with runtimeConfig: { public: { bookingsUrl: 'http://localhost:5173' } }; in production it is changed without rebuilding, with the NUXT_PUBLIC_BOOKINGS_URL environment variable.
  • The photos: copy the public/img/rooms/ folder from Colmena Bookings to public/img/rooms/ in colmena-web.

12.4 useAsyncData and $fetch

useFetch(url) is a shortcut for useAsyncData, which accepts any async function. Use it when the data does not come from a single URL:

// Two requests in parallel, stored together in the payload under the 'home' key
const { data } = await useAsyncData('home', async () => {
  const [rooms, featured] = await Promise.all([
    $fetch('/api/rooms'),
    $fetch('/api/rooms/nectar')
  ])
  return { rooms, featured }
})

$fetch is Nuxt's HTTP client (based on the ofetch library): like fetch, but it returns the JSON directly and throws an error if the response is not OK. By itself it does not transfer anything to the payload, so:

Situation What to use
Data for rendering a page or component useFetch or useAsyncData
A user action (submitting a form, clicking a button) $fetch inside the event handler
Inside useAsyncData $fetch (it is its fetching function)

  1. SEO with useSeoMeta and useHead

What makes the public website valuable is that the HTML arrives with its <title> and its metadata for search engines and social networks. Nuxt manages the <head> with two composables:

  • useSeoMeta for SEO and social network tags, with camelCase names and type checking: title, description, ogTitle, ogDescription, ogImage, twitterCard... It accepts fixed values or getters, which are recalculated if the data changes (as in the spec sheet).
  • useHead for everything else: the <html> element's lang, links (canonical, preload), external scripts or structured data.

On the home page:

<!-- app/pages/index.vue -->
<script setup>
useSeoMeta({
  title: 'Coworking Colmena · Meeting rooms by the hour',
  description: 'Five rooms, from a single-person booth to an auditorium for 40 people, in a three-storey building.',
  ogTitle: 'Coworking Colmena',
  ogDescription: 'Meeting rooms by the hour in a three-storey building.'
})

const { data: rooms } = await useFetch('/api/rooms')
const featured = computed(() => (rooms.value ?? []).filter((room) => room.available).slice(0, 3))
</script>

<template>
  <section class="home">
    <h1>Rooms for teamwork</h1>
    <p>Book by the hour. No commitment.</p>
    <PublicRoomCard v-for="room in featured" :key="room.id" :room="room" />
    <NuxtLink to="/rooms">See all the rooms →</NuxtLink>
  </section>
</template>

And for the whole site, the document's language in nuxt.config.ts (section 14), with app: { head: { htmlAttrs: { lang: 'en' } } }: the equivalent of the lang="en" we put in Colmena Bookings' index.html in 01-03.

To check it, look at the page's source code (Ctrl+U), not the inspector: the source code is what a search engine or a social network receives. You will see the <title>, the <meta> tags and the cards' content inside the HTML.

  1. Per-route rendering rules: routeRules

By default, Nuxt does SSR on every request. With routeRules you choose the strategy per route, which is the hybrid model from section 1. colmena-web's nuxt.config.ts:

// nuxt.config.ts
export default defineNuxtConfig({
  compatibilityDate: '2025-07-15', // whatever the template sets when creating the project
  devtools: { enabled: true },

  app: {
    head: { htmlAttrs: { lang: 'en' } }
  },

  runtimeConfig: {
    public: {
      bookingsUrl: 'http://localhost:5173' // Colmena Bookings in development
    }
  },

  routeRules: {
    '/': { prerender: true },           // SSG: generated when building
    '/rooms': { swr: 3600 },            // SSR with a cache: regenerated at most once an hour
    '/rooms/**': { swr: 3600 }
  }
})
Rule Effect In colmena-web
prerender: true The route is rendered when building and served as a static file The home page: it changes very little
swr: seconds Stale-while-revalidate: the first request is rendered and cached; during that time the copy is served, and when it expires the old copy is served while the new one is regenerated in the background The catalogue and the spec sheets: public data that changes from time to time
isr: seconds Like swr, but delegating the cache to the CDN on platforms that support it An alternative to swr depending on where it is deployed (10-02)
ssr: false That route behaves like an SPA (client-side rendering) A private area, if there were one
redirect, headers, cors Redirects, headers and CORS per route —

** matches any route under /rooms/. The result: the home page comes from a static file, the catalogue and the spec sheets are rendered on the server at most once an hour, and the Node server barely does any work.

  1. State, Pinia and internationalisation in Nuxt

useState is Nuxt's SSR-safe shared state: it is created per request on the server, travels in the payload and is recovered when hydrating. It is identified by a key:

// Shared between the components of the same request/browser session, never between users
const favoriteFloor = useState('favorite-floor', () => null)

It is the solution to the module state problem in section 4. For more structured state, Pinia works in Nuxt with its official module, which is installed with:

npx nuxt module add pinia

The command installs @pinia/nuxt and adds it to modules in nuxt.config.ts. From then on, defineStore and the stores (in app/stores/, auto-imported) work as in 05-06, creating a new Pinia per request on the server and transferring its state to the browser. What cannot be carried over unchanged is our persistence plugin (05-07), because it reads localStorage and sessionStorage, which do not exist on the server.

For several languages, the @nuxtjs/i18n module integrates Vue I18n (07-03) with file-based routing: it generates routes per language (/rooms, /es/salas, /ca/sales), the hreflang tags for search engines and language detection on the server too. Colmena Bookings' message files could be reused. We are leaving it as an improvement: section 3 has already shown why the language must be decided in the same way on the server and on the client.

  1. Building and generating

Command Result When
npm run build (nuxt build) .output/ with a Node server (.output/server/index.mjs) and the public files (.output/public/); the routes with prerender are already generated To deploy with SSR, SWR or server routes (/api/rooms)
npm run generate (nuxt generate) .output/public/ with every route prerendered as static HTML For a completely static site, with no server (server routes will not be available at runtime)
npm run preview Serves the result of build locally To check it before deploying

colmena-web needs build: it has an API and swr rules, which require a server. After building, node .output/server/index.mjs starts it on port 3000. How and where it is deployed (your own server, a platform with serverless functions or a CDN for the static version) we will see in Deploying Vue.js Applications.

  1. Try it

  1. The server's HTML. With npm run dev in colmena-web, open http://localhost:3000/rooms and look at the source code (Ctrl+U): the five rooms are in the HTML. Do the same in Colmena Bookings (http://localhost:5173/rooms): you will only see <div id="app"></div>.
  2. Without JavaScript. In the browser's developer tools, disable JavaScript (command menu, "Disable JavaScript") and reload both applications: colmena-web is displayed in full (although the filter buttons do not work); Colmena Bookings, blank. Enable it again.
  3. Filters from the server. Open http://localhost:3000/rooms?floor=2&sort=price-desc: the source code already contains only Néctar and Celda, in that order. Click "Floor 1": the URL changes without reloading the page (it is now an SPA) and the list is updated.
  4. Hydration. There must be no hydration warnings in the development console. Now temporarily remove the <ClientOnly> around <ColmenaClock /> in the layout, reload and look for the mismatch warning in the console. Restore it.
  5. A single request. In the Network tab, filter by "api" and reload /rooms: there is no request to /api/rooms from the browser, because the data arrived in the payload. Navigate to the home page and back to "Rooms" using the links: now there is a request, because that navigation already happens on the client.
  6. SEO. Open http://localhost:3000/rooms/nectar and look at the source code: <title>Néctar Room · Coworking Colmena</title>, the description with "€35.00 an hour" and the og: tags.
  7. A real 404. Open /rooms/basement: an error page. In the Network tab, the document has the 404 status.
  8. Production. Run npm run build and node .output/server/index.mjs. Check with curl -I http://localhost:3000/rooms that the response includes a cache-control header with stale-while-revalidate, and that .output/public/index.html exists (the prerendered home page).
  9. The two applications. With Colmena Bookings running on 5173, click "Book in Colmena Bookings" on Néctar's spec sheet: you arrive at its form (or at the sign-in page, if you are not signed in).

Common Mistakes and Tips

  • Using window, document or localStorage in setup or at module level. They do not exist on the server. Move it to onMounted or guard it with import.meta.client.
  • Creating timers or subscriptions in setup. On the server they are never cleaned up. Create them in onMounted.
  • Keeping state at module level in an application with SSR. It is shared between the requests of every user. Use useState or Pinia.
  • Requesting data with fetch (or $fetch) directly in setup. A double request and a hydration mismatch. Use useFetch or useAsyncData.
  • Ignoring hydration warnings. They indicate that the client and the server render different things: look for the cause in the table in section 3 instead of silencing them.
  • Formatting dates or numbers without an explicit locale or time zone. The server and the browser need not agree.
  • Choosing SSR for everything by default. It has a cost in servers and complexity. A private application with a session, like Colmena Bookings, does not need it; use routeRules to choose per route.
  • Looking at the inspector to check SEO. The inspector shows the DOM after JavaScript. What search engines see is the source code.
  • Tip: Vue 3.5 also allows lazy hydration of async components: defineAsyncComponent({ loader: () => import('./Map.vue'), hydrate: hydrateOnVisible() }) does not hydrate the component (it neither downloads nor runs its code) until it is visible. It is useful for heavy parts that sit outside the first screen, such as a map at the bottom of the home page.

Exercises

Exercise 1. Add a /floors/[number] page to colmena-web (app/pages/floors/[number].vue) that shows the rooms on a floor, requesting only that floor's rooms from the API with useFetch's query option. If number is not 1, 2 or 3, the 404 error page must be shown. Add its title and description with useSeoMeta, and a prerendering rule for the three floors.

Exercise 2. Identify, in this component intended for colmena-web, everything that would fail or cause a hydration mismatch with SSR, and fix it:

<script setup>
const language = localStorage.getItem('language') ?? navigator.language
const visits = ref(Number(localStorage.getItem('visits') ?? 0) + 1)
localStorage.setItem('visits', visits.value)
const noticeId = `notice-${Math.random().toString(36).slice(2)}`
const today = new Date().toLocaleDateString(language)
setInterval(() => console.log('still alive'), 60000)
</script>

<template>
  <p :id="noticeId">Today is {{ today }}. This is visit number {{ visits }}.</p>
</template>

Exercise 3. Create a /contact page in colmena-web with a form (name, email address and message) that is submitted to a server route, server/api/contact.post.js. The route must check that all three fields arrive and that the email address contains an @ (if not, respond with a 422 error) and return { received: true }. On the page, submit the form with $fetch and show a confirmation message or the error.

Solutions

Solution 1.

<!-- app/pages/floors/[number].vue -->
<script setup>
const route = useRoute()
const number = Number(route.params.number)

if (![1, 2, 3].includes(number)) {
  throw createError({ statusCode: 404, statusMessage: 'Floor not found', fatal: true })
}

const { data: rooms } = await useFetch('/api/rooms', { query: { floor: number } })

useSeoMeta({
  title: `Rooms on floor ${number} · Coworking Colmena`,
  description: `Meeting rooms available on floor ${number} of Coworking Colmena.`
})
</script>

<template>
  <section>
    <h1>Floor {{ number }}</h1>
    <PublicRoomCard v-for="room in rooms" :key="room.id" :room="room" />
  </section>
</template>
// nuxt.config.ts: add to routeRules
'/floors/1': { prerender: true },
'/floors/2': { prerender: true },
'/floors/3': { prerender: true },

The check on the number comes before useFetch: there is no point requesting data for a floor that does not exist. Since the page is not reused between floors with a reactive param (each floor is a navigation with its own server render), reading route.params.number once is enough here; if you added links between floors within the page, it would be advisable to use a getter, as in the room's spec sheet. The three floors are prerendered at build time because their content changes as little as the home page's.

Solution 2. The problems: localStorage and navigator do not exist on the server (an error when rendering); Math.random() gives a different id on the server and on the client (a mismatch); new Date().toLocaleDateString(language) depends on each environment's time and language (a mismatch); and the setInterval in setup creates an interval on the server that is never cleaned up, one per request (a leak). Fixed:

<script setup>
const noticeId = useId() // stable between server and client
const dateFormatter = new Intl.DateTimeFormat('en-GB', { dateStyle: 'full', timeZone: 'Europe/Madrid' })
const today = dateFormatter.format(new Date())
const visits = ref(null) // unknown on the server
let timer

onMounted(() => {
  // Only in the browser
  visits.value = Number(localStorage.getItem('visits') ?? 0) + 1
  localStorage.setItem('visits', visits.value)
  timer = setInterval(() => console.log('still alive'), 60000)
})
onUnmounted(() => clearInterval(timer))
</script>

<template>
  <p :id="noticeId" data-allow-mismatch="text">
    Today is {{ today }}.
    <span v-if="visits">This is visit number {{ visits }}.</span>
  </p>
</template>

The date with a fixed locale and time zone can only differ if the page is rendered just before midnight and hydrated just after; for that edge case, data-allow-mismatch="text" prevents the warning. The visits are only shown after mounting, so that the server and the client's first render match (without the <span>).

Solution 3.

// server/api/contact.post.js
export default defineEventHandler(async (event) => {
  const { name, email, message } = (await readBody(event)) ?? {}
  if (!name || !email || !message || !String(email).includes('@')) {
    throw createError({ statusCode: 422, statusMessage: 'Please check the name, email address and message' })
  }
  // An email would be sent or the message saved to a database here
  return { received: true }
})
<!-- app/pages/contact.vue -->
<script setup>
const form = reactive({ name: '', email: '', message: '' })
const sending = ref(false)
const result = ref('')
const error = ref('')

async function send() {
  sending.value = true
  result.value = ''
  error.value = ''
  try {
    await $fetch('/api/contact', { method: 'POST', body: form })
    result.value = 'Thank you: we will reply within one working day.'
    Object.assign(form, { name: '', email: '', message: '' })
  } catch (e) {
    error.value = e.statusMessage ?? 'The message could not be sent.'
  } finally {
    sending.value = false
  }
}

useSeoMeta({ title: 'Contact · Coworking Colmena', description: 'Write to us to arrange a visit to the coworking space.' })
</script>

<template>
  <form @submit.prevent="send">
    <label>Name <input v-model.trim="form.name" required /></label>
    <label>Email address <input v-model.trim="form.email" type="email" required /></label>
    <label>Message <textarea v-model.trim="form.message" required></textarea></label>
    <button type="submit" :disabled="sending">Send</button>
    <p v-if="result" role="status">{{ result }}</p>
    <p v-if="error" role="alert">{{ error }}</p>
  </form>
</template>

$fetch is the right choice here, rather than useFetch, because submitting is a user action that happens in the browser, not data needed to render the page. readBody is another h3 utility auto-imported in server/. Server-side validation is essential even though the form has required: we saw this with the router's guards in 04-06.

Conclusion

Rendering strategies answer the question of who generates the HTML and when: the browser on every visit (CSR), the server on every request (SSR), the server once at build time (SSG) or the server with a cache (hybrid), and each one balances SEO, first paint, server cost and data freshness differently. With SSR, the browser hydrates the HTML it receives, which requires the code to be universal: no browser APIs in setup, no timers outside onMounted, no module state shared between users and no values that differ between server and client (dates, random numbers), with <ClientOnly> for whatever only makes sense in the browser. Colmena Bookings remains an SPA, because it is a private tool with a session, and the new colmena-web is its public shop window built with Nuxt: file-based routing (pages/index.vue, pages/rooms/index.vue, pages/rooms/[id].vue), a layout with the header, auto-imported components and composables (including useRoomFilters, reused without any changes to its logic), server routes that serve the catalogue (server/api/rooms.get.js and server/api/rooms/[id].get.js) with the same data model, useFetch to obtain the data without requesting it twice, useSeoMeta for search engines and social networks, and routeRules to prerender the home page and serve the catalogue with swr.

A website that appears instantly is only half of performance: the other half is that, once loaded, it responds effortlessly to every click, every filter and every list of thousands of items. We return to Colmena Bookings to measure where its time goes and to apply the right techniques in Performance Optimization.

New edition · October 2026

Vue.js Course

Module 1: Introduction to Vue.js

Module 2: Vue.js Basics

Module 3: Vue.js Components

Module 4: Vue Router

Module 5: State Management with Vuex and Pinia

Module 6: Vue.js Directives

Module 7: Vue.js Plugins

Module 8: Testing in Vue.js

Module 9: Advanced Vue.js Concepts

Module 10: Building and Deploying Vue.js Applications

Module 11: Real-World Vue.js Projects

© Copyright 2026. All rights reserved