# Fetching Data

> Read Postgres data in a service, call it from a typed page loader, validate request inputs, and handle slow or missing data.

*Canonical: https://makerkit.dev/docs/void-cloudflare/development-guide/data-fetching*

---

Fetch a page's initial data in its server loader. Call the database or an outside service from named functions, then return the fields the component needs. This avoids a second browser request just to display the initial page.

This guide extends the [account summary page](./pages-and-routing). The `user` table already exists in the kit.

## 1. Write a Scoped Query

Create `apps/web/lib/account-summary.service.ts`:

```ts
import { db, eq } from 'void/db';

import { user } from '#/db/schema.ts';

export async function findAccountSummary({ userId }: { userId: string }) {
  const [profile] = await db
    .select({ name: user.name, email: user.email, createdAt: user.createdAt })
    .from(user)
    .where(eq(user.id, userId))
    .limit(1);

  return profile ?? null;
}
```

The query filters by the authenticated user's id and selects only the fields the page displays. It cannot become a list of every account by forgetting a filter in the component.

This service contains server work. Import it from loaders, actions, or other server code, never from a React component. In a reusable package, inject the database through the package's server entry rather than importing `void/db` there.

## 2. Call the Service in the Loader

Replace the account summary loader in `index.server.ts` with:

```ts
import { HTTPException } from 'hono/http-exception';
import { defineHandler } from 'void';

import { findAccountSummary } from '#/lib/account-summary.service.ts';
import { requireSession } from '#/lib/session.server.ts';

export const loader = defineHandler(async (c) => {
  const { user } = requireSession({ c });
  const profile = await findAccountSummary({ userId: user.id });

  if (!profile) throw new HTTPException(404);

  return { profile };
});
```

Keep the existing `Props = InferProps<typeof loader>` and `head` exports, and merge imports when replacing the file's earlier loader. The new props are `{ profile }`, rather than `{ name }`.

## 3. Render the Data

Update the component to accept `profile`:

```tsx
import { useTranslations } from '@kit/i18n/react';
import { PageBody } from '@kit/ui/page';

import { AppPageHeader } from '#/components/app-page-header.tsx';
import type { Props } from './index.server';

export default function AccountSummaryPage({ profile }: Props) {
  const t = useTranslations('app.accountSummary');

  return (
    <>
      <AppPageHeader />
      <PageBody>
        <dl>
          <dt>{t('name')}</dt>
          <dd>{profile.name}</dd>
          <dt>{t('email')}</dt>
          <dd>{profile.email}</dd>
        </dl>
      </PageBody>
    </>
  );
}
```

Everything returned by a loader is sent to the browser, including fields the JSX never uses. Do not return password hashes, access tokens, private settings, database clients, or an entire session object. Return a deliberate projection like the one above.

## Query Strings and Route Parameters

Validate query parameters with `withValidator` before using them for pagination, filtering, or sorting:

```ts
import * as z from 'zod';

const listQuery = z.object({
  page: z.coerce.number().int().min(1).max(10000).default(1),
});

export const loader = defineHandler.withValidator({ query: listQuery })(
  async (c, { query }) => {
    const { user } = requireSession({ c });
    return { page: query.page, viewerId: user.id };
  },
);
```

This separate example demonstrates parsing only. A real list service takes the validated page and session-derived owner id, applies a bounded limit and stable ordering, and returns its rows. Do not load an entire table and paginate in React. For UUID route parameters, validate the id with `z.uuid()` before querying.

## Slow Data and Parallel Reads

Await independent service calls with `Promise.all` when the page needs both before rendering. If a secondary value can arrive later, use `defer()` from `void` in the loader; React reads the resulting promise with `use()` beneath `<Suspense>`. Authenticate before creating the deferred callback, and capture only the owner ids and data it needs.

A deferred rejection is an error, not an empty result. Give the slow section a loading state and an error boundary when the rest of the page should remain usable. For your first feature, a normal awaited loader is usually enough.

## Errors, Freshness and Caching

- A scoped lookup returning `null` can become `HTTPException(404)`; a list with no rows normally returns an empty array.
- Let unexpected database failures reach the error handling path. Returning an empty array on a database failure makes an outage look like successful data loss.
- A successful page action that returns nothing reruns the loader. A redirect starts a new request and refreshes middleware-owned shared data too.
- Signed-in pages are private and not stored in the shared edge cache. Keep user or organization data out of public ISR and shared response caches.

Call services directly from loaders. Use [API Routes](./api-routes) when the browser or another client needs an endpoint. TanStack Query is available for client caching and repeated reads, but the initial page load does not need a `useEffect` fetch.

---

**Next:** [Save a Form →](./mutations-and-forms)
