Class Router<R, C>

A simple client-side router for single-page applications. It uses express-style middleware and has a first-class support for Web Components and lazy-loading. Works great in Polymer and non-Polymer apps.

Use new Router(outlet, options) to create a new Router instance.

  • The outlet parameter is a reference to the DOM node to render the content into.

  • The options parameter is an optional object with options. The following keys are supported:

The Router instance is automatically subscribed to navigation events on window.

See Live Examples for the detailed usage demo and code snippets.

See also detailed API docs for the following methods, for the advanced usage:

  • setOutlet – should be used to configure the outlet.
  • setTriggers – should be used to configure the navigation events.
  • setRoutes – should be used to configure the routes.

Only setRoutes has to be called manually, others are automatically invoked when creating a new instance.

Type Parameters

  • R extends object = EmptyObject
  • C extends object = EmptyObject

Hierarchy (view full)

Constructors

  • Creates a new Router instance with a given outlet, and automatically subscribes it to navigation events on the window. Using a constructor argument or a setter for outlet is equivalent:

    const router = new Router();
    router.setOutlet(outlet);

    Type Parameters

    • R extends object = EmptyObject
    • C extends object = EmptyObject

    Parameters

    Returns Router<R, C>

Properties

baseUrl: string

The base URL for all routes in the router instance. By default, if the base element exists in the <head>, vaadin-router takes the <base href> attribute value, resolved against the current document.URL.

location: RouterLocation<R, C> = ...

Contains read-only information about the current router location: pathname, active routes, parameters. See the Location type declaration for more details.

ready: Promise<RouterLocation<R, C>> = ...

A promise that is settled after the current render cycle completes. If there is no render cycle in progress the promise is immediately settled with the last render cycle result.

resolve: ((contextOrPathname: string | RouteContext<R, C>) => Promise<Readonly<{
    chain?: ChainItem<ActionValue, RouteExtension<R, C>, ContextExtension<R, C>>[];
    hash?: string;
    next(resume?: boolean, parent?: Route<ActionValue, RouteExtension<R, C>, ContextExtension<R, C>>, prevResult?: ActionResult<RouteContext<ActionValue, RouteExtension<R, C>, ContextExtension<R, C>>>): Promise<ActionResult<RouteContext<ActionValue, RouteExtension<R, C>, ContextExtension<R, C>>>>;
    params: Readonly<Record<string, ParamValue>>;
    redirectFrom?: string;
    resolver?: Resolver<ActionValue, RouteExtension<R, C>, ContextExtension<R, C>>;
    route: Route<ActionValue, RouteExtension<R, C>, ContextExtension<R, C>>;
    search?: string;
}> & {
    result?: ActionValue | RouteContext<ActionValue, RouteExtension<R, C>, ContextExtension<R, C>>;
} & Readonly<{
    pathname: string;
}> & Readonly<{
    chain?: ChainItem<R, C>[];
    resolver?: Router<R, C>;
}> & C & Readonly<{
    from: string;
    params: Readonly<Record<string, ParamValue>>;
    pathname: string;
}>>)

Asynchronously resolves the given pathname, i.e. finds all routes matching the pathname and tries resolving them one after another in the order they are listed in the routes config until the first non-null result.

Returns a promise that is fulfilled with the return value of an object that consists of the first route handler result that returns something other than null or undefined and context used to get this result.

If no route handlers return a non-null result, or if no route matches the given pathname the returned promise is rejected with a 'page not found' Error.

resolveRoute: ResolveRouteCallback<ActionValue, RouteExtension<R, C>, ContextExtension<R, C>>

Accessors

  • get __effectiveBaseUrl(): string
  • If the baseUrl property is set, transforms the baseUrl and returns the full actual base string for using in the new URL(path, base); and for prepernding the paths with. The returned base ends with a trailing slash.

    Otherwise, returns empty string.

    Returns string

