# Create a Router

To create a [router](/docs/platform/lwr/guide/lwr-routers-route-matching.md), you can either:

- use the [`createRouter()` API](#createrouter) to create and initialize a router. It accepts a JSON object as an argument. This method is appropriate for more sophisticated use cases.

- use the [Router Module Provider](#router-module-provider) to generate a router based on a static JSON file. This method is appropriate for most use cases.

## createRouter()

The `createRouter()` API takes a configuration object, [`RouterConfig`](https://developer.salesforce.com/docs/platform/lwr/references/csr-reference/routerconfig.md), as an argument. To initialize a router with `createRouter()`, follow these steps.

### 1. Set the Root Component of Your Application

Open your app's `lwr.config.json` file and specify a `rootComponent` value in a `routes` object. For more information on how to set routing properties, see the [`route` reference page](https://developer.salesforce.com/docs/platform/lwr/references/ss-routing-reference/route.md).

:::note
The routes defined in `lwr.config.json` are server-side. They differ from the [`RouteDefinition`](https://developer.salesforce.com/docs/platform/lwr/references/csr-reference/routedefinition.md) array that you set up in the next step for the client-side router.
:::

Here's an example of a `routes` object inside an `lwr.config.json` file.

```sfdocs-code {"lang":"json", "title": "lwr.config.json", "src": "" }
{
  "lwc": { "modules": [{ "dir": "$rootDir/src/modules" }] },
  "routes": [
    {
      "id": "app",
      "path": "/",
      "rootComponent": "example/app"
    }
  ]
}
```

### 2. Configure createRouter()

In your root component, import the [`createRouter()`](https://developer.salesforce.com/docs/platform/lwr/references/csr-reference/createrouter.md) function from `lwr/router`.

```sfdocs-code {"lang":"javascript", "title": "app.js", "src": "" }
import { LightningElement } from 'lwc';
import { createRouter } from 'lwr/router';
```

`createRouter()` takes a [`RouterConfig`](https://developer.salesforce.com/docs/platform/lwr/references/csr-reference/routerconfig.md) object. `RouterConfig` has to contain an array of [`RouteDefinition`](https://developer.salesforce.com/docs/platform/lwr/references/csr-reference/routedefinition.md) objects.

Here's an example `RouterConfig`. It contains an array with two routes, and it customizes the `basePath`, sets an `i18n` locale, and enables case sensitive URI processing. `namedPageHandler` is a [route handler module](https://developer.salesforce.com/docs/platform/lwr/guide/lwr-route-handler-modules.md).

```sfdocs-code {"lang":"javascript", "title": "src/modules/example/app/app.js", "src": "" }
const routerConfig = {
  routes: [
    {
      id: 'home',
      uri: '/',
      handler: () => import('example/homePageHandler'),
        page: {
            type: 'home',
        },
    },
    {
        id: 'namedPage',
        uri: '/:pageName',
        handler: () => import('example/namedPageHandler'),
        page: {
            type: 'namedPage',
            attributes: {
                pageName: ':pageName',
            },
        },
    },
  ],
  basePath: '/my-site',
  i18n: {
    locale: 'es',
    defaultLocale: 'en-US'
  },
  caseSensitive: true
}
```

Pass `RouterConfig` into `createRouter()`, which returns a router instance for use by `lwr/routerContainer`.

```sfdocs-code {"lang":"javascript", "title": "src/modules/example/app/app.js", "src": "" }
import { LightningElement } from 'lwc';
import { createRouter } from 'lwr/router';

const routerConfig = {
  routes: [
    {
      id: 'home',
      uri: '/',
      handler: () => import('example/homePageHandler'),
        page: {
            type: 'home',
        },
    },
    {
        id: 'namedPage',
        uri: '/:pageName',
        handler: () => import('example/namedPageHandler'),
        page: {
            type: 'namedPage',
            attributes: {
                pageName: ':pageName',
            },
        },
    },
  ],
  basePath: '/my-site',
  i18n: {
    locale: 'es',
    defaultLocale: 'en-US'
  },
  caseSensitive: true,
}

export default class SimpleRoutingApp extends LightningElement {
    router = createRouter(routerConfig);

    homeReference = { type: 'home' }; // Home page reference for the page-link
}
```

### 3. Attach the router to `lwr/routerContainer`

You have to attach the router to a [router container](/docs/platform/lwr/guide/lwr-router-containers.md). In your root component’s html file, attach the router instance to `lwr/routerContainer` like this:

```sfdocs-code {"lang":"html", "title": "src/modules/example/app/app.html", "src": "" }
<template>
  <lwr-router-container router={router}> // router instance attachment point
    <example-page-link label="Home" page-reference={homeReference}></example-page-link>
    <lwr-outlet>
      <div slot="error">This content failed to display.</div>
    </lwr-outlet>
  </lwr-router-container>
</template>
```

## Router Module Provider

The Router Module Provider generates a router based on a static JSON file. Static configurations can be easier to author and to maintain than a JavaScript module.

This module provider (`@lwrjs/router/module-provider`) is included in all projects by default.

### Optional: Register the Router Module Provider

In `lwr.config.json`, you can configure the directory location of your router JSON files.

```sfdocs-code {"lang":"json", "title": "lwr.config.json", "src": "" }
{
  "moduleProviders": [
    ["@lwrjs/router/module-provider", { "routesDir": "$rootDir/config/router" }],
    "@lwrjs/app-service/moduleProvider",
    "@lwrjs/lwc-module-provider",
    "@lwrjs/npm-module-provider"
  ]
}
```

If you don't specify a configuration, it uses this configuration by default:

```sfdocs-code {"lang":"json", "title": "lwr.config.json", "src": "" }
{
  "routesDir": "$rootDir/src/routes"
}
```

### Optional: Register client-side routes

To automatically register **client-side** routes with the server, specify them as `subRoutes` in `lwr.config.json` and point to their route JSON file.

```sfdocs-code {"lang":"json", "title": "lwr.config.json", "src": "" }
{
    "routes": [
        {
            "id": "spa",
            "path": "/site",
            "rootComponent": "my/spa",
            "subRoutes": "$rootDir/src/routes/client.json"
        }
    ]
}
```

The LWR server takes client-side routes as `uri` strings from static router configuration files. It registers `path` strings from them as follows:

| `uri`    | Resulting `path` |
| -------- | ---------------- |
| `/`      | `/site`          |
| `/about` | `/site/about`    |
| `/:id`   | `/site/:id`      |

### 1. Configure the Router JSON

The Router Module Provider generates a router module based on the JSON configuration of [`LwrRouterConfig`](https://developer.salesforce.com/docs/platform/lwr/references/csr-reference/lwrrouterconfig.md), which contains an array of route definitions in the form of [`LwrConfigRouteDefinition`](https://developer.salesforce.com/docs/platform/lwr/references/csr-reference/lwrconfigroutedefinition.md) objects.

Here's an example of a static JSON config file for `LwrRouterConfig`.

```sfdocs-code {"lang":"json", "title": "src/routes/my-config-file.json", "src": "" }
{
  "routes": [        // array of LwrConfigRouteDefinition objects
    {
      "id": "home",
      "uri": "/",
      "component": "examples/home",
      "page": {
        "type": "home"
      },
      "metadata": {
        "title": "Home"
      }
    },
    {
      "id": "namedPage",
      "uri": "/:pageName",
      "handler": "examples/namedPageHandler",
      "page": {
        "type": "namedPage",
        "attributes": {
          "pageName": ":pageName"
        }
      }
    }
  ],
  "caseSensitive": "true",
  "i18n": {
        "defaultLocale": "en-US",
        "locales": [{ "id": "en-US" }]
    }
}
```

For `LwrConfigRouteDefinition`, the `handler` and `component` properties are **string** references. Because `LwrConfigRouteDefinition` is pure JSON, it can't contain any functions.

### 2. Import and Use the Generated Router

After you’ve specified the JSON configurations, you can import and use the generated router. Make sure to attach the router to a [router container](/docs/platform/lwr/guide/lwr-router-containers.md), too.

```sfdocs-code {"lang":"javascript", "title": "src/modules/my/app/app.js", "src": "" }
import { LightningElement } from "lwc";
import { createRouter } from "@lwrjs/router/my-config-file";

export default class MyApp extends LightningElement {
  router = createRouter();
}
```

```sfdocs-code {"lang":"html", "title": "src/modules/my/app/app.html", "src": "" }
<template>
    <lwr-router-container router={router}>
        <lwr-outlet></lwr-outlet>
    </lwr-router-container>
</template>
```

The generated router module specifier is `@lwrjs/router/<name of the JSON config file>`. It provides a `createRouter()` function that's nearly identical to the static `createRouter()` function. Unlike the static `createRouter()`, the generated function doesn't take a `routes` array because the routes are configured in the JSON configuration file instead.

If `basePath` or `caseSensitive` is specified in both the static JSON configuration file and the generated `createRouter()` call, the latter takes precedence.

## Next Steps

Ready to configure navigaton rules for your new router? Check out [Simple Routing Example](/docs/platform/lwr/guide/lwr-routing-example-simple.md) to get started.
