@k8ordo/router

Base path

How to serve the app below a base path, such as https://example.com/docs/. The route table stays written from /, and the router adds and removes the base path.

On this page

Vite’s base

vite.config.ts
import react from '@vitejs/plugin-react';
import { defineConfig } from 'vite';

export default defineConfig({
  base: '/docs/',
  plugins: [react()],
});

Set the base path with Vite’s base. The router reads it from import.meta.env.BASE_URL.

The route table does not change. The /products page stays /products in the table and is /docs/products in the address bar.

ts
href('/products'); // '/docs/products'
href('/'); // '/docs/'

href and navigateTo put the base path in front of the URL they build. So href returns a string, not a path in the route table.

Which URLs get the base path under @k8ordo/framework is covered in Deployment.

Warning

Pitfall

Passing the URL href returned to @k8ordo/state’s href adds the base path twice. See Links in the @k8ordo/state guide.

Paths you read

ts
// at /docs/products
usePathname(); // '/products'

usePathname returns the path without the base path: /products at /docs/products. What comes back compares directly with the route table’s patterns.

useMatch and <Router> also match the route table against the path without the base path.

<Router> does not match a URL outside the base path, whatever the route table says. The browser navigates to it as usual.

withBase and withoutBase

ts
withBase('/products'); // '/docs/products'
withoutBase('/docs/products'); // '/products'
withoutBase('/docs'); // '/'
withoutBase('/elsewhere'); // null
withBase('/products', '/docs/'); // '/docs/products'
Code Vite does not process passes the base path as the second argument

withBase and withoutBase let your own code add and remove the base path the way the router does. withoutBase returns null for a path outside the base path. The base path itself, /docs, becomes / with or without its trailing slash.

Code that Vite does not process has no import.meta.env to read the base path from.

A relative base such as ./ names no path, so neither function adds or removes anything.

k8ordo

React libraries that use Baseline features without holding back.