Route Strings & Route Functions

By default, vite-plugin-ssr does Filesystem Routing:

FILESYSTEM                  URL
pages/index.page.js         /
pages/about.page.js         /about
pages/faq/index.page.js     /faq

For advanced routes we define so-called "Route Strings" and "Route Functions" in .page.route.js files.

// /pages/product.page.route.js

// This file defines the route of `/pages/product.page.js`

// A Route String enables to easily define a parameterized route
export default '/product/:productId'
// `productId` is available at `pageContext.routeParams.productId`
// /pages/product-edit.page.route.js

// This file defines the route of `/pages/product-edit.page.js`

import partRegex from 'part-regex'

// A Route Function enables full programmatic flexibility
export default async (pageContext) => {
  const { url } = pageContext
  // Only URLs like `/product/[0-9]+/edit`
  if (!partRegex`/product/${/[0-9]+/}/edit`.test(url)) {
    return false
  }

  // Route Functions enable Route Guards.
  // `pageContext.user` is defined in the server middleware, see https://vite-plugin-ssr.com/auth
  if (!pageContext.user.isAdmin) {
    return false
  }

  // Only if there is a product matching `productId`
  const productId = url.split('/')[2]
  const product = await db.fetchProduct(productId)
  if (!product) {
    return false
  }

  return {
    // We make `product` available as `pageContext.routeParams.product` so we can
    // access it anywhere, see https://vite-plugin-ssr.com/pageContext-anywhere
    routeParams: {
      product,
    }
  }
}

See also:

Edit this page