Skip to main content
@spa-tools/core-router

Vanilla Reference

The Core Router is designed to be framework agnostic and can be used with any JavaScript library. This reference will cover the usage of the Core Router with Typescript but works for Javascript as well (simply ignore all type usage).

routesFactory()

The routesFactory<R> function returns a factory method, which when called transforms route definitions into a routes object. The resulting routes object is what you use in your app whenever you need to provide routes to a Core Router or when you need to specify a route for navigation.

The generic R type is used to define the shape of the route that will be created and must extend the default CoreRoute type.

Usage

import { CoreRoute, routesFactory } from '@spa-tools/core-router';

// adding custom properties to your routes is as simple
// as creating an interface that extends CoreRoute
interface MyCustomRoute extends CoreRoute {
requiresAuth: boolean;
}

// to create your routes, first generate a route factory method
const createMyRoutes = routesFactory<MyCustomRoute>();

// next define and create all of your routes, which you'll
// typically export to use throughout your app
export const myRoutes = createMyRoutes({
dashboardRoute: {
path: '/',
requiresAuth: true,
},
financialsRoute: {
path: '/financials',
requiresAuth: true,
},
loginRoute: {
path: '/login',
requiresAuth: false,
},
signupRoute: {
path: '/signup',
requiresAuth: false,
},
});

CoreRouter

The CoreRouter class is used to create a new instance of a Core Router which is where all of the routing logic is encapsulated.

Usage

import { CoreRouter } from '@spa-tools/core-router';

const myRouter = CoreRouter.initialize(myRoutes, myOptions);

myRouter.navigate(myRoutes.dashboardRoute);

Constructor

ParameterTypeRequired?DefaultComments
routesRecord<string, R>yes-The routes are created using a factory method generated via routesFactory.
optionsCoreRouterOptionsno-See the Options section for details.

The navigate method is used to navigate to a new route.

ParameterTypeRequired?DefaultComments
routeR or stringyes-Must be EITHER one of the routes that were created using the factory method generated via routesFactory OR the respective route's path.
stateRecord<string, unknown>no-The state to be passed to the new route.
hashstringno-The hash to be passed to the new route, which will trigger an auto-scroll after navigation on target element if one exists.

CoreRouterOptions

The CoreRouterOptions type is used to define the options that can be passed to the CoreRouter constructor.

Usage

import { CoreRouterOptions } from '@spa-tools/core-router';

const myOptions: CoreRouterOptions<MyCustomRoute> = {
basePath: '/app',
fallbackRoute: myRoutes.dashboardRoute,
fallbackState: { error: '404' },
onRouteChange: (route, state) => {
console.log('Route changed to:', route, 'with state:', state);
},
onRouteRequest: (newRoute, newState) => {
console.log('Route requested:', newRoute, 'with state:', newState);
},
};

Properties

PropertyTypeRequired?DefaultComments
basePathstringno-Used to build the full URL for each route. An example of a base path is /app which would be used to build the full URL for a route with a path of /home as /app/home.
fallbackRouteRno-Route to use when no route is matched.
fallbackStateRecord<string, unknown>no-State to use when no route is matched.
onRouteChangeOnCoreRouteChange<R>no-Callback that is invoked when a route change has been processed.
onRouteRequestOnCoreRouteRequest<R>no-Callback that is invoked when a route change request is pending and ready to act on.

CoreRoute

CoreRoute is the base type that all Core Router routes must extend.

PropertyTypeRequired?DefaultComments
hashScrollBehaviorScrollBehaviorno-Determines the scroll behavior when hash links are auto-srolled on route navigation.
pathstringyes-The route's path, relative to the app's base path.
addUnusedStateToQueryStringbooleannofalseIf true, any state that is not used to interpolate URL path params will be added to the query string.
preEncodeQueryStringValuesstring[]no[]The querystring values for all keys provided will be pre-encoded, which in effect applies double-encoding. Example for use is if you have to pass file paths in a querystring and the consuming service requires it to be double URI encoded.
removeUnusedQueryParamsbooleannotrueIf true, any query string placeholders that are not used to interpolate the URL will be removed from path (i.e. discard orhpaned placeholders).

CoreRouteChangePayload

CoreRouteChangePayload<R> is the object that is passed to the onRouteChange callback when a route change has been processed.

PropertyTypeRequired?DefaultComments
routeRyes-The route that was navigated to.
stateRecord<string, unknown>no-The state that was passed to the route.

CoreRouteRequestPayload

CoreRouteRequestPayload<R> is the object that is passed to the onRouteRequest callback when a route change request is pending and ready to act on.

PropertyTypeRequired?DefaultComments
newRouteRyes-The route that is being requested.
newStateRecord<string, unknown>no-The state that is being passed to the requested route.
oldRouteRno-The route of the last request that was approved.
oldStateRecord<string, unknown>no-The state of the last request that was approved.

CoreRouteResponse

CoreRouteResponse<R> is the response that the consumer returns from within the onRouteRequest callback when a route change request is pending and ready to act on. This is used to determine how the Core Router should proceed with the route change request and thus is the mechanisim by which consumers maintain absolute control over routing flow logic.

ScenarioReturn typeResulting behavior
Auto-approvevoid (i.e. do nothing)Request is auto-approved and proceeds with route change.
Explicit approval/cancellationPromise<boolean>Resolving true approves request and proceeds with route change; othwerwise, cancels route change.
Redirect to routePromise<R>Redirects to the provided route.
Redirect to route with statePromise<[R, Record<string, unknown>]>Redirects to the route provided in tuple's first element while applying state provided in second element.
Redirect to route with state and hashPromise<[R, Record<string, unknown>, string]>Redirects to the route provided in tuple's first element while applying state provided in second element and requests scroll to target location's element via hash provided in third element.
Redirect to route with hashPromise<[R, string]>Redirects to the route provided in tuple's first element and requests scroll to target location's element via hash provided in second element.
Redirect using pathPromise<string>Redirects to the route corresponding with the respective path.
Redirect using path with statePromise<[string, Record<string, unknown>]>Redirects to the route corresponding with the respective path in tuple's first elment while applying state provided in second element.
Redirect using path with state and hashPromise<[string, Record<string, unknown>], string>Redirects to the route corresponding with the respective path in tuple's first element while applying state provided in second element and requests scroll to target location's element via hash provided in third element.
Redirect using path and hashPromise<[string, string]>Redirects to the route corresponding with the respective path in tuple's first element and requests scroll to target location's element via hash provided in second element.

OnCoreRouteChange

OnCoreRouteChange<R> defines the signature for the callback that is invoked after a route change has been processed.

type OnCoreRouteChange<R> = (payload: CoreRouteChangePayload<R>) => void;
ParameterTypeRequired?DefaultComments
payloadCoreRouteChangePayload<R>yes-Object containing information about the route change that was just processed.

OnCoreRouteRequest

OnCoreRouteRequest<R> is the signature for the callback that is invoked when a route change request is pending and ready to act on.

type OnCoreRouteRequest<R> = (payload: CoreRouteRequestPayload<R>) => Promise<CoreRouteResponse<R>> | void;
ParameterTypeRequired?DefaultComments
payloadCoreRouteRequestPayload<R>yes-Object containing information about the route change that is pending and ready to act on.