# Pages behind a sign-in

A Récit site is prerendered: every page is an HTML file written at build time, the same for every
visitor. The **application mode** adds pages that are not: their routes are rendered for each
request, after a **guard** that decides who may enter, with **data** read for that request only.
Nothing a visitor sees ever lands in a built file.

It goes through one plugin in `recit.config.ts`. A site without it builds exactly the same files as
before.

:::caution{title="Preview: private package"}

The application mode is part of the site framework (`@recit/site`), which stays private for now.
This page is the reference of a **preview**, outside the 1.0 contract
([Stability](/documentation/reference/stability)). A guarded page needs a server that renders the
site, which is itself experimental (`recit-site build --experimental-ssr`).

:::

## When to use it

- **A page for signed-in people only**: an account, a team's notes, a dashboard of one customer.
- **A page whose content depends on who reads it**, read from an API at each visit.

For a page everyone may read, write Markdown as usual. For a small lock over a whole static site,
with no server, see [Protect a site with a password](/documentation/configuration/password): it is a
modal in the browser, not a guard.

## The plugin

An application is an `AppPlugin`, exported by `@recit/site/plugins`, in the `plugins` of the site:

```ts title="recit.config.ts"
import { defineConfig } from "recit/config";
import { loremAppPlugin } from "./app/plugin.js";

export default defineConfig({
  site: { title: "Lorem App Site" },
  docs: { files: ["./docs/**/*.md"] },
  navigation: [{ type: "doc", file: "index" }],
  plugins: [loremAppPlugin()],
});
```

It has three parts, of which only the routes are required:

| Part           | Receives                    | Returns                             | At prerender             | At each request                 |
| -------------- | --------------------------- | ----------------------------------- | ------------------------ | ------------------------------- |
| `getAppRoutes` | nothing                     | React Router routes                 | one shell per root route | the route, after the guard      |
| `guard`        | the request, the params     | `{ allow: true }` or `{ redirect }` | never called             | called, cookies included        |
| `createData`   | the request (on the server) | the value `useAppData` reads        | never called             | a new value, in a React context |

```tsx title="app/plugin.tsx"
import { useAppData } from "@recit/site/app";
import type { AppPlugin, RouteObject } from "@recit/site/plugins";
import { createLoremBackend, type LoremBackend } from "./backend.js";
import { hasLoremSession, LOGIN_PATH, loginRedirect, NOTES_PATH } from "./session.js";

const Loading = () => <p>Loading…</p>;

const appRoutes = (): RouteObject[] => [
  { path: LOGIN_PATH, element: <LoginPage />, HydrateFallback: Loading },
  { path: NOTES_PATH, element: <NotesPage />, HydrateFallback: Loading },
];

export const loremAppPlugin = (): AppPlugin<LoremBackend> => ({
  getAppRoutes: appRoutes,
  guard: ({ request }) => {
    if (new URL(request.url).pathname === LOGIN_PATH) return { allow: true };
    return hasLoremSession(request) ? { allow: true } : { redirect: loginRedirect(request) };
  },
  createData: () => createLoremBackend(),
});
```

The whole example, with its sign-in page and its test backend, is `examples/site-app`.

## The routes

`getAppRoutes` returns [React Router](https://reactrouter.com) routes, built by a function, never at
module level. They are never prerendered, and never enter the site's plan, its search index, its
`llms.txt` or its Markdown export.

- **Give every root route a `HydrateFallback`**: what shows while the route loads. The build writes
  one **shell** per root route, the site's layout and this fallback, marked `noindex`, with no guard
  and no data. It sits at an address its route matches (`/teams/:teamId` gives
  `/teams/__shell.html`), and the host serves it for every address of the route. A child route uses
  its parent's shell.
- **The build stops** when a shell would land on a prerendered page, or when two root routes share
  one shell.
- `handle: { layout: "none" }` on a route that draws its own frame; without it, the page sits in the
  site's layout, header and sidebar included.

## The guard

`guard` runs before the loader and the action of every route of the plugin:

- **On the server**, with the real request, cookies included; `{ redirect: "/login?returnTo=…" }`
  leaves as a `302`.
- **In the browser**, at each navigation and when a shell first loads.

It keeps nothing between two calls. A page or a redirect of the application is sent with
`Cache-Control: private, no-store`. A shell is never hydrated: the browser replaces it with a fresh
render of the route, after its guard.

Put public pages of the application (sign-in, a password link, an error page) either before the
check in the guard, as the example does for `/login`, or in a second plugin with no `guard`. Bring
the visitor back where they were going: pass the path in `returnTo`, and accept only a path of the
site (`/notes`, never `//example.com`).

The guard decides who sees a page, not what the data says: an API should answer « not found » to
someone outside the resource, and the page should show it that way.

## The data

`createData` gives one value **per request on the server** and **one per tab in the browser**. A
page reads it with `useAppData<Data>()` from `@recit/site/app`:

```tsx title="app/plugin.tsx"
const NotesPage = () => {
  const backend = useAppData<LoremBackend>();
  const { data, isPending, isError } = useQuery({
    queryKey: ["lorem-notes"],
    queryFn: () => backend.listNotes(),
  });
  // …
};
```

Never keep anything of a visitor in a module variable, a top-level query client or a shared
singleton: the same server answers every visitor. A prerendered page has no data (`createData` is
not called at build time); the browser mounts it after hydration.

## Hosting

A guarded page needs a server: the guard reads the request, which a static file cannot. Build the
site for server rendering, with one of the adapters of the site framework:

```bash
recit-site build --experimental-ssr --adapter node   # or cloudflare, vercel, lambda
```

`node` is the default: it writes a server (Hono) that serves the prerendered pages and renders the
application's routes. A site of its own can replace that entry with a `recit.server.ts` next to its
`recit.config.ts`.

A static build still serves the public pages and the shells, so a visitor sees the loading state,
then the guard runs in the browser: enough for a demonstration, never for a page whose content must
stay private.

## Test it

- `e2e/site-app.spec.ts` is the model: the public page, a visit without a session sent to sign in
  and back, a visit with a session, and no application route in the prerendered files.
- Give each page component a story whose `play` reads the page by roles and names, with its data
  mocked.

## See also

- [Protect a site with a password](/documentation/configuration/password), the lock with no server.
- [Récit account](/documentation/reference/account), the platform's own application.
- [`recit.config` reference](/documentation/configuration/recit-config#a-site), the site options.
