Simple LWR Client-Side Routing Example

You can use the @lwrjs/router package to create a single page LWR application (SPA) with client-side routing. Important exports from the package include:

  • lwr/router
  • lwr/routerContainer
  • lwr/outlet
  • lwr/navigation

For additional information:

While an LWR app contains more files than shown here, in this recipe the following example module files are most important:

The first step in creating a router is to set up the root component of your SPA. You specify a rootComponent value in a routes object in your app’s lwr.config.json file. Check out the following example and "Routing Properties" for more information.

The routes defined in lwr.config.json are server-side. They differ from the RouteDefinition array that you set up in the next step for the client-side router.

This file is lwr.config.json.

After you set up your root component, create a router for it. This example uses the createRouter() function to generate a router.

In your root component’s html file, attach the router instance to lwr/routerContainer, as in this example:

In the previous step you created a router in your root component file. That router includes a promise in RouteDefinition.handler to a route handler module that’s called when a location matches a RouteDefinition. Route handler modules determine the associated "view", which is the component to display when the application navigates to a location.

In LWR, route handler modules are dynamically imported, so they are provided via promises. Promises allow the module code to be lazily loaded, improving application performance.

A simple route handler for a home page:

Route handler modules allow you to define enhanced routing rules such as branching and pivoting logic based on data and metadata values. Here’s another route handler, this time with branching logic:

In a Lightning web component, use the NavigationContext wire and navigate() function from lwr/navigation to navigate.

For example, in this snippet, the NavigationContext wire obtains a ContextId value. It assigns the ID to the navContext property, where it can be used by the navigate() API.

You can also use generateUrl() to generate a URL from a page reference, like this:

Sometimes the router navigation completes, but the component's new view contains an error. This situation is considered a successful navigation, so an errornavigate event doesn't fire. To handle this situation:

  1. Display an error:

    Via an error slot in an lwr-outlet component:

    Or via a custom component in the error slot:

  2. Handle the viewerror event that lwr-outlet dispatches:

Read more about LWR outlets.

Run the following terminal commands from the root of your project. Read Get Started for details on LWR NPM commands.

Open the site at http://localhost:3000.