Now.js Framework Documentation
RouterManager
RouterManager
Overview
RouterManager is the client-side routing system in Now.js Framework for SPA (Single Page Application).
When to use:
- Need SPA routing
- Need page navigation without reload
- Need route guards
- Need dynamic routes
Why use it:
- ✅ Hash and History mode
- ✅ Route parameters
- ✅ Navigation guards
- ✅ Lazy loading
- ✅ Auto template loading
- ✅ Scroll restoration
Basic Usage
Initialization
await RouterManager.init({
mode: 'history', // or 'hash'
routes: [
{ path: '/', template: '/pages/home.html' },
{ path: '/about', template: '/pages/about.html' },
{ path: '/users/:id', template: '/pages/user.html' }
]
});HTML Links
<!-- Regular links work automatically -->
<a href="/about">About</a>
<a href="/users/123">User Profile</a>
<!-- Programmatic navigation -->
<button onclick="RouterManager.navigate('/contact')">Contact</button>Configuration
RouterManager.init({
mode: 'history',
routes: [
{ path: '/', template: '/pages/home.html' },
{ path: '/products', template: '/pages/products.html' },
{ path: '/products/:id', template: '/pages/product.html' }
],
// Container for page content
container: '#app',
// Default route
defaultRoute: '/',
// 404 template
notFoundTemplate: '/pages/404.html',
// Scroll behavior
scrollBehavior: 'top', // 'top', 'restore', 'none'
// Base path
basePath: '',
// API integration
api: {
enabled: true,
format: '/api{path}'
}
});Route Definition
{
// URL path
path: '/users/:id',
// Template file
template: '/pages/user.html',
// API endpoint
api: '/api/users/:id',
// Route name
name: 'user-profile',
// Metadata
meta: {
requiresAuth: true,
title: 'User Profile'
},
// Before enter guard
beforeEnter: (to, from) => {
if (!isAuthenticated()) {
return '/login'; // Redirect
}
return true; // Allow
}
}API Reference
RouterManager.navigate(path, options?)
Navigate to path
| Parameter | Type | Description |
|---|---|---|
path |
string | Target path |
options.replace |
boolean | Replace history |
options.params |
object | Query parameters |
RouterManager.navigate('/users/123');
RouterManager.navigate('/search', { params: { q: 'john' } });
RouterManager.navigate('/login', { replace: true });RouterManager.go(delta)
Navigate history
RouterManager.go(-1); // Back
RouterManager.go(1); // ForwardRouterManager.back()
Go back
RouterManager.back();RouterManager.forward()
Go forward
RouterManager.forward();RouterManager.getCurrentRoute()
Get current route info
Returns: Object
const route = RouterManager.getCurrentRoute();
// { path: '/users/123', params: { id: '123' }, query: {}, meta: {} }RouterManager.getParams()
Get route parameters
Returns: Object
// URL: /users/123
const params = RouterManager.getParams();
// { id: '123' }RouterManager.getQuery()
Get query parameters
Returns: Object
// URL: /search?q=john&page=2
const query = RouterManager.getQuery();
// { q: 'john', page: '2' }RouterManager.beforeEach(guard)
Global navigation guard
| Parameter | Type | Description |
|---|---|---|
guard |
function | Guard function |
RouterManager.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isAuthenticated()) {
next('/login');
} else {
next();
}
});RouterManager.afterEach(hook)
After navigation hook
RouterManager.afterEach((to, from) => {
document.title = to.meta.title || 'My App';
trackPageView(to.path);
});Events
| Event | When Triggered | Detail |
|---|---|---|
route:changed |
Route changed | {path, params, query} |
route:before |
Before navigate | {to, from} |
route:after |
After navigate | {to, from} |
route:error |
Error | {error, path} |
EventManager.on('route:changed', (data) => {
console.log('Navigated to:', data.path);
});Real-World Examples
Basic SPA Setup
<!DOCTYPE html>
<html>
<head>
<title>My App</title>
</head>
<body>
<nav>
<a href="/">Home</a>
<a href="/about">About</a>
<a href="/contact">Contact</a>
</nav>
<main id="app">
<!-- Page content loads here -->
</main>
<script src="/js/now.js"></script>
<script>
Now.init({
router: {
mode: 'history',
container: '#app',
routes: [
{ path: '/', template: '/pages/home.html' },
{ path: '/about', template: '/pages/about.html' },
{ path: '/contact', template: '/pages/contact.html' }
]
}
});
</script>
</body>
</html>Protected Routes
RouterManager.init({
routes: [
{ path: '/', template: '/pages/home.html' },
{ path: '/login', template: '/pages/login.html', meta: { guest: true } },
{
path: '/dashboard',
template: '/pages/dashboard.html',
meta: { requiresAuth: true }
},
{
path: '/admin',
template: '/pages/admin.html',
meta: { requiresAuth: true, role: 'admin' }
}
]
});
RouterManager.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !AuthManager.isAuthenticated()) {
AuthManager.saveIntendedUrl(to.path);
return next('/login');
}
if (to.meta.guest && AuthManager.isAuthenticated()) {
return next('/dashboard');
}
if (to.meta.role && !AuthManager.hasRole(to.meta.role)) {
return next('/403');
}
next();
});Dynamic Page Title
RouterManager.afterEach((to) => {
const titles = {
'/': 'Home',
'/about': 'About Us',
'/contact': 'Contact'
};
document.title = `${titles[to.path] || 'Page'} | My App`;
});Route Parameters
// Route: /users/:id
// URL: /users/123
const route = RouterManager.getCurrentRoute();
console.log(route.params.id); // '123'
// In template
// <h1>User {{params.id}}</h1>Common Pitfalls
⚠️ 1. History Mode Requires Server Config
# Apache (.htaccess)
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule># Nginx
location / {
try_files $uri $uri/ /index.html;
}⚠️ 2. Guard Must Call next()
// ❌ Forgot to call next()
RouterManager.beforeEach((to, from, next) => {
console.log('Guard');
// Navigation stuck!
});
// ✅ Always call next()
RouterManager.beforeEach((to, from, next) => {
console.log('Guard');
next();
});Related Documentation
- TemplateManager - Templates
- AuthManager - Authentication