Methods

  • If the baseUrl is set, matches the pathname with the router’s baseUrl, and returns the local pathname with the baseUrl stripped out.

    If the pathname does not match the baseUrl, returns undefined.

    If the baseUrl is not set, returns the unmodified pathname argument.

    Parameters

    • pathname: string

    Returns undefined | string

  • Appends one or several routes to the routing config and returns the effective routing config after the operation.

    Parameters

    • routes: Route<R, C> | readonly Route<R, C>[]

      a single route or an array of those (the array is shallow copied)

    Returns readonly Route<R, C>[]

  • Returns the current router outlet. The initial value is undefined.

    Returns
        | undefined
        | null
        | Element
        | DocumentFragment

    the current router outlet (or undefined)

  • Returns the current list of routes (as a shallow copy). Adding / removing routes to / from the returned array does not affect the routing config, but modifying the route objects does.

    Returns readonly Route<ActionValue, RouteExtension<R, C>, ContextExtension<R, C>>[]

  • Triggers navigation to a new path. Returns a boolean without waiting until the navigation is complete. Returns true if at least one Router has handled the navigation (was subscribed and had baseUrl matching the path argument), otherwise returns false.

    Parameters

    • path: string | Readonly<{
          hash?: string;
          pathname: string;
          redirectFrom?: string;
          search?: string;
      }>

      A new in-app path string, or an URL-like object with pathname string property, and optional search and hash string properties.

    Returns boolean

  • Asynchronously resolves the given pathname and renders the resolved route component into the router outlet. If no router outlet is set at the time of calling this method, or at the time when the route resolution is completed, a TypeError is thrown.

    Returns a promise that is fulfilled with the router outlet DOM Element | DocumentFragment after the route component is created and inserted into the router outlet, or rejected if no route matches the given path.

    If another render pass is started before the previous one is completed, the result of the previous render pass is ignored.

    Parameters

    • pathnameOrContext: string | Readonly<{
          hash?: string;
          pathname: string;
          redirectFrom?: string;
          search?: string;
      }>

      the pathname to render or a context object with a pathname property, optional search and hash properties, and other properties to pass to the resolver.

    • shouldUpdateHistory: boolean = false

      update browser history with the rendered location

    Returns Promise<RouterLocation<R, C>>

  • Sets the router outlet (the DOM node where the content for the current route is inserted). Any content pre-existing in the router outlet is removed at the end of each render pass.

    Parameters

    • Optionaloutlet: null | Element | DocumentFragment

      the DOM node where the content for the current route is inserted.

    Returns void

    This method is automatically invoked first time when creating a new Router instance.

  • Sets the routing config (replacing the existing one) and triggers a navigation event so that the router outlet is refreshed according to the current window.location and the new routing config.

    Each route object may have the following properties, listed here in the processing order:

    • path – the route path (relative to the parent route if any) in the express.js syntax.

    • children – an array of nested routes or a function that provides this array at the render time. The function can be synchronous or asynchronous: in the latter case the render is delayed until the returned promise is resolved. The children function is executed every time when this route is being rendered. This allows for dynamic route structures (e.g. backend-defined), but it might have a performance impact as well. In order to avoid calling the function on subsequent renders, you can override the children property of the route object and save the calculated array there (via context.route.children = [ route1, route2, ...];). Parent routes are fully resolved before resolving the children. Children 'path' values are relative to the parent ones.

    • action – the action that is executed before the route is resolved. The value for this property should be a function, accepting context and commands parameters described below. If present, this function is always invoked first, disregarding of the other properties' presence. The action can return a result directly or within a Promise, which resolves to the result. If the action result is an HTMLElement instance, a commands.component(name) result, a commands.redirect(path) result, or a context.next() result, the current route resolution is finished, and other route config properties are ignored. See also Route Actions section in Live Examples.

    • redirect – other route's path to redirect to. Passes all route parameters to the redirect target. The target route should also be defined. See also Redirects section in Live Examples.

    • component – the tag name of the Web Component to resolve the route to. The property is ignored when either an action returns the result or redirect property is present. If route contains the component property (or an action that return a component) and its child route also contains the component property, child route's component will be rendered as a light dom child of a parent component.

    • name – the string name of the route to use in the router.urlForName(name, params) navigation helper method.

    For any route function (action, children) defined, the corresponding route object is available inside the callback through the this reference. If you need to access it, make sure you define the callback as a non-arrow function because arrow functions do not have their own this reference.

    context object that is passed to action function holds the following properties:

    • context.pathname – string with the pathname being resolved

    • context.search – search query string

    • context.hash – hash string

    • context.params – object with route parameters

    • context.route – object that holds the route that is currently being rendered.

    • context.next() – function for asynchronously getting the next route contents from the resolution chain (if any)

    commands object that is passed to action function has the following methods:

    • commands.redirect(path) – function that creates a redirect data for the path specified.

    • commands.component(component) – function that creates a new HTMLElement with current context. Note: the component created by this function is reused if visiting the same path twice in row.

    Parameters

    • routes: Route<R, C> | readonly Route<R, C>[]

      a single route or an array of those

    • skipRender: boolean = false

      configure the router but skip rendering the route corresponding to the current window.location values

    Returns Promise<RouterLocation<R, C>>

  • Configures what triggers Router navigation events:

    • POPSTATE: popstate events on the current window
    • CLICK: click events on <a> links leading to the current page

    This method is invoked with the pre-configured values when creating a new Router instance. By default, both POPSTATE and CLICK are enabled. This setup is expected to cover most of the use cases.

    See the router-config.js for the default navigation triggers config. Based on it, you can create the own one and only import the triggers you need, instead of pulling in all the code, e.g. if you want to handle click differently.

    See also Navigation Triggers section in Live Examples.

    Parameters

    Returns void

  • Subscribes this instance to navigation events on the window.

    NOTE: beware of resource leaks. For as long as a router instance is subscribed to navigation events, it won't be garbage collected.

    Returns void

  • Removes the subscription to navigation events created in the subscribe() method.

    Returns void

  • Generates a URL for the route with the given name, optionally performing substitution of parameters.

    The route is searched in all the Router instances subscribed to navigation events.

    Note: For child route names, only array children are considered. It is not possible to generate URLs using a name for routes set with a children function.

    Parameters

    • name: string

      The route name or the route’s component name.

    • Optionalparams: null | Params

      Optional object with route path parameters. Named parameters are passed by name (params[name] = value), unnamed parameters are passed by index (params[index] = value).

    Returns string

  • Generates a URL for the given route path, optionally performing substitution of parameters.

    Parameters

    • path: string

      String route path declared in express.js syntax.

    • Optionalparams: null | Params

      Optional object with route path parameters. Named parameters are passed by name (params[name] = value), unnamed parameters are passed by index (params[index] = value).

    Returns string