tuijs-router
v0.9.5
Published
A simple and easy to use client-side router for JavaScript.
Readme
TUIJS-Router
Last Updated 03/14/2026
Description
A simple and easy to use client-side router for JavaScript. TUIJS-Router is flexible and can be used with vanilla Javascript or with most front end frameworks. TUIJS-Router also works great with TypeScript projects.
TUIJS-Router is currently pre-release. Expect breaking changes.
Getting Started
Install TUIJS-Router via NPM.
Once installed import createRouterInstance and use the creator function to create a new instance.
import { createRouterInstance } from 'tuijs-router';
const routerInstance = createRouterInstance();- Once an instance has been created, routes can be added individually using the addRoute or all at once using the setRouteList method. Each route consists of a path, an enter function, and an optional exit function. This simple route object format keeps router extremely flexible and allows a developer to have complete control over the code that executes when navigating between routes.
Example using addRoute:
routerInstance.addRoute({
path: '/',
enterFunction: () => {document.body.innerText = 'Home Page'}
});Example using setRouteList:
const routes = [
{
path: '/',
enterFunction: () => {document.body.innerText = 'Home Page'}
},
{
path: '/about',
enterFunction: () => {document.body.innerText = 'About Page'},
exitFunction: () => {console.log('Leaving the About Page')}
}
]- The setRouteNotFound method may be used to configure the router's behavior in the event that a route is called that was not defined in the routeList configuration. These can be redirected to the client side router or to the server if a true 404 response is desired. By default, all unknown routes are sent to the server with the path "/404".
It should be noted that if the server has a basic SPA configuration, and serves "index.html" for all requests, sending unknown routes to the server will cause a routing loop. To avoid this, ensure the server is configured to correctly handle the configured route not found path. This includes Vite. To ensure development environments handle the route not found path, make sure it is included in the Vite configuration file.
- Client redirects may also be configured but are optional. These can be useful if you have a parent path that is not an actual page. Redirects can be added, deleted, or the entire list set at once. See the example below.
Example using addRedirect:
routerInstance.addRedirect({
fromPath: '/users',
toPath: '/users/profile'
})Example using setRedirectList:
const redirectList = [
{
fromPath: '/users',
toPath: '/users/profile'
},
{
fromPath: '/docs',
toPath: '/docs/introduction'
}
]
routerInstance.setRedirectList();- If desired, server only routes may configured. These routes will bypass the client router and be sent directly to the server. Server routes may be added, deleted, or the entire list set at once.
It should be noted that TUIJS-Router does not affect fetch requests. As a result, many project likely do not need to utilize this configuration.
Example using addServerRoute:
routerInstance.addServerRoute('/login');Example using setServerRouteList:
const serverRouteList = [
'/login',
'/logout'
]
routerInstance.setServerRouteList(serverRouteList);- Once the router configuration is ready, the router needs to be started using startRouter method.
routerInstance.startRouter();Dynamic Routes
TUIJS-Router supports dynamic routing. to create a dynamic route, simple add a route with a path starting with ":".
IT IS NOT RECOMMENDED TO USE DYNAMIC ROUTES AT THE ROOT. THIS CAN BREAK ROUTING, CREATE ROUTING LOOPS, OR CAUSE SEO ISSUES.
State Data
TUIJS-Router supports the ability to pass a state data Object from one page to another. State data is passed using the optional data parameter in the navigateTo method. All previous state data is cleared when the navigateTo method is called. State data may also be manually manipulated using the setState, getState, and clearState methods if needed.
In this example, we collect the path from the current view and pass it to the next view via the state data object.
const path = window.location.pathname;
routerInstance.navigateTo('about', { previousPath: path });Once at the next view, we can collect the state using the getState method.
const stateData = routerInstance.getState();
console.log(stateData);New Tabs
To open a new tab, use the navigateToNewTab method.
Notes:
- If and A tag is used and the target is set to _blank, client side routing will be skipped.
- If an A tag used and the href starts with one of the following prefix's, client side routing will be skipped.
- 'http://'
- 'https://'
- 'ftp://'
- 'file://'
- 'ws://'
- 'wss://'
- 'tel:'
- 'mailto:'
- If an A tag is used and the href starts with #, the scrollTo method is used to scroll to the element location on the current page.
ROUTER CONTROL METHODS
startRouter
Attaches window and document event listeners to start the router.
| Parameters | |------------| | None |
stopRouter
Removes all event listeners to stop the router.
| Parameters | |------------| | None |
getRouterConfig
Returns the active routerConfig object.
| Parameters | |------------| | None |
ROUTER NAVIGATION METHODS
navigateTo
Navigates to the target route.
- If the target route is the same as the current route, it will re-run the enter function and update state.
- If the target route is different from the current route, it will create a new entry in the browser's history stack and run the enter function.
- If the target route matches a redirect, it will navigate to the redirect's toPath.
- If the target route is not found in the client route list but is found in the server route list, it will send a request to the server.
- If the target route is not found in either the client or server route list, it will navigate to the route not found path.
- To prevent infinite loops, if a route is visited more than once during a single navigation attempt, the router will log an error and navigate to the root path.
| Parameters | Type | Description | |--------------|----------|---------------------------------------------------------------------------| | targetRoute | string | The route to be navigated to | | data | Object | State data to be passed to the destination route (optional) | | visitedPaths | Set | A list of visited paths designed to prevent infinite route loops (20 Max) |
navigateToNewTab
Allows the client side router to open a page in a new tab.
| Parameters | Type | Description | |--------------|----------|------------------------------| | route | string | The route to be navigated to |
navigateToAnchorTag (scrollTo)
Handles anchor tag routes. Scrolls element into view smoothly. If the anchor tag is in a shadow DOM, the shadow DOM root should be added to the anchor tag wrapped in "$". This tells navigateToAnchorTag where to search for the anchor tag. Example: "#$shadowRootId$targetElementId"
| Parameters | Type | Description | |--------------|----------|--------------------------------------| | anchor | string | The element to be scrolled into view | | options | Object | Options for the scroll. |
Options behavior: ScrollBehavior - The scroll behavior to be used. Default is 'smooth'. searchShadowDom: boolean - Weather the shadow DOM should be searched. This defaults to true. If no shadow root is provided, navigateToAnchorTag will search the entire tree, which provides a simple dev experience but can impact performance for large DOM trees. Using the "$" wrapper is recommended if the target anchor tag is in a Shadow DOM.
NavigateBack
Navigates back to the previous page or to the root if no referrer exists. Uses the browser's history API and delegates to navigateTo to maintain router state.
| Parameters | |------------| | None |
ROUTE LIST METHODS
setRouteList
Sets the entire routeList array in the routerConfig Object, overwriting any existing routeList.
| Parameters | Type | Description | |--------------|--------------|---------------------------| | newRouteList | RouteList | An array of Route Objects |
addRoute
Creates a route Object within the routeList Array. If a route with the same path already exists, it is overwritten with the new route Object.
| Parameters | Type | Description | |--------------|-------------|---------------------------| | newRoute | Route | The route to be added |
deleteRoute
Deletes all matching route Objects within the routeList Array.
| Parameters | Type | Description | |--------------|----------|---------------------------| | path | string | The route to be added |
getRouteList
Returns the RouteList array.
| Parameters | |------------| | None |
SERVER ROUTE LIST METHODS
setServerRouteList
Sets the routeListServer array in the routerConfig Object.
| Parameters | Type | Description | |--------------------|------------------|--------------------------------------------------------------------| | serverRouteList | ServerRouteList | List of server routes to be added to router instance configuration |
addServerRoute
Creates a route Object within the serverRouteList Array.
| Parameters | Type | Description | |--------------|----------|---------------------------| | path | string | The route to be added |
deleteServerRoute
Deletes all matching route Objects within the serverRouteList Array based on input.
| Parameters | Type | Description | |--------------|----------|---------------------------| | path | string | The route to be added |
replaceServerRoute
Replaces an existing route Object within the serverRouteList Array.
| Parameters | Type | Description | |--------------|----------|-------------------------------------------| | oldPath | string | The old route/path to be replaced | | newPath | string | The new route/path to replace the old one |
getServerRouteList
Returns the ServerRouteList array.
| Parameters | |------------| | None |
ROUTE NOT FOUND METHODS
setRouteNotFound
Sets the routeNotFound Object in the routerConfig Object.
| Parameters | Type | Description | |--------------|-----------------------|------------------------------------| | routeNotFound | RouteNotFound | The route not found object |
getRouteNotFound
Returns the RouteNotFound Object.
| Parameters | |------------| | None |
REDIRECT METHODS
setRedirectList
Sets the redirectList Array in the routerConfig Object.
| Parameters | Type | Description | |--------------|-----------------|------------------------------| | redirectList | RedirectList | An array of redirect objects |
addRedirect
Creates a redirect Object within the redirectList Array. If a redirect with the same fromPath already exists, it is overwritten with the new redirect Object.
| Parameters | Type | Description | |--------------|----------|---------------------------------------------------------| | newRedirect | Redirect | The redirect object to be added to the routeConfig |
deleteRedirect
Deletes all matching redirect Objects within the redirectList Array based on input.
| Parameters | Type | Description | |--------------|----------|-----------------------------------| | fromPath | string | The redirect object to be deleted |
getRedirectList
Returns the RedirectList Array.
| Parameters | |------------| | None |
STATE METHODS
setState
Sets the stateData Object.
| Parameters | Type | Description | |--------------|----------|---------------------------------------------------------------------------| | data | Object | The state data to be set (Global to the router) |
getState
Returns the stateData Object.
| Parameters | |------------| | None |
clearState
Clears the stateData Object.
| Parameters | |------------| | None |
