---
name: routes-and-visibility
description: >-
  Add a route file and declare its settings: definePage with its visibility
  (LOGGED_IN_USERS, NON_LOGGED_IN_USERS and customGroups) and its title,
  guardRoute or assertRouteAccess in beforeLoad, pageHead in head, isAuthorized
  and checkAccess anywhere, rendering an access error, and the lint rules that
  require the declaration. Search engines and link previews: the seo setting, a
  typed head for record pages, readable record addresses with recordSlug,
  jsonLdScript, robotsTxt, sitemapXml and recordImage.
metadata:
  type: sub-skill
  library: softr-sdk
  library_version: 1.23.0
---

**Boundary.** `definePage`, `pageHead`, `jsonLdScript`, `recordSlug`, `recordIdFromSlug`, the access functions and the error predicates come from `@softr/sdk` and work anywhere. `robotsTxt`, `sitemapXml` and `recordImage` come from `@softr/sdk/server` and belong in a route's `server` handlers.

# Route visibility

Every route file in a Softr app declares its settings: who may see it, its title and its SEO tags. Softr reads them out of the source text without executing it and shows them in Softr Studio, where the app owner sees every route and its audience and can change them. That is why the rules below are strict: a setting Softr cannot read is a setting Studio cannot show.

## Setup

Every route file, without exception, looks like this:

```tsx
import { createFileRoute } from '@tanstack/react-router'
import { definePage, guardRoute, pageHead } from '@softr/sdk'

const pageSettings = definePage({
  visibility: { userGroupTypes: ['LOGGED_IN_USERS'] },
  title: 'Billing',
})

export const Route = createFileRoute('/_app/billing')({
  beforeLoad: guardRoute(pageSettings),
  head: pageHead(pageSettings),
  component: Billing,
})

function Billing() {
  return <h1>Billing</h1>
}
```

The route's settings are one `definePage` call at module scope, with an inline object literal as its argument. It always states `visibility`, and a page states its `title` too. `beforeLoad` applies the visibility, and `head` renders the title and the SEO tags.

These constraints hold, because Softr reads the file rather than running it:

- The call must initialise a top-level `const`.
- The import must be a direct named import from `@softr/sdk`.
- A route file has one `definePage`. The route names it in `beforeLoad` and in `head`. A page imported from elsewhere is rejected.
- Every value inside the literal is written there too. A group id taken from a `const`, a spread or an import still type-checks, but Studio can no longer change that setting. Repeat the id on each route, even when two routes share it.
- A head setting that depends on the route's data is a function of its head context: `title: ({ loaderData }) => loaderData?.name`. For typed loader data, write `head` after `loader` instead, as [Search engines and link previews](#search-engines-and-link-previews) shows.
- Never state `visibility` on `__root.tsx`. The root cannot carry an audience, so a rule there would gate nothing while looking like it does. Its `definePage` holds the app-wide head defaults only. Put the rule on a layout below the root instead.

`userGroupTypes` is a set, so a rule names one audience or several:

```ts
visibility: { userGroupTypes: ['NON_LOGGED_IN_USERS', 'LOGGED_IN_USERS'] }  // everyone, signed in or not
visibility: { userGroupTypes: ['NON_LOGGED_IN_USERS'] }                     // signed-out only: login, signup
visibility: { userGroupTypes: ['LOGGED_IN_USERS'] }                         // any signed-in visitor
visibility: {                                                               // those groups only
  userGroupTypes: ['LOGGED_IN_USERS'],
  customGroups: ['00000000-0000-0000-0000-00000000000a'],
}
visibility: {                                                               // signed-out visitors AND those groups
  userGroupTypes: ['NON_LOGGED_IN_USERS', 'LOGGED_IN_USERS'],
  customGroups: ['00000000-0000-0000-0000-00000000000a'],
}
```

Everyone is both audiences, as in the first line above. A set names each audience at most once and is never empty — the type and the build both reject one that does not. `customGroups` never stands alone: it narrows the `LOGGED_IN_USERS` half of the set, so the rule still names that half, and one without `userGroupTypes` is a type error. Absent or empty it means **any** signed-in visitor, not "nobody".

Take every id in `customGroups` from `docs/user-groups.md`, which lists each group the app has with its name and id. An id the app does not have is a type error.

