onBeforeRoute() hook

The onBeforeRoute() hook provides full control over routing.

It is usually used for internationalization:

export { onBeforeRoute }

async function onBeforeRoute(pageContext) {
  const { urlWithoutLocale, locale } = extractLocale(pageContext.urlOriginal)
  return {
    pageContext: {
      locale,
      urlLogical: urlWithoutLocale
    }
  }
}

We can also use it to implement a custom router.

⚠
For use cases other than i18n, open a GitHub ticket or reach out on Discord: onBeforeRoute() is purposely limited but the limitations can be lifted in order to unlock new capabilities.

Example:

TypeScript

export { onBeforeRoute }

import type { OnBeforeRouteAsync } from 'vike/types'

const onBeforeRoute: OnBeforeRouteAsync = async (pageContext): ReturnType<OnBeforeRouteAsync> => {
  const { urlWithoutLocale, locale } = extractLocale(pageContext.urlOriginal)
  return {
    pageContext: {
      locale,
      urlLogical: urlWithoutLocale
    }
  }
}
⚠
Don't omit ReturnType<OnBeforeRouteAsync> (don't write const onBeforeRoute: OnBeforeRouteAsync = async (pageContext) => {), otherwise TypeScript won't strictly check the return type for unknown extra properties: see this TypeScript playground and issue.

See API > pageContext > Typescript for more information on how to extend pageContext with your own extra properties.