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, you create a router in it.

Start by importing the createRouter() function from lwr/router. Next, define a RouteDefinition array and pass that array to createRouter().

Finally, the createRouter() function returns a router instance for use by lwr/routerContainer.

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, modules are always 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. The following example also uses generateUrl() to generate a URL from a page reference:

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:

Open the site at http://localhost:3000. Read Get Started for details on LWR Yarn commands.