> For the complete Lynkow documentation index in agent-friendly format, see [llms.txt](/llms.txt).

# Catch-all Routes & Path Resolution

**Publié le** : 2026-11-30
**Catégorie** : Advanced

> **Reference** - This guide is a tutorial. For exhaustive, always-current signatures and field lists, see the auto-generated reference:
> 
> - SDK: [`PathsService`](/sdk/services/sdk-paths-service)
> - Types: [SDK Types](/sdk/types)
> - API: [Storefront: Content](/storefront-api/storefront-content), [Storefront: Commerce](/storefront-api/storefront-commerce)

In nested blog URL mode, `/blog/guides` can be a category and `/blog/guides/getting-started` an article. One `[...slug]` route covers both: it asks `paths.resolve()` what a path is and renders that. The route keeps working when an editor moves a category or changes the blog URL mode.

## Prerequisites

- A client in `lib/lynkow.ts`, with a `publishableKey` on a commerce site ([Add Lynkow to an Existing Project](/sdk/getting-started/existing-project))
- Article and category rendering from [Build a Blog with Next.js](/sdk/getting-started/blog-nextjs)
- On a multi-language site, the `@lynkow/next` setup of [Guide 6](/sdk/features/i18n#6-locale-routing-with-the-nextjs-proxy)

## Static Generation with `generateStaticParams`

`paths.list()` returns the article and category paths of one locale, each as a full `path` such as `/blog/guides/getting-started`. In flat mode it lists the root categories only. Split each path into the `slug` array a root catch-all expects:

```tsx
// app/[...slug]/page.tsx
import { lynkow } from '@/lib/lynkow'

export async function generateStaticParams() {
  const { paths } = await lynkow.paths.list()
  return paths.map((p) => ({ slug: p.path.split('/').filter(Boolean) }))
}
```

A path left out of `generateStaticParams` still renders on its first request, unless you set `dynamicParams` to `false`.

### Commerce pages and other locales

`paths.list({ include: 'commerce' })` appends the public URLs of the published products and of the visible product categories and collections, with `type` `'product'`, `'product_category'` or `'product_collection'`. It needs no publishable key.

Without a locale, a multi-language site lists its default locale's paths only, so call it once per locale. With the `@lynkow/next` setup, `lynkow(locale)` sends its locale with every read, and the catch-all sits under `app/[locale]`:

```tsx
// app/[locale]/[...slug]/page.tsx
import { lynkow, paths, siteLocales } from '@/lib/config'

export async function generateStaticParams() {
  const { locales } = await siteLocales.get()
  const params: Array<{ locale: string; slug: string[] }> = []

  for (const locale of locales) {
    const { paths: list } = await lynkow(locale).paths.list({ include: 'commerce' })
    // The locale's prefix: '' for the default locale, '/fr' for French
    const prefix = paths.localePath(locale, '/').replace(/\/$/, '')

    for (const p of list) {
      // A URL served in another language renders on request
      if (p.isFallback) continue
      // Drop the prefix: the [locale] segment of the route carries it
      const slug = paths.fromApiPath(p.path, locale).slice(prefix.length).split('/').filter(Boolean)
      if (slug.length > 0) params.push({ locale: locale.toLowerCase(), slug })
    }
  }

  return params
}
```

A locale read lists, for each entity with no translation in that locale, its fallback URL: the locale's prefix with its source slug, flagged `isFallback: true`, with `locale` the language its text is served in. Pass `fallback: false` to drop those entries from the answer. A product hidden in a locale is not listed there.

## Path Resolution

`paths.resolve(path)` returns a union discriminated by `type`:

- `'content'`: `content`, the full article.
- `'category'`: `category`, and `contents`, its first 500 articles with pagination `meta`.
- `'product'`, `'product_category'`, `'product_collection'`: a commerce page ([Commerce Paths](#commerce-paths)).
- `'redirect'`: a redirect covers the path ([404 Handling](#404-handling)).

Every hit except a redirect also carries `locale`, the locale of the URL. Narrow with the `isContentResolve()`, `isCategoryResolve()` and `isRedirectResponse()` type guards, or on `type`. A path that matches nothing throws a `LynkowError` with status 404.

### Fallback URLs

On a multi-language site, an article or category with no translation in a locale still has a URL there, served in another language ([fallback contract](/sdk/features/i18n#fallback-contract)). It resolves only when the read carries a locale: without one, the lookup is exact and the fallback URL is a 404.

```typescript
// With a single client, pass the locale per call: paths.resolve(path, { locale: 'fr' })
const resolved = await lynkow('fr').paths.resolve('/fr/blog/product-launch')

if (isContentResolve(resolved) && resolved.content.isFallback) {
  // Served in resolved.content.locale, e.g. 'en'; requestedLocale is 'fr'
}
```

The fallback signals `locale`, `requestedLocale` and `isFallback` sit on `resolved.content` or `resolved.category`. The record's `alternates` array is empty, and an article's canonical is the default locale's URL (`content.canonicalUrl` when the site has a domain in Lynkow).

## Page Component

```tsx
// app/[...slug]/page.tsx (continued)
import type { Metadata } from 'next'
import { notFound } from 'next/navigation'
import { isCategoryResolve, isContentResolve, isLynkowError } from 'lynkow'

const PER_PAGE = 12

async function resolvePath(slug: string[]) {
  try {
    return await lynkow.paths.resolve('/' + slug.join('/'))
  } catch (error) {
    // Only a missing path is a 404: rethrow a network failure or a rejected key
    if (isLynkowError(error) && error.status === 404) notFound()
    throw error
  }
}

export async function generateMetadata({
  params,
}: {
  params: Promise<{ slug: string[] }>
}): Promise<Metadata> {
  const resolved = await resolvePath((await params).slug)
  if (isContentResolve(resolved)) {
    return { title: resolved.content.metaTitle || resolved.content.title }
  }
  if (isCategoryResolve(resolved)) return { title: resolved.category.name }
  return {}
}

export default async function CatchAllPage({
  params,
  searchParams,
}: {
  params: Promise<{ slug: string[] }>
  searchParams: Promise<{ page?: string }>
}) {
  const resolved = await resolvePath((await params).slug)

  if (isContentResolve(resolved)) {
    const { content } = resolved
    return (
      <article>
        <h1>{content.title}</h1>
        <div dangerouslySetInnerHTML={{ __html: content.body }} />
      </article>
    )
  }

  if (isCategoryResolve(resolved)) {
    // resolve() takes no page number: read the requested page with contents.list()
    const { page } = await searchParams
    const { data: articles } = await lynkow.contents.list(
      { category: resolved.category.slug, page: Number(page) || 1, limit: PER_PAGE },
      { locale: resolved.locale }
    )
    return (
      <section>
        <h1>{resolved.category.name}</h1>
        {articles.map((article) => (
          <a key={article.id} href={article.path}>{article.title}</a>
        ))}
      </section>
    )
  }

  notFound()
}
```

For full meta tags, see [Guide 7](/sdk/media-seo/seo-analytics). With `@lynkow/next`, `server.articleMetadata(resolved.content)` and `server.categoryMetadata(resolved.category)` build them, hreflang included ([Guide 6](/sdk/features/i18n#4-generate-hreflang-tags)).

On a multi-language site, the page sits at `app/[locale]/[...slug]/page.tsx`, gets its locale from `pageLocale()` of [Guide 6](/sdk/features/i18n#9-complete-i18n-layout-example), and resolves the URL as the visitor typed it: `lynkow(locale).paths.resolve(paths.localePath(locale, '/' + slug.join('/')))`.

## Commerce Paths

On a commerce site, `paths.resolve()` also recognises the public URL of a product, a product category and a collection, in every locale the site serves it in. The answer comes in one of two shapes, chosen by the SDK:

- **Record**, when the client has a `publishableKey`: the full entity under `product`, `productCategory` or `productCollection`, the one its single read returns, and its JSON-LD graph as `resolved.structuredData` at the top level. One request gives the page and its `<head>` what they need.
- **Pointer**, when the client has no key: `{ id, slug, path }` under the same key. Read the record with a keyed client.

Both shapes share the same `type`: tell them apart with `'structuredData' in resolved`. Add the branches before the final `notFound()`:

```tsx
// `catalog` is a client created with a publishableKey: on a commerce site, the one
// that resolved the path, so the record branch runs and no second read is made.

if (resolved.type === 'product') {
  const product =
    'structuredData' in resolved
      ? { ...resolved.product, structuredData: resolved.structuredData }
      : await catalog.products.getBySlug(resolved.product.id) // accepts the prod_... id
  return <ProductPage product={product} />
}

if (resolved.type === 'product_category') {
  const category =
    'structuredData' in resolved
      ? { ...resolved.productCategory, structuredData: resolved.structuredData }
      : await catalog.productCategories.getBySlug(resolved.productCategory.slug)
  const { data } = await catalog.products.list({ category: category.slug })
  return <ProductCategoryPage category={category} products={data} />
}

if (resolved.type === 'product_collection') {
  const collection =
    'structuredData' in resolved
      ? { ...resolved.productCollection, structuredData: resolved.structuredData }
      : await catalog.productCollections.getBySlug(resolved.productCollection.slug)
  const { data } = await catalog.products.list({ collection: collection.slug })
  return <ProductCollectionPage collection={collection} products={data} />
}
```

Each branch ends with the record and its `structuredData`: render the graph with `renderJsonLdGraph(product.structuredData?.graph)` ([Guide 16](/sdk/features/json-ld-cascade)). A category or collection page lists its products with `products.list()` either way. [Guide 18](/sdk/features/commerce-products) covers the catalog reads and the URL settings.

If the API rejects the client's publishable key, `resolve()` throws a `LynkowError` with `code` `'UNAUTHORIZED'` (status 401, `apiCode` `'STOREFRONT_KEY_REQUIRED'`) for a commerce URL, with no fallback to the pointer. Articles and blog categories still resolve. Map only a 404 to `notFound()`, so a revoked key does not show as "page not found" on every product.

### Exact URLs only

A commerce path resolves only when it is exactly the page's public URL in its locale: the locale's prefix (none for the default locale), that locale's URL segment, then the entity's slug in that locale. When products are nested under their category, the category's slug sits between the segment and the product slug. Any other form is a 404. A path under a commerce prefix that matches no commerce page falls through to the article and category resolution.

An entity with no translation in a locale resolves at its fallback URL, `/fr/produits/linen-shirt`, even when the request carries no locale. It carries `isFallback: true` and the locale served; the record also carries an empty `alternates` array and `canonicalPath`, the default locale's URL.

Two URLs of a commerce page answer a redirect instead: the source-slug URL once the entity has its own slug in that locale, and the default locale's prefixed form (`/en/products/linen-shirt`). Both are 301s, served by the proxy below.

## Redirect Handling in the Proxy

Lynkow serves the redirect rules you create in the dashboard (301, 302, 307 or 308), and redirects of its own: when a URL changes, and from a URL under the default locale's prefix to the unprefixed one. Serve them from `proxy.ts`, which Next.js 16 runs before a page renders: a page cannot choose the status code.

### With `@lynkow/next`

The `createLynkowProxy` of [Guide 6](/sdk/features/i18n#6-locale-routing-with-the-nextjs-proxy) serves every redirect with no code of yours. On each page request it looks up the path as the visitor typed it, and an unprefixed path also under the default locale's prefix. A rule you created wins over the redirects Lynkow creates. When the rule keeps the query string, the request's parameters are carried over, a parameter the target already names keeping its own value.

### A proxy of your own

```typescript
// proxy.ts
import { NextRequest, NextResponse } from 'next/server'
import { lynkow } from '@/lib/lynkow'

export async function proxy(request: NextRequest) {
  try {
    const redirect = await lynkow.paths.matchRedirect(request.nextUrl.pathname)

    if (redirect) {
      // `target` is a site-relative path or an absolute URL: this handles both
      const destination = new URL(redirect.target, request.url)

      if (redirect.preserveQueryString) {
        request.nextUrl.searchParams.forEach((value, key) => {
          if (!destination.searchParams.has(key)) destination.searchParams.append(key, value)
        })
      }

      return NextResponse.redirect(destination, redirect.statusCode)
    }
  } catch {
    // A failed lookup lets the request through to the page
  }

  return NextResponse.next()
}

export const config = {
  matcher: ['/((?!_next/|api/|.*\\.[\\w]+$).*)'],
}
```

`matchRedirect()` returns `null` when no redirect matches, else `{ source, target, statusCode, preserveQueryString }`. Pass the path in full: commerce segments and locale prefixes are part of what Lynkow matches. On a multi-language site, your proxy also has to rewrite an unprefixed path to your `[locale]` route, which `createLynkowProxy` does for you.

## 404 Handling

`paths.resolve()` throws a `LynkowError` with status 404 (`code` `'NOT_FOUND'`) when no article, category or commerce page matches and no redirect covers the path. The `resolvePath()` helper above maps that to `notFound()` and rethrows every other error ([Guide 12](/sdk/advanced/error-handling)).

A path a redirect covers resolves to `{ type: 'redirect', redirect: { target, statusCode, preserveQueryString } }` instead. The proxy has already served it, so a page rarely sees one, and it falls through to the final `notFound()`. To follow it from the page instead:

```typescript
import { notFound, permanentRedirect, redirect } from 'next/navigation'
import { isRedirectResponse } from 'lynkow'

const SITE_ORIGIN = new URL(process.env.NEXT_PUBLIC_SITE_URL!).origin
const pathOf = (url: string) => new URL(url, SITE_ORIGIN).pathname.replace(/\/+$/, '') || '/'

// In CatchAllPage, before the final notFound()
if (isRedirectResponse(resolved)) {
  const { target, statusCode } = resolved.redirect
  const path = '/' + (await params).slug.join('/')
  // A rule can point a path back at itself (`/*` to `/*`): answer 404 instead of looping
  if (new URL(target, SITE_ORIGIN).origin === SITE_ORIGIN && pathOf(target) === pathOf(path)) notFound()
  if (statusCode === 301 || statusCode === 308) permanentRedirect(target)
  redirect(target)
}
```

A rule such as `/*` to `/*` leads a path back to itself, so the snippet answers 404 when `target` is the asked path on your own origin. [Pages & Site Configuration](/sdk/features/pages-site-config) guards `pages.getByPath()` the same way.

Add a `not-found.tsx` next to the route for your own 404 page.

## Next Steps

- [Guide 6: Multi-language (i18n)](/sdk/features/i18n) - locale prefixes, the proxy and hreflang
- [Guide 18: Product Catalog](/sdk/features/commerce-products) - commerce pages and their URL settings
- [Guide 11: Webhooks & Cache Revalidation](/sdk/advanced/webhooks-revalidation) - refresh the pre-rendered paths on publish