# Wix Studio: Creating a Router

Source: https://support.wix.com/en/article/wix-studio-creating-a-router (updated 2023-08-02)
Related: Wix developer documentation, https://dev.wix.com/docs/llms.txt; Help Center index, https://support.wix.com/en/llms.txt

> Wix Studio is being released gradually to ensure a smooth onboarding experience. If you’re an agency or freelancer already using Wix or Editor X, you’ll receive an email once you have access.

Creating a router allows you to take complete control when handling certain incoming requests to your site.

This article takes you through the steps to add a router to your site, and what code you have to write in order to make your router work. To learn more about what a router is and why you would want to create one, see [About Routers](https://support.wix.com/en/article/velo-about-routers).

## Add a Router

To add a router to your site:

1. Click the Pages icon ![](https://github-production-user-asset-6210df.s3.amazonaws.com/91874936/255611116-bbe4fa95-9281-4246-9780-3a3641cc8bf5.png) to open the Site Pages panel. ![](https://github-production-user-asset-6210df.s3.amazonaws.com/91874936/255612203-8f3649e1-be8b-438d-a127-710602e92576.png)
2. Click the Add New Page icon ![](https://github-production-user-asset-6210df.s3.amazonaws.com/91874936/255386869-eac62946-357a-44c4-800c-cf8c8735b77f.png). Then, click **Add** under Router. ![](https://github-production-user-asset-6210df.s3.amazonaws.com/91874936/255609146-71622729-618b-49ad-b275-04f086a56bc1.png)
3. Enter a [URL prefix](https://support.wix.com/en/article/velo-about-routers#url-prefix) for your router and click **Add & Edit Code** to add the router to your site. All incoming requests with the specified URL prefix will be sent to your router for handling. ![](https://github-production-user-asset-6210df.s3.amazonaws.com/91874936/255608686-3e70a4bc-00cd-4196-ac65-2bb3b2836169.png)

After you've added your router, the following occurs:

* The following functions are added to your **router.js** file with sample code for a simple routing scenario:  
   * `<your-router-prefix>_Router(request)`  
   * `<your-router-prefix>_SiteMap(sitemapRequest)`  
 The **router.js** file is found in the `src/backend` folder of your [backend code](https://support.wix.com/en/article/coding-with-the-wix-studio-sidebar#backend-code). Find your backend code by navigating to the [Wix IDE](https://support.wix.com/en/article/wix-studio-about-the-wix-ide) from the Code panel. If you've [integrated your site with Github](https://support.wix.com/en/article/velo-about-git-integration-wix-cli), your backend code can be found in your local IDE.  
 Learn more about the [router()](https://support.wix.com/en/article/velo-about-routers#router) and [sitemap()](https://support.wix.com/en/article/velo-about-routers#sitemap) functions.
* A new section for router pages is created in the Pages panel for your routers. Router pages are grouped together under a title based on the URL prefixes used. For example, if your created a router with the prefix name "myRouter", a page named **myRouter-page** is added under the title **MyRouter Pages (Router)**.

## Sample Scenario

There are four parts to the sample code that's added to the **routers.js** file:

1. The `import` statement.
2. The sample data.
3. The [router()](http://wix.to/94BuAAs/wix-router.html#router) function.
4. The [sitemap()](http://wix.to/94BuAAs/wix-router.html#sitemap) function.

## Import statement

The functionality used to create a router is contained in the [Router API](http://wix.to/94BuAAs/wix-router.html). To use this functionality, you need to import it. By default, the [ok()](http://wix.to/94BuAAs/wix-router.html#ok) and [notFound()](http://wix.to/94BuAAs/wix-router.html#notFound) functions are imported, as well as the [WixRouterSitemapEntry](http://wix.to/94BuAAs/wix-router.WixRouterSitemapEntry.html) object.

```javascript
import {ok, notFound, WixRouterSitemapEntry} from "wix-router";
```

If you want to use more of the functionality from the Router API, you need to add it to the `import` statement.

## Sample Data

In the sample scenario, the router uses some static data contained in an object named `peopleData`.

```javascript
const peopleData = {  
  "Ash": {    
    title: "Ash Stowe",    
    image: "https://static.wixstatic.com/media/b8f383e0fe2b478ea91362b707ef267b.jpg"  
  },  
  "Aiden": {    
    title: "Aiden Johnson",    
    image: "https://static.wixstatic.com/media/ca3c7ac5427e43928aa5f3f443ae2163.jpg"  
  },  
  "Jess": {    
    title: "Jess White",    
    image: "https://static.wixstatic.com/media/147fe6f37fe24e83977b4124e41b6d3d.jpg"  
  },  
  "Morgan": {    
    title: "Morgan James",    
    image: "https://static.wixstatic.com/media/59e1f2f4dbbc4f7c9d6e66e3e125d830.jpg"  
  }
};
```

The `peopleData` object contains four keys, each representing a person. Each person contains two properties, a `title` that is the person's full name and an `image` that is a link to an image of the person.

Although you can use static data with a router, typically you would use data from your site's database or an external source. We'll see where you would write code to retrieve that data a little later.

Regardless of where you get the data from, since you'll be writing the code that handles it, the data can be structured in any way you like.

## Router Function

Remember, all incoming requests with the URL prefix you specified when creating the router are sent to your router for handling. The [router()](http://wix.to/94BuAAs/wix-router.html#router) function is where you handle those requests.

The [router()](http://wix.to/94BuAAs/wix-router.html#router) function is named with the following convention:

`<router prefix>_Router(request)`

So if you named your router **myRouter**, the code added to the **routers.js** file should look like:

`myRouter_Router(request) { // routing code ...}`

The [router()](http://wix.to/94BuAAs/wix-router.html#router) function has a `request` parameter which receives a [WixRouterRequest](http://wix.to/94BuAAs/wix-router.WixRouterRequest.html) object that contains information about the incoming request. The object has information about the URL used to reach the router, where the request came from, and who the request came from.

Typically, the [router()](http://wix.to/94BuAAs/wix-router.html#router) function will decide which page to show (if any) and what data to pass to the page. A response is then sent using the [forbidden()](http://wix.to/94BuAAs/wix-router.html#forbidden), [notFound()](http://wix.to/94BuAAs/wix-router.html#notFound), [ok()](http://wix.to/94BuAAs/wix-router.html#ok), [redirect()](http://wix.to/94BuAAs/wix-router.html#redirect), or [sendStatus()](http://wix.to/94BuAAs/wix-router.html#sendStatus) functions.

Let's take a look at the sample [router()](http://wix.to/94BuAAs/wix-router.html#router) function code:

```javascript
export function myRouter_Router(request) {

  // Get item name from URL request
  const name = request.path[0];

  // Get the item data by name
  const data = peopleData[name];

  if (data) {

    //define SEO tags 
    const seoData = { 
      title: data.title, 
      description: `This is a description of ${data.title} page`,
      noIndex: false,
      metaTags: [
         {
          "property": "og:title",
          "content": data.title,
         },
         {
          "property": "og:image",
          "content": data.image,
         }
      ]
    };

    // Render item page 
    return ok("myRouter-page", data, seoData); 
  }

  // Return 404 if item is not found 
  return notFound();
}
```

The [router()](http://wix.to/94BuAAs/wix-router.html#router) function begins by parsing the request's path to pull out a `name` value.

`const name = request.path[0];`

For example, a user might reach this [router()](http://wix.to/94BuAAs/wix-router.html#router) function by browsing to `https://mysite.com/myRouter/Ash`. The received [WixRouterRequest](http://wix.to/94BuAAs/wix-router.WixRouterRequest.html) object's [path](http://wix.to/94BuAAs/wix-router.WixRouterRequest.html#path) property will be an array with one element: `["Ash"]`. Now the value of `name` is `"Ash"`.

Next, the [router()](http://wix.to/94BuAAs/wix-router.html#router) function retrieves data based on the `name` it received.

`const data = peopleData[name];`

Continuing our example above, we pull out Ash's information from the `peopleData` object.

So `data` now holds:

```javascript
{ 
      title: "Ash Stowe",
      image: "https://static.wixstatic.com/media/b8f383e0fe2b478ea91362b707ef267b.jpg"
    }
```

If you want to retrieve data from an external source, this is where you place the call to retrieve that data.

After attempting to retrieve the data that corresponds to the incoming request, we check to see if any data was found:

```javascript
if (data) {
      // ...
    }
```

If nothing was found, the `if` is skipped and we return a 404 error using the [notFound()](http://wix.to/94BuAAs/wix-router.html#notFound) function.

`return notFound();`

Assuming we found the data we were looking for, we now prepare some header data for our page:

```javascript
const seoData = { 
      title: data.title, 
      description: `This is a description of ${data.title} page`,
      noIndex: false,
      metaTags: {
        "og:title": data.title,
        "og:image": data.image
      }
    };
```

Here we create a [HeadOptions](https://www.wix.com/velo/reference/wix-router/wixrouterresponse/head) object that defines what will be put in the HTML head of the page we respond to the request with. That object is stored in the `seoData` variable.

The sample code creates a `title` and `description` based on the `title` property of the retrieved `data` object. It also sets `noIndex` to false, meaning search engines should index the page. Finally, some `metaTags` properties are added as well.

You can create the [HeadOptions](https://www.wix.com/velo/reference/wix-router/wixrouterresponse/head) object using any information you want.

You can also add a `keywords` property to the [HeadOptions](https://www.wix.com/velo/reference/wix-router/wixrouterresponse/head) object with a string containing the page's keywords.

Finally, we return a [WixRouterResponse](http://wix.to/94BuAAs/wix-router.WixRouterResponse.html) object using the [ok()](http://wix.to/94BuAAs/wix-router.html#ok) function:

`return ok("myRouter-page", data, seoData);`

Here we route the user to the router page named `"myRouter-page"` and pass it the `data` that was retrieved and the `seoData` that was built for the page.

Depending on the situation, you can return a number of different responses from the [router()](http://wix.to/94BuAAs/wix-router.html#router) function. So far we've seen the [notFound()](http://wix.to/94BuAAs/wix-router.html#notFound) and [ok()](http://wix.to/94BuAAs/wix-router.html#ok) functions in use. You can also use the [forbidden()](http://wix.to/94BuAAs/wix-router.html#forbidden) function to return a 403 response, the [redirect()](http://wix.to/94BuAAs/wix-router.html#redirect) function to return a 301 or 302 response, or the [sendStatus()](http://wix.to/94BuAAs/wix-router.html#sendStatus) function to return a response with any status code you choose.

## Router Data

To use the data that was returned with a [WixRouterResponse](http://wix.to/94BuAAs/wix-router.WixRouterResponse.html) using the [ok()](http://wix.to/94BuAAs/wix-router.html#ok) function, use the `wix-window-frontend` [getRouterData()](http://wix.to/94BuAAs/wix-window-frontend.html#getRouterData) function.

For example, we can take the data passed by the sample router code and use it to present a person's information on the **myRouter-page** page that was created.

First, we need to add a text and image element to serve as placeholders for a person's title and image.

Next, in the page's code we retrieve the router data and set the text and image elements to display the `title` and `image` from the data.

```javascript
import wixWindowFrontend from 'wix-window-frontend';

$w.onReady(function () {
  let data = wixWindowFrontend.getRouterData();
  $w("#text1").text = data.title;
  $w("#image1").src = data.image;
});
```

If you preview the page, you'll see that the placeholders we put on the page are filled in with information from the data that was passed to the page. You can use the preview widget to see what the page looks like for any of the people in the `peopleData` object that was defined in the **routers.js** file.

The preview widget gets populated with the `title` values from the [WixRouterSitemapEntry](http://wix.to/94BuAAs/wix-router.WixRouterSitemapEntry.html) objects that are returned by the router's [sitemap()](http://wix.to/94BuAAs/wix-router.html#sitemap) function.

## Sitemap Function

Like the [router()](http://wix.to/94BuAAs/wix-router.html#router) function, the [sitemap()](http://wix.to/94BuAAs/wix-router.html#sitemap) function is named with the following convention:

`<router prefix>_Sitemap(sitemapRequest)`

So if you named your router **myRouter**, the code added to the **routers.js** file should look like:

`myRouter_Sitemap(sitemapRequest) { // routing code ...}`

The [sitemap()](http://wix.to/94BuAAs/wix-router.html#sitemap) function has a `sitemapRequest` parameter which receives a [WixRouterSitemapEntry](http://wix.to/94BuAAs/wix-router.WixRouterSitemapEntry.html) object that contains information about the incoming request. The object has information about the URL used to reach the router, the pages in the router, and who the request came from.

Typically, the [sitemap()](http://wix.to/94BuAAs/wix-router.html#sitemap) function creates a [WixRouterSitemapEntry](http://wix.to/94BuAAs/wix-router.WixRouterSitemapEntry.html) object for each item in the data used by the router. So, in our example, we create an entry for each person in the `personData` object. You also might want to include entries for other pages, like an index page or a search page.

Let's take a look at the sample [sitemap()](http://wix.to/94BuAAs/wix-router.html#sitemap) function code:

```javascript
export function myRouter_SiteMap(sitemapRequest) {

  // Convert the data to site map entries
  const siteMapEntries = Object.keys(peopleData).map( (name) => {
    const data = peopleData[name];
    const entry = new WixRouterSitemapEntry(name);
    entry.pageName = "myRouter-page"; // The name of the page in the Wix Editor to render
    entry.url = `/myRouter/${name}`; // Relative URL of the page
    entry.title = data.title;   // For better SEO - Help Google
    return entry;
  } );

  // Return the site map entries
  return siteMapEntries;
}
```

The [sitemap()](http://wix.to/94BuAAs/wix-router.html#sitemap) function takes the keys of the `peopleData` object and uses the JavaScript `map()` function to create an array of [WixRouterSitemapEntry](http://wix.to/94BuAAs/wix-router.WixRouterSitemapEntry.html) objects, one object for each key. Each entry is given values for the `pageName`, `url`, and `title` properties. Then the array is wrapped in a `Promise` and returned.

A sitemap entry can also contain `changeFrequecy`, `lastModified`, and `priority` properties to give search engines more information about each page.

In a case where you're using a router with external data, in the [sitemap()](http://wix.to/94BuAAs/wix-router.html#sitemap) function you would retrieve that data and build sitemap entries for each item that was retrieved.