**`visibility` guards the page, not the server functions it calls.** A call can reach them without the page and with any arguments, so the queries and mutations behind a page carry its groups in their own `permissions`. `permissions` decide who may run them, not which rows they reach: the `filter` of each query and mutation decides that, as [record-queries](../record-queries/SKILL.md#keep-each-visitor-to-their-own-records) shows.

## Core Patterns

### Guard a whole section with one layout route

```tsx
// src/routes/_app.tsx: guards every route under /_app
import { Outlet, createFileRoute } from '@tanstack/react-router'
import { definePage, guardRoute, pageHead } from '@softr/sdk'

const pageSettings = definePage({ visibility: { userGroupTypes: ['LOGGED_IN_USERS'] } })

export const Route = createFileRoute('/_app')({
  beforeLoad: guardRoute(pageSettings),
  head: pageHead(pageSettings),
  component: () => <Outlet />,
})
```

A pathless layout like this one is not a page, so it needs no `title`.

The whole match chain runs, so a layout guards everything beneath it. Sibling routes do not guard each other. `/admin/index.tsx` does nothing for `/admin/users.tsx` unless an `admin.tsx` layout exists. A route below a guarded layout declares and guards its own settings too.

A thrown error renders in place of the guarded route's component. A shell layout guarded with `LOGGED_IN_USERS`, where `unauthenticated` redirects, sends a signed-out visitor away before anything renders there. A rule that can _throw_ — a `customGroups` rule with `forbidden` set to throw — should not sit on the shell itself, or the error replaces the nav and chrome. Put it on a layout inside the shell, or on the restricted routes, so the error renders inside the chrome.

### Change what a denied visitor gets

`guardRoute` takes per-reason overrides as a second argument. A bare string is shorthand for a redirect.

```ts
beforeLoad: guardRoute(pageSettings, { unauthenticated: '/marketing/sign-up' }),
beforeLoad: guardRoute(pageSettings, { forbidden: { strategy: 'throw' } }),
beforeLoad: guardRoute(pageSettings, {
  unauthenticated: { strategy: 'redirect', to: '/marketing/sign-up' },
  forbidden: { strategy: 'throw' },
}),
```

The long redirect form and the bare string do the same thing.

Every app declares where a denied visitor goes in `softr.json`, at the app root, and every app has one:

```json
{
  "$schema": "./node_modules/@softr/sdk/schema/softr.schema.json",
  "auth": {
    "routes": {
      "login": { "path": "/login", "redirectParam": "redirect" },
      "resetPassword": { "path": "/reset-password", "tokenParam": "token" },
      "acceptInvitation": { "path": "/accept-invitation", "tokenParam": "token" },
      "magicLink": { "path": "/magic-authentication", "tokenParam": "magic-token" }
    },
    "guard": {
      "unauthenticated": "/login",
      "alreadyAuthenticated": "/",
      "forbidden": { "strategy": "throw" }
    }
  }
}
```

Every key is required, because nothing fills in one the file leaves out:

| Reason | Condition | Goes to |
| --- | --- | --- |
| `unauthenticated` | Route needs a visitor, none present | `guard.unauthenticated` |
| `forbidden` | Signed in, in none of the named groups | `guard.forbidden` |
| `alreadyAuthenticated` | Signed-in visitor on a signed-out-only route | `guard.alreadyAuthenticated` |

`guard.unauthenticated` is where signed-out visitors go. It is usually the same as `routes.login.path`, but it can be another page, such as a public landing page. Every `unauthenticated` redirect, an override's included, carries the page they wanted under `routes.login.redirectParam`. The login page reads it back with `toReturnPath`. See [auth/SKILL.md](../auth/SKILL.md).

`auth.routes` names the app's sign-in pages. To move one, rename its route file and edit its `path` in `auth.routes` to match. When `guard.unauthenticated` points at the login page, edit it too.

That file covers every route at once; a route's own overrides win over it. A rule naming both audiences with no `customGroups` admits everyone, so it never redirects and never throws. Only `strategy: 'throw'` reaches an `errorComponent`. A redirect navigates away and the route never renders.

### Render the error in place

```tsx
import { createFileRoute } from '@tanstack/react-router'
import { definePage, guardRoute, isAccessError, isForbiddenError, pageHead } from '@softr/sdk'

const pageSettings = definePage({
  visibility: {
    userGroupTypes: ['LOGGED_IN_USERS'],
    customGroups: ['00000000-0000-0000-0000-00000000000a'],
  },
  title: 'Billing',
})

export const Route = createFileRoute('/_app/billing')({
  beforeLoad: guardRoute(pageSettings),
  head: pageHead(pageSettings),
  component: Billing,
  errorComponent: ({ error }: { error: unknown }) => {
    if (isForbiddenError(error)) return <UpgradePrompt />
    if (isAccessError(error)) return <NoAccess />
    return <SomethingWentWrong />
  },
})
```

The error carries a `type` discriminant and its `reason`, nothing else. It never names the groups the route wanted, which would hand that list to the one visitor who was just turned away.

Use the predicates: `isAccessError` for any of the three, and `isUnauthenticatedError`, `isForbiddenError`, `isAlreadyAuthenticatedError` for one each. The error is plain data rather than an `Error` subclass, so `instanceof` never matches and there is no `message` to read. That is also why the parameter is annotated `error: unknown`. The router types it as `Error`, and the wider annotation is what lets the predicates narrow it. Leave it as it is.

### Run the check and then keep going

`guardRoute` covers almost everything. When a route needs its own logic afterwards, `assertRouteAccess(pageSettings, opts)` applies the same rule to the whole `beforeLoad` argument and throws the same access error, using the default behaviour for each reason. It takes no overrides.

It also narrows `opts.context.user` for the rest of the handler, where the set names one audience and no other: `User` under `['LOGGED_IN_USERS']`, `null` under `['NON_LOGGED_IN_USERS']`. A set naming both admits either kind of visitor, so it narrows to neither. `guardRoute` cannot, because it hands `beforeLoad` a function rather than running inside one.

```tsx
import { createFileRoute, redirect } from '@tanstack/react-router'
import { assertRouteAccess, definePage, pageHead } from '@softr/sdk'

const pageSettings = definePage({
  visibility: { userGroupTypes: ['LOGGED_IN_USERS'] },
  title: 'Reports',
})

export const Route = createFileRoute('/_app/reports')({
  beforeLoad: (opts) => {
    assertRouteAccess(pageSettings, opts)
    if (opts.context.user.email.endsWith('@example.com')) throw redirect({ to: '/internal' })
  },
  head: pageHead(pageSettings),
  component: Reports,
})
```

Take `opts` whole. A `context` destructured in the parameter list does not narrow.

`guardRoute` and `assertRouteAccess` throw router redirects, so they belong in a route and nowhere else. That is what `Route` in their names marks.

### Search engines and link previews

With `"seo": { "enabled": true }` in `softr.json`, `pageHead` gives every page what search engines and link previews expect when the page states nothing else: a canonical link to the page's own address, `og:url`, `og:title` and `og:description` from its `title` and `description`, and a full address for a `socialImage` path. A setting the page states wins. The canonical address keeps only the `page` parameter of the query, so a filtered list points at the list.

A public page states a `description` of one or two sentences, about 155 characters at most. A record page takes its title and description from the record. Write `head` after `loader`, so `ctx.loaderData` has the loader's type, and spread the page's settings into `pageHead`:

```tsx
import { createFileRoute } from '@tanstack/react-router'
import { definePage, guardRoute, pageHead } from '@softr/sdk'
import { loadBike } from '#/server/bikes.ts'

const pageSettings = definePage({
  visibility: { userGroupTypes: ['NON_LOGGED_IN_USERS', 'LOGGED_IN_USERS'] },
  title: 'Bike | Lisbon Cycle Hire',
  description: 'A bike to rent by the day in Lisbon.',
})

export const Route = createFileRoute('/bikes/$bikeId')({
  beforeLoad: guardRoute(pageSettings),
  loader: ({ params }) => loadBike({ data: params.bikeId }),
  head: (ctx) =>
    pageHead({
      ...pageSettings,
      title: ctx.loaderData ? `${ctx.loaderData.fields.name} | Lisbon Cycle Hire` : pageSettings.title,
      description: ctx.loaderData?.fields.summary ?? pageSettings.description,
    })(ctx),
  component: BikePage,
})
```

The literals in `definePage` stay as the fallbacks: Studio shows and edits them, and they render when the loader has no record. Never put a record's attachment URL in `socialImage`: it expires, and link previews keep the URL for much longer. Point `socialImage` to a `recordImage` route instead, see below.

A record page's address holds the record's name and its id in one segment, such as `/bikes/belem-coast-cruiser--2d0grM08PZDtDs`. `recordSlug(id, name)` makes the segment from the value of the record's name field, and `recordIdFromSlug(segment)` reads the id back. The route keeps its one parameter, so a link with a plain id still opens the page. Redirect an old name or a plain id to the current address, so each record has one address. Every link to the page, and its sitemap `path`, uses `recordSlug` too:

```tsx
import { notFound, redirect } from '@tanstack/react-router'
import { recordIdFromSlug, recordSlug } from '@softr/sdk'

loader: async ({ params }) => {
  const bike = await loadBike({ data: recordIdFromSlug(params.bikeId) })
  if (bike === null) throw notFound()
  const slug = recordSlug(bike.id, bike.fields.name)
  if (params.bikeId !== slug) throw redirect({ to: '/bikes/$bikeId', params: { bikeId: slug }, statusCode: 301 })
  return bike
},
```

Structured data goes into `head` with `jsonLdScript`, next to every tag `pageHead` renders. It keeps record text from closing the script tag, so never write the script entry by hand:

```tsx
head: (ctx) => ({
  ...pageHead(pageSettings)(ctx),
  scripts: [jsonLdScript({ '@context': 'https://schema.org', '@type': 'Organization', name: 'Lisbon Cycle Hire' })],
}),
```

`robotsTxt` and `sitemapXml` from `@softr/sdk/server` answer `/robots.txt` and `/sitemap.xml`. Each is a route file with only a `server` handler and no page settings:

```ts
// src/routes/sitemap[.]xml.ts
import { createFileRoute } from '@tanstack/react-router'
import { recordSlug } from '@softr/sdk'
import { sitemapXml } from '@softr/sdk/server'
import { bikesQuery } from '#/server/bikes.ts'

export const Route = createFileRoute('/sitemap.xml')({
  server: {
    handlers: {
      GET: sitemapXml({
        records: [
          {
            query: bikesQuery,
            path: (bike) => `/bikes/${recordSlug(bike.id, bike.fields.name)}`,
            lastModified: (bike) => bike.fields.updatedAt ?? bike.fields.createdAt,
          },
        ],
      }),
    },
  },
})
```

The sitemap finds its pages in the app's routes, so a page that becomes public or private joins or leaves it with no code change. It lists a page with no path parameter when its `guardRoute` and that of each layout above it admit both `NON_LOGGED_IN_USERS` and `LOGGED_IN_USERS` with no `customGroups`, and no page turns `searchEngineIndexing` off. Write `searchEngineIndexing` as `true` or `false`: a page that sets it with a function is left out. A page whose `beforeLoad` does more than `guardRoute`, such as one that calls `assertRouteAccess`, is left out. A `pages` list of paths replaces this search, and then no record path is checked.

`records` uses the same query as the record page, so the sitemap lists exactly the records that page shows. Without `pages`, a record's path is listed only when its page passes the same check. `lastModified` gives the sitemap the date the record last changed. Select the table's "last modified" and "created" fields in the query, and fall back to the created date: the "last modified" field is empty for a record that nobody changed after it was made. A new record shows in the sitemap within a day, with no new publish. A sitemap holds up to 50,000 addresses: the pages first, then the records of each source in order. `robots.txt` is `GET: robotsTxt()` in `src/routes/robots[.]txt.ts`. A file of the same name under `public/` wins over either route.

`recordImage` answers a route with the image in one field of a record, for link previews and search engines. Its address does not expire, so a shared link keeps its picture. The query must be open to `NON_LOGGED_IN_USERS`, and the route has one path parameter, the record id or its `recordSlug`. The page's own `<img>` keeps the URL from its loader:

```ts
// src/routes/images/bikes/$bikeId.ts
import { createFileRoute } from '@tanstack/react-router'
import { recordImage } from '@softr/sdk/server'
import { bikesQuery } from '#/server/bikes.ts'

export const Route = createFileRoute('/images/bikes/$bikeId')({
  server: { handlers: { GET: recordImage({ query: bikesQuery, field: 'photo' }) } },
})
```

In its typed head, the record page then sets `socialImage` to the image route's path for the record, such as `/images/bikes/2d0grM08PZDtDs`. The image route answers 404 for a record a signed-out visitor cannot read, a field with no image, and an image too large for a link preview.

### Check a rule without a throw

`isAuthorized(rule, context)` and `checkAccess(rule, context)` answer the same question and throw nothing, so they work anywhere: in a loader, a component or a server function. They take a rule from `defineVisibility`, not a page. Use `isAuthorized` for the same narrowing of `context.user` as `assertRouteAccess`, and `checkAccess` to branch on why: it returns `{ ok: true } | { ok: false, reason }`. All of them are synchronous and make no request.

```tsx
import { defineVisibility, isAuthorized, useCurrentUser } from '@softr/sdk'

const staffOnly = defineVisibility({
  userGroupTypes: ['LOGGED_IN_USERS'],
  customGroups: ['00000000-0000-0000-0000-00000000000a'],
})

function StaffNote() {
  const context = { user: useCurrentUser() }
  if (!isAuthorized(staffOnly, context)) return null
  return <p>Signed in as staff: {context.user.email}</p>
}
```

To show or hide a part of a page, `Audience` is simpler: see [region-visibility/SKILL.md](../region-visibility/SKILL.md).

## References

- [current-user/SKILL.md](../current-user/SKILL.md): reading the visitor a guard has just admitted
- [record-queries/SKILL.md](../record-queries/SKILL.md): a guard covers the page, not the server function behind it
- [auth/SKILL.md](../auth/SKILL.md): `NON_LOGGED_IN_USERS` and the sign-in flow it fronts
- [region-visibility/SKILL.md](../region-visibility/SKILL.md): showing part of a page to some of the visitors the route admits
