Redirects

Editor-defined redirects

Redirects field in Sanity Studio

How it works

The redirect schema

Redirects are set-up in Sanity Studio, in the Global Settings singleton (refer to app/sanity/schemas/documents/settings.ts)

Its destination is a regular link, like any other in the toolkit, and is resolved with getLinkProps (from app/routing/urls.ts).

Query Sanity for the redirect target in the loader

app/routing/routeLoader.ts parses redirects and acts on them:

app/routing/routeLoader.ts#getDocForRoute
// Simplified for clarity
const { redirectTarget } = await client.fetch(
  /* groq */ `{
    "redirectTarget": *[_id == $settingsId][0].redirects[source in $routePaths][0]{
      source,
      destination {
        ${LINK_FRAGMENT}
      },
      permanent,
    }
  }`,
  {
    routePaths: getPathVariations(routePath),
    settingsId: COMMON_IDS.settings,
  },
)
 
const redirect = redirectTarget?.destination
  ? {
      to: getLinkProps(target.destination)?.href,
      permanent: target.permanent,
    }
  : undefined

If a target exists, redirect users to it

We use Remix's own redirect method:

app/routing/routeLoader.ts
if (redirectRoute?.to) {
  return redirect(redirectRoute.to, {
    status: Boolean(redirectRoute.permanent) ? 308 : 307,
  })
}