---
title: "Render data on the server"
description: "Render pages with their data, signed-in reads included, and go live in the browser without a second fetch; preload from a Nitro route, or call the backend from your own API routes."
canonical_url: "https://nuxt-backend.dev/docs/build/data/read-write/server-rendering"
---
# Render data on the server

> Render pages with their data, signed-in reads included, and go live in the browser without a second fetch; preload from a Nitro route, or call the backend from your own API routes.

Version: nuxt-backend 0.6.x · Tab: Build · Kind: how-to · Status: stable

Every page: [llms.txt](https://nuxt-backend.dev/llms.txt) · Skill for coding agents: [nuxt-backend](https://nuxt-backend.dev/.well-known/skills/nuxt-backend/SKILL.md)

Commands use npm; use your project's package manager.

A page rendered with `useQuery` arrives empty and fills in once the browser has connected. `useAsyncQuery` fetches during the server render instead, as the signed-in person, puts the result in the HTML and the Nuxt payload, and the browser takes it over as a live subscription with no second fetch. For your own API routes, the server helpers call the backend from Nitro, as the visitor or as the signed-in person. Convex answers the server fetch over HTTP; the base module hands the result to the live subscription, and the package adds the signed-in token on the server, the private cache headers and `backendAuth(event)`. `api` comes from [`#backend/api`](https://nuxt-backend.dev/docs/reference/nuxt/import-aliases) on both sides.

## Render a page with its data

```vue [app/pages/strips.vue]
<script setup lang="ts">
import { api } from '#backend/api'

definePageMeta({ auth: true })

const { data: strips, error } = await useAsyncQuery(api.strips.list, {})
</script>

<template>
  <p v-if="error">{{ getBackendError(error)?.message ?? 'Could not load your strips.' }}</p>
  <ul v-else>
    <li v-for="strip in strips" :key="strip._id">{{ strip.title }}</li>
  </ul>
</template>
```

- **Signed in on the server.** The module reads the session's token at the start of every server render, so a query behind [an access tier](https://nuxt-backend.dev/docs/build/auth/access/functions) answers for the person who asked. A response rendered with a token is sent `Cache-Control: private, no-store`, so no cache keeps one person's page for another. A page with `auth: true` renders only for someone signed in.
- **Live afterwards.** `data` holds the server's result until the browser's subscription delivers its own, then follows it. Arguments may be a ref or a getter, and `'skip'` pauses the query.
- **One fetch.** The result is keyed on the query and its first arguments, so two components asking for the same query share it. `await` holds the render until it lands, as `useAsyncData` does.
- **Failures.** `error` holds why the fetch or the subscription failed, and `status` is `'idle'`, `'pending'`, `'success'` or `'error'`; nothing throws. Read a refusal's code with [`getBackendError`](https://nuxt-backend.dev/docs/build/data/read-write/errors).

<table>
<thead>
  <tr>
    <th>
      Option
    </th>
    
    <th>
      Default
    </th>
    
    <th>
      Effect
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        server
      </code>
    </td>
    
    <td>
      <code>
        true
      </code>
    </td>
    
    <td>
      <code>
        false
      </code>
      
       fetches in the browser only
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        lazy
      </code>
    </td>
    
    <td>
      <code>
        false
      </code>
    </td>
    
    <td>
      <code>
        true
      </code>
      
       does not hold a client-side navigation for the first fetch
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        live
      </code>
    </td>
    
    <td>
      <code>
        true
      </code>
    </td>
    
    <td>
      <code>
        false
      </code>
      
       opens no subscription: the page shows what the server rendered, and <code>
        refresh()
      </code>
      
       fetches it again
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        key
      </code>
    </td>
    
    <td>
      the query and its first arguments
    </td>
    
    <td>
      Names the payload entry, for two calls that must not share one
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        token
      </code>
    </td>
    
    <td>
      the session's
    </td>
    
    <td>
      A token, or a function that resolves one, for the server's fetch
    </td>
  </tr>
</tbody>
</table>

## Render a long list

`useAsyncPaginatedQuery(query, args, { initialNumItems })` renders the first page on the server, then hands over to [`usePaginatedQuery`](https://nuxt-backend.dev/docs/build/data/read-write#pagination) in the browser, with `loadMore` and live rows:

```vue
<script setup lang="ts">
import { api } from '#backend/api'

const { results, status, loadMore } = await useAsyncPaginatedQuery(
  api.messages.listPaginated,
  { channel: '#general' },
  { initialNumItems: 20 },
)
</script>
```

It returns `results`, `status`, `isLoading`, `error`, `loadMore` and `refresh`. Until the browser has its first page, `status` comes from the server's page (`'CanLoadMore'` or `'Exhausted'`), and `loadMore` waits for the subscription.

## Preload from a Nitro route

Preloading fits when a server route is where the data comes from: one that also serves the JSON to another client, or gathers several queries in one request. `preloadQuery` returns a payload that the page turns live with `usePreloadedQuery`:

```ts [server/api/messages.preload.ts]
import { api } from '#backend/api'

export default defineEventHandler(() => preloadQuery(api.messages.list, {}))
```

```vue
<script setup lang="ts">
const { data: preloaded } = await useFetch('/api/messages.preload')
const messages = usePreloadedQuery(preloaded.value!)
</script>
```

For a signed-in read, preload through `backendAuth(event)` and turn it live with `usePreloadedAuthQuery`. It keeps the server's result on screen while the browser signs in, skips the live query for someone signed out, and goes live once the browser is signed in:

```ts [server/api/account.preload.ts]
import { api } from '#backend/api'

export default defineEventHandler(event => backendAuth(event).preloadAuthQuery(api.auth.getAuthUser, {}))
```

```vue
<script setup lang="ts">
const { data: preloaded } = await useFetch('/api/account.preload')
const currentUser = usePreloadedAuthQuery(preloaded.value!)
</script>
```

## Call the backend from a Nitro route

Server routes and middleware call the backend through auto-imported helpers. No client is injected on the server: every call goes through one of these.

```ts [server/api/messages.post.ts]
import { api } from '#backend/api'

export default defineEventHandler(async (event) => {
  const { body } = await readBody<{ body: string }>(event)
  return await backendAuth(event).fetchAuthMutation(api.messages.send, { body })
})
```

<table>
<thead>
  <tr>
    <th>
      Helper
    </th>
    
    <th>
      Runs
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        fetchQuery
      </code>
      
      , <code>
        fetchMutation
      </code>
      
      , <code>
        fetchAction
      </code>
    </td>
    
    <td>
      A function as the visitor, or with <code>
        { token }
      </code>
      
       as its third argument
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        preloadQuery
      </code>
    </td>
    
    <td>
      A query, as a payload for <code>
        usePreloadedQuery
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        preloadedQueryResult
      </code>
    </td>
    
    <td>
      The result inside a preloaded payload
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        backendAuth(event)
      </code>
    </td>
    
    <td>
      The helpers below, for the person signed in on this request
    </td>
  </tr>
</tbody>
</table>

<table>
<thead>
  <tr>
    <th>
      <code>
        backendAuth(event)
      </code>
      
       helper
    </th>
    
    <th>
      Does
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        isAuthenticated()
      </code>
    </td>
    
    <td>
      Whether the request carries a session
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        getToken()
      </code>
    </td>
    
    <td>
      The session's token, for <code>
        fetchQuery
      </code>
      
       and the others
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        fetchAuthQuery
      </code>
      
      , <code>
        fetchAuthMutation
      </code>
      
      , <code>
        fetchAuthAction
      </code>
    </td>
    
    <td>
      Run a function as the signed-in person
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        preloadAuthQuery
      </code>
    </td>
    
    <td>
      Preload a query as the signed-in person, for <code>
        usePreloadedAuthQuery
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        handler
      </code>
    </td>
    
    <td>
      Forward an auth request to the deployment, as the module's <code>
        /api/auth
      </code>
      
       route does
    </td>
  </tr>
</tbody>
</table>

A call through `backendAuth(event)` that crashes, or is refused as `unavailable`, is [reported](https://nuxt-backend.dev/docs/ship/operate/monitoring#what-gets-reported) with the function's name, then thrown as before. A refusal reaches your route as the function threw it, with its code in the error's `data`; left uncaught, it becomes the route's error.

```ts [server/api/profile.ts]
import { api } from '#backend/api'

export default defineEventHandler(async (event) => {
  const auth = backendAuth(event)
  if (!await auth.isAuthenticated()) throw createError({ statusCode: 401, statusMessage: 'Sign in first' })
  return auth.fetchAuthQuery(api.users.me, {})
})
```

## Limits

- **One request, one token.** The server render reads the session once, at its start. A session that ends during the render still renders that page; the browser then follows the new state.
- **No prerendering of private data.** A page rendered with a token is never cached or prerendered. Cache only public pages, through route rules scoped to their paths ([Caches](https://nuxt-backend.dev/docs/build/ui/pages#caches)).
- **Payload size.** Every server result rides in the page's payload. Render the first page of a long list, not the whole list.

## Test it

Open the page with JavaScript turned off in the browser's developer tools: the list is in the HTML. Then turn it back on, change a row from another tab, and watch the page follow without a reload. [Test pages over a mock backend](https://nuxt-backend.dev/docs/develop/testing/pages) covers `useAsyncQuery` in component tests.

## Related

- [Query and update data](https://nuxt-backend.dev/docs/build/data/read-write): the live composables a server-rendered page hands over to.
- [Handle errors](https://nuxt-backend.dev/docs/build/data/read-write/errors): the codes a server fetch can be refused with.
- [Protect pages](https://nuxt-backend.dev/docs/build/auth/access/pages): which pages render for whom, checked on the server.
- [Server utilities](https://nuxt-backend.dev/docs/reference/nuxt/server-utilities) and [Composables](https://nuxt-backend.dev/docs/reference/nuxt/composables): the reference.
- [Convex](https://nuxt-backend.dev/docs/services/convex): the deployment the server fetches from.


## Sitemap

See the full [sitemap](https://nuxt-backend.dev/sitemap.md) for all pages.
