Skip to content

Router

Metro UI provides class to create Router for SPA (single page application).

The Router class provides a simple way to create a router for your SPA application.

Metro UI already includes the Router library. You can use it without any additional installation, but if you want to use it in your project, you can install it with package manager:

Terminal window
npm install @olton/router

or use CDN:

<script type="module">
import Router from "https://esm.run/@olton/router";
</script>
import { Router } from "@olton/router";
const router = new Router()
router.addRoute("/", () => { console.log("Home page")})
router.addRoute("/product/:id", (params) => { console.log(`Product page for product ${params.id}`)})
router.listen()
OptionTypeDescription
basestringBase URL for the router. Default is /.
fallbackstringFallback route. Default is /
maxRedirectsnumberMaximum redirects. Default is 5.
useCachebooleanEnabling cache.
cahceLimitnumberCache size. Default is 50.
enableSwipeNavigationbooleanEnable swipe left/right for history navigation. Default is false.
routesobjectCreate routes in constructor. Default is null.
pluginsarrayRegistering plugins in constructor. Default is null.
const router = new Router({
base: "/",
fallback: "/",
maxRedirects: 5,
cacheLimit: 50,
enableSwipeNavigation: false,
routes: {
"/": () => { },
"/product/:id": (params) => { }
}
})

To add routes, you can use methods:

  • addRoute(path, callback) - add a new route
  • addNestedRoute(parentPath, path, callback) - add a nested route
  • addLazyRoute(path, callback) - add a lazy route
  • addLazyNestedRoute(parentPath, path, importFunc) - add a lazy nested route
  • addFallbackRoute(path) - add a fallback route
  • add404Route(path) - add a 404 route
  • addErrorRoute(path) - add a error route
  • addProtectedRoute(path, callback, guardFunction, fallback = '/login') - add a protected route
router.addRoute("/", () => { })
router.addRoute("/product/:id", (params) => { })

To remove a route, use the removeRoute(path) method:

router.removeRoute("/product/:id")

To update a route, use the updateRoute(path, callback) method:

router.updateRoute("/product/:id", (params) => { })

Router uses method navigate(path) to navigate to a matched route.

For manual navigation, you can use the navigateTo(path, replaceState = false)

router.navigateTo("/product/1")

To listen for routes, use the listen() method:

router.listen()

To get the current route, use the current property:

const currentRoute = router.current

To get all routes, use the routes property or getRoutes() method:

const allRoutes = router.routes
const allRoutes = router.getRoutes()

You can use middleware to intercept requests and perform actions before the route is processed. To add middleware, use the use(middleware) method:

router.use((route) => {
console.log(`Navigating to ${route.path}`)
})

You can use hooks to perform actions before and after the route is processed. To add hooks, use the beforeEach(hook) and afterEach(hook) methods:

router.beforeEach((route) => {
console.log(`Before navigating to ${route.path}`)
})
router.afterEach((route) => {
console.log(`After navigating to ${route.path}`)
})

You can use redirects to redirect from one route to another. To add a redirect, use the addRedirect(from, to) method:

router.addRedirect("/old-path", "/new-path")

You can test a path, with a test(path) method. This method returns object:

{
"original": string, // original path
"sanitized": string, // sanitized path
"isBlocked": boolean, // must blocked
"isModified": boolean, // was modified
}
router.test("/product/1")

You can use cache to store routes. To enable cache, use the useCache option in the constructor:

const router = new Router({
useCache: true
})

To set the cache limit, use the cacheLimit option in the constructor:

const router = new Router({
cacheLimit: 100
})

To clear the cache, use the clearCache() method:

router.clearCache()

You can enable debug mode with debug option. This will log all routes and navigation events to the console:

const router = new Router({
debug: true
})

You can use plugins to extend the functionality of the router.

// Пример плагина логирования
const loggerPlugin = {
install(router, options = {}) {
const prefix = options.prefix || '[Router]';
const level = options.level || 'info';
// Подписываемся на события роутера
router.on('beforeNavigate', (route) => {
console[level](`${prefix} Переход на: ${route.path}`);
});
router.on('error', (error) => {
console.error(`${prefix} Ошибка:`, error);
});
},
onInit(router) {
console.log('Logger plugin initialized');
},
onDestroy() {
console.log('Logger plugin destroyed');
}
};
// Использование
const router = new Router({
plugins: [
loggerPlugin,
]
});
// or
router.usePlugin(loggerPlugin, { prefix: '[MyApp Router]', level: 'debug' });