CodeAPI

wix-router

This module contains the APIs for code routers and data binding router hooks.

The code for both routers and data binding router hooks are defined in the routers.js file in the Backend section of the Site Structure sidebar.

The functions are named with the following convention:

 export function <router prefix>_<function name>()

These are not functions that you call in your code, rather they are functions that you define. They are called when your users browse to a URL that is handled by a router as described below.

For example, the following code creates a router on the myRouter prefix that shows a page when the path begins with the word "good" and returns a 404 in all other cases.

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

 export function myRouter_Router(request) {

   // URL looks like:
   // https://mysite.com/myRouter/good
   // or:
   // https://user.wixsite.com/mysite/myRouter/good
   const status = request.path[0];

   if(status === "good") {
     // Show a page
     return ok("myRouter-page");
   }
   else {
     // Return 404
     return notFound();
   }
 }

Code Router

Code your own router() and sitemap() functions for a router that handles all incoming requests with a specified URL prefix. Your code decides what actions to perform, what responses to return, where to route the request, and what data to pass to pages.

Data Binding Router Hooks

When a request comes in for a page that a router handles, either a code router or a dynamic page, you can add data binding router hooks to intercept the process of the data getting bound to the page at certain points and insert additional logic.

The hooks you can use are listed here in the order they are triggered:

  • beforeRouter
    • Before the data binding router logic.
  • customizeQuery
    • As the data binding router prepares a data query.
  • afterRouter
    • After the data binding router completes its logic, but before the page is displayed.
  • afterSitemap
    • After the data binding sitemap function completes preparing the list of urls.

Table of Contents

FUNCTIONS

?
Perform actions on an object.
afterRouter( )Registers a hook that is called after a router.
afterSitemap( )Registers a hook that is called after a sitemap is created.
beforeRouter( )Registers a hook that is called before a router.
customizeQuery( )Registers a hook that is called after a route is resolved by the data binding router, but before the wix-data query is executed.
forbidden( )Returns a response with a status code 403 (Forbidden) and instructs the router to show a 403 page.
next( )Returns a response that instructs the router to continue.
notFound( )Returns a response with a status code 404 (Not Found) and instructs the router to show a 404 page.
ok( )Returns a response with a status code 200 (OK) and instructs the router to show the selected page.
redirect( )Returns a response with a status code of 301 (Moved Permanently) or 302 (Found) and instructs the router to redirect to the given URL.
router( )Function containing routing logic for a given URL prefix.
sendStatus( )Returns a response with the specified HTTP status code with an optional message.
sitemap( )Function containing sitemap logic for a given URL prefix.

afterRouter( )

Registers a hook that is called after a router.

Description

The afterRouter hook is a data binding router hook that is triggered after the router with the specified prefix has bound the data, but before the page is displayed.

The afterRouter() function is not a function that you call from your code. You define the function in a file named routers.js in your site's Backend section. The function is called as described above.

Use this hook to change the router's response based on the data that was retrieved. For example, you can have two versions of a page, one for portrait oriented images and another for landscape oriented ones. After the image is pulled from the database, you can show the page that corresponds to the image's orientation.

The function receives a WixRouterRequest object containing information about the incoming request and a WixRouterResponse object containing information about the router's response.

The function returns a WixRouterResponse object that causes the router to respond with a specified page, specified data, and a success response code, or respond with any other HTTP response code. The returned response can be either the response received or a new response that overrides the one received.

If the function does not return a WixRouterResponse, the response received as the response parameter acts as the effective router response.

Typically, the response is created using one of the ok(), forbidden(), notFound(), redirect(), or sendStatus() functions.

See Also

ok(), forbidden(), notFound(), redirect(), sendStatus()

Syntax

function afterRouter(request: WixRouterRequest, response: WixRouterResponse): Promise<WixRouterResponse>
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Fulfilled - A router response, either the response received or a new response.

Examples

After router stub

This example creates an after router hook on the myRouter prefix.
// In routers.js

export function myRouter_afterRouter(request, response) {
  // after router code ...
}

Basic after router hook

This example creates an after router hook on the myRouter prefix that possibly reroutes the request depending on some conditions.

// In routers.js

import {ok, forbidden} from 'wix-router';

export function myRouter_afterRouter(request, response) {
  if (some_condition)
    return ok("different-page", response.data, response.head);
  else if (other_condition)
    return response;
  else
    return forbidden();
}

After router hook that reroutes based on response data

This example creates an after router hook on the myRouter prefix that checks the orientation of a picture in the response's data and routes to a page that is built for diplaying pictures in that orientation.

// In routers.js

import {ok} from 'wix-router';

export function myRouter_afterRouter(request, response) {
  if(response.status === 200 && response.page === "horizontal-pic") {
    if(response.data.picture.orientation === "vertical")
      return ok("vertical-pic", response.data, response.head);
    else
      return response;
  }

  return response;
}

afterSitemap( )

Registers a hook that is called after a sitemap is created.

Description

The afterSitemap hook is a data binding router hook that is triggered after a sitemap is created for the specified router.

The afterSitemap() function is not a function that you call from your code. You define the function in a file named routers.js in your site's Backend section. The function is called as described above.

Use this hook to revise the list of pages in your sitemap. For example, you can add a search page's information to your sitemap.

The function returns an array of WixRouterSitemapEntry objects. Typically the returned array is a modified version of the one the function received.

If the function does not return a WixRouterSitemapEntry array, the array received as the sitemapEntries parameter acts as the router's effective sitemap entries.

Syntax

function afterSitemap(request: WixRouterSitemapRequest, sitemapEntries: Array<WixRouterSitemapEntry>): Promise<Array<WixRouterSitemapEntry>>
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Promise<Array<WixRouterSitemapEntry>>
Fulfilled - A sitemapEntries array.

Examples

After sitemap stub

This example creates an after sitemap hook on the myRouter prefix.
// In routers.js

export function myRouter_afterSitemap(sitemapRequest, sitemapEntries) {
  // after sitemap code ...
}

Add a search page to the sitemap

This example creates an after sitemap hook on the myRouter prefix that adds a search page to the sitemap. Note that the sitemap function only publishes a URL for the search page. To actually implement a page at this URL you can use a beforeRouter() hook to check for the request for the search page URL and route the user to a search page.

// In routers.js

import {WixRouterSitemapEntry} from 'wix-router';

export function myRouter_afterSitemap(sitemapRequest, sitemapEntries) {
  let prefix = sitemapRequest.prefix;
  let entry = new WixRouterSitemapEntry(`${prefix}/search`);
  sitemapEntries.push(entry);
  return sitemapEntries;
}

beforeRouter( )

Registers a hook that is called before a router.

Description

The beforeRouter hook is a data binding router hook that is triggered before the router with the specified prefix has bound the data to the page.

The beforeRouter() function is not a function that you call from your code. You define the function in a file named routers.js in your site's Backend section. The function is called as described above.

Use this hook to route requests to a different page or return an error response. For example, you can check who is requesting the page and then decide based on the user's role whether to let the router continue to the next step or to return an error type response code.

The function receives a WixRouterRequest object containing information about the incoming request.

The function returns a WixRouterResponse object that causes the router to continue its routing, or respond with an HTTP response code.

Typically, the response is created using one of the next(), forbidden(), notFound(), redirect(), or sendStatus() functions.

See Also

next(), forbidden(), notFound(), redirect(), sendStatus()

Syntax

function beforeRouter(request: WixRouterRequest): Promise<WixRouterResponse>
PARAMETERS
?
The kind of data the property stores.
request
The routing request.
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Fulfilled - Which page to display, redirect to, or which HTTP status code to respond with.

Examples

Before router stub

This example creates a before router hook on the myRouter prefix.
// In routers.js

export function myRouter_beforeRouter(request) {
  // before router code ...
}

Basic before router hook

This example creates a before router hook on the myRouter prefix that continues with the request if some_condition is true and returns a 403 in all other cases.

// In routers.js

import {forbidden, next} from 'wix-router';

export function myRouter_beforeRouter(request) {
  if (some_condition)
    return next();
  else
    return forbidden();
}

Before router hook that restricts access based on user role

This example creates a before router hook on the myRouter prefix that continues with the request as long as the path does not begin with "admin". If it does, the hook checks to see if the user is the site owner before continuing.

// In routers.js

import {forbidden, next} from 'wix-router';

export function myRouter_beforeRouter(request) {
  if (request.path.length > 1 && request.path[0] === "admin") {
    if (request.user && request.user.role == "Admin")
      return next();
    else
      return forbidden();
  }

  return next();
}

customizeQuery( )

Registers a hook that is called after a route is resolved by the data binding router, but before the wix-data query is executed.

Description

The customizeQuery hook is a data binding router hook that is triggered before the data query is executed for the pages in the specified router.

The customizeQuery() function is not a function that you call from your code. You define the function in a file named routers.js in your site's Backend section. The function is called as described above.

Use this hook to further refine or change the query that will determine what data is bound to your page's dataset. For example, you can filter the query to only return items that have a status field set to "active".

The function returns a WixDataQuery object. Typically the returned query is a modified version of the one the function received.

The customizeQuery() hook is triggered when using dynamic pages, but not when you code your own router.

Syntax

function customizeQuery(request: WixRouterRequest, route: string, query: WixDataQuery): WixDataQuery
PARAMETERS
?
The kind of data the property stores.
request
The routing request.
route
string
The resolved router URL pattern.
query
The wix-data query.
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
A wix-data query.

Examples

Customize query stub

This example creates a customize query hook on the myRouter prefix.
// In routers.js

export function myRouter_customizeQuery(request, route, query) {
  // customize query code ...
}

Filter query to return on active users

This example creates a customize query hook on the myRouter prefix that filters the query for a certain route to only query for active users.

// In routers.js

export function myRouter_customizeQuery(request, route, query) {
  if (route === "/users/{name}")
    return query.eq("status", "active");
  else
    return query;
}

forbidden( )

Returns a response with a status code 403 (Forbidden) and instructs the router to show a 403 page.

Description

The forbidden() function is used in the router(), beforeRouter(), and afterRouter() hooks to indicate that the requested page is forbidden. Optionally, you can pass a message that otherwise defaults to 'Forbidden'.

See Also

router( ), beforeRouter( ), afterRouter( )

Syntax

function forbidden([message: string]): Promise<WixRouterResponse>
PARAMETERS
?
The kind of data the property stores.
message(Optional)
string
The message to show.
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Fulfilled - A response object with HTTP status code 403.

Examples

Create a forbidden response

import {forbidden} from 'wix-router';

export function myRouter_Router(request) {

  return forbidden();
}

next( )

Returns a response that instructs the router to continue.

Description

The next() function is used in the beforeRouter() hook to indicate the hook has completed and the routing should continue to the data binding router.

See Also

beforeRouter( )

Syntax

function next(): Promise<WixRouterResponse>
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Fulfilled - The router response.

Examples

Create a response to continue routing

import {next} from 'wix-router';

export function myRouter_beforeRouter(request) {

  return next();
}

notFound( )

Returns a response with a status code 404 (Not Found) and instructs the router to show a 404 page.

Description

The notFound() function is used in the router(), beforeRouter(), and afterRouter() hooks to indicate that the requested page was not found. Optionally, you can pass a message that otherwise defaults to "Not Found".

See Also

router( ), beforeRouter( ), afterRouter( )

Syntax

function notFound([message: string]): Promise<WixRouterResponse>
PARAMETERS
?
The kind of data the property stores.
message(Optional)
string
The message to show.
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Fulfilled - A response object with HTTP status code 404.

Examples

Create a not found response

import {notFound} from 'wix-router';

export function myRouter_Router(request) {

  return notFound();
}

ok( )

Returns a response with a status code 200 (OK) and instructs the router to show the selected page.

Description

The ok() function is used in the router() and afterRouter() hooks to continue the routing process to the specified page with a successful HTTP response code. The specified page must be a page found under the given router in the Site Structure sidebar. For example, if you want to route to myRouter-page from the myRouter_Router() function, myRouter-page must be in the MyRouter Pages (Router) section of your site's Site Structure sidebar. To learn more about router pages in the Site Structure sidebar, see Working with the Site Structure Sidebar.

Optionally, you can pass a data object to be used by the page routed to and header options for the page. The page routed to accesses the data passed to it using the getRouterData() function of wix-window. with optional data and HTML header.

See Also

router( ), afterRouter( )

Syntax

function ok(Page: string | Array<string>, [routerReturnedData: Object], [head: HeadOptions]): Promise<WixRouterResponse>
PARAMETERS
?
The kind of data the property stores.
Page
string | Array<string>
A router page or an array of page fallbacks.
routerReturnedData(Optional)
Object
A data object.
head(Optional)
HTML head members of the response.
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Fulfilled - The router response object.

Examples

Create an okay response

import {ok} from 'wix-router';

export function myRouter_Router(request) {

  return ok("router-page");
}

Create an okay response with data and head options

import {ok} from 'wix-router';

export function myRouter_Router(request) {

  return ok("router-page", dataObj, headOpts);
}

Create an okay response with data and head options

import {ok} from 'wix-router';

export function myRouter_Router(request) {

  let dataObj = {
    "field1": "value1",
    "field2": "value2"
  };

  let headOptions = {
    "title": "A page title",
    "description": "A page description",
    "keywords": "wix code example",
    "noIndex": true,
    "metaTags": {
      "copyright": "Wix.com",
      "Classification": "Example",
      "og:title": "The Rock",
      "og:image": "http://ia.media-imdb.com/rock.jpg"
    }
  };

  return ok("router-page", dataObj, headOptions);
}

redirect( )

Returns a response with a status code of 301 (Moved Permanently) or 302 (Found) and instructs the router to redirect to the given URL.

Description

The redirect() function is used in the router(), beforeRouter(), and afterRouter() hooks to redirect to a page that is not the requested page.

Optionally, you can pass a status code of "301" or "302" using the statusCode parameter. If any other status code is passed or no status code is passed at all, the status code defaults to "302".

See Also

router( ), beforeRouter( ), afterRouter( )

Syntax

function redirect(url: string, [statusCode: string]): Promise<WixRouterResponse>
PARAMETERS
?
The kind of data the property stores.
url
string
The url to redirect to.
statusCode(Optional)
string
The status code to use.
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Fulfilled - The redirect response object.

Examples

Create a redirect response

import {redirect} from 'wix-router';

export function myRouter_Router(request) {

  return redirect("http://myothersite.com");
}

Create a redirect response with HTTP code 301

import {redirect} from 'wix-router';

export function myRouter_Router(request) {

  return redirect("http://myothersite.com", "301");
}

router( )

Function containing routing logic for a given URL prefix.

Description

The router() function handles all incoming requests with the specified URL prefix. It is responsible for deciding which page to diplay and what data to pass to the page, where to redirect to, or which HTTP status code to respond with.

The router() function is not a function that you call from your code. You define the function in a file named routers.js in your site's Backend section. The function is called when your users browse to a URL that is handled by the router with the specified prefix.

The function receives a WixRouterRequest object containing information about the incoming request.

The function returns a WixRouterResponse object that causes the router to respond with a specified page, specified data, and a success response code, or respond with any other HTTP response code.

Typically, the response is created using one of the ok(), forbidden(), notFound(), redirect(), or sendStatus() functions.

Data that is returned as part of the WixRouterResponse is accessed in the page code of the page that was routed to using the getRouterData() function of wix-window.

You can also set members of the HTML head of the response using the response's HeadOptions parameter.

Note

In a request URL, spaces are replaced with dashes (-). For example, a request for /animals/killer whale or /animals/killer%20whale will be received in the request as /animals/killer-whale. Therefore, when searching for the data that matches the incoming request, you need to take special care if the path contains dashes (-).

See Also

ok(), forbidden(), notFound(), redirect(), sendStatus()

Syntax

function router(request: WixRouterRequest): Promise<WixRouterResponse>
PARAMETERS
?
The kind of data the property stores.
request
The routing request.
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Fulfilled - Which page to display, redirect to, or which HTTP status code to respond with.

Examples

Router stub

This example creates a router on the myRouter prefix.
export function myRouter_Router(request) {
  // router code ...
}

Basic router

This example creates a router on the myRouter prefix that shows a page when the path begins with the word "good" and returns a 404 in all other cases.

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

export function myRouter_Router(request) {

  // URL looks like:
  // https://mysite.com/myRouter/good
  // or:
  // https://user.wixsite.com/mysite/myRouter/good
  const status = request.path[0];

  if(status === "good") {
    // Show a page
    return ok("myRouter-page");
  }
  else {
    // Return 404
    return notFound();
  }
}

A router with static data

This example creates a router on the myRouter prefix that shows a page when the path begins with a name that is found in a static data object. The appropriate data and HTML head options are also passed in the response. If the requested item does not exist, a 404 "Not Found" response is returned.

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

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

export function myRouter_Router(request) {

  // Get item name from URL request
  // URL looks like:
  // https://mysite.com/myRouter/Morgan
  // or:
  // https://user.wixsite.com/mysite/myRouter/Morgan
  const name = request.path[0];

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

  // If the item exists
  if(data) {

    //Define SEO tags
    const seoData = {
      title: data.title,
      description: `This is a description of ${data.title} page`,
      noIndex: false,
      metaTags: {
        "og:title": data.title,
        "og:image": data.imageSite + data.image
      }
    };

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

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

A router with data from a collection

This example creates a router on the myRouter prefix that shows an index page when the path is empty. If the path contains an item title, that title is looked up in a collection. If the item is found in the collection, it shows an item page and passes the item data. If the item is not found in the collection, a 404 "Not Found" response is returned.

import wixData from 'wix-data';
import {ok, notFound} from 'wix-router';

export function myRouter_router(request) {

  // Empty path - show index page
  // URL looks like:
  // https://mysite.com/myRouter
  // or:
  // https://user.wixsite.com/mysite/myRouter
  if (request.path.length < 1) {
    return ok("index-page");
  }

  // Path with item - show item page with data from collection
  // URL looks like:
  // https://mysite.com/myRouter/itemTitle
  // or:
  // https://user.wixsite.com/mysite/myRouter/itemTitle
  // Retrieve data from collection
  return wixData.query("myCollection")
    .eq("title", request.path[0])
    .find()
    .then( (queryResult) => {
      if (queryResult.length > 0) {
        return ok("item-page", queryResult.items[0]);
      }
      return notFound();
    } );
}

sendStatus( )

Returns a response with the specified HTTP status code with an optional message.

Description

The sendStatus() function is used in the router(), beforeRouter(), and afterRouter() hooks to return a specified response. Optionally, you can pass a message.

See Also

router( ), beforeRouter( ), afterRouter( )

Syntax

function sendStatus(statusCode: string, [message: string]): Promise<WixRouterResponse>
PARAMETERS
?
The kind of data the property stores.
statusCode
string
The HTTP status code to return.
message(Optional)
string
The message to write as the HTTP body.
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Fulfilled - A response object with the specified HTTP status.

Examples

Create a response with a specified status code

import {sendStatus} from 'wix-router';

export function myRouter_Router(request) {

  return sendStatus("418");
}

Create a response with a specified status code and message

import {sendStatus} from 'wix-router';

export function myRouter_Router(request) {

  return sendStatus("418", "Message");
}

sitemap( )

Function containing sitemap logic for a given URL prefix.

Description

The sitemap() function handles sitemap requests for pages with the specified URL prefix. Use this function to make sure search engines can find the links to your router's pages.

The sitemap() function is not a function that you call from your code. You define the function in a file named routers.js in your site's Backend section. The function is called when a sitemap request is received for the router with the specified prefix.

The function receives a WixRouterSitemapRequest object containing information about the incoming sitemap request.

The function returns an array of WixRouterSitemapEntry objects each of which includes information about a page, such as its URL, title, and name.

To create sitemap entry objects, first import WixRouterSitemapEntry from wix-router:

 import {WixRouterSitemapEntry} from "wix-router";

The sitemap() function is also used to populate the items preview widget, allowing you to switch between URLs in preview mode.

Syntax

function sitemap(request: WixRouterSitemapRequest): Promise<Array<WixRouterSitemapEntry>>
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Promise<Array<WixRouterSitemapEntry>>
Fulfilled - An array of sitemap entries.

Examples

Sitemap stub

This example creates a sitemap on the myRouter prefix.
// In routers.js

export function myRouter_SiteMap(sitemapRequest) {
  // sitemap code ...
}

Basic sitemap

This example creates a sitemap on the myRouter prefix by looping through a data object and creating a sitemap entry for each object.

// In routers.js

import {WixRouterSitemapEntry} from 'wix-router';

export function myRouter_SiteMap(sitemapRequest) {

  let siteMapEntries = [];

  // Create a sitemap entry for each item
	for (var key in myData) {
    let entry = new WixRouterSitemapEntry(key);
    entry.pageName = "myRouter-page";
    entry.url = "/myRouter/" + key;
    entry.title = myData[key].title;
    siteMapEntries.push(entry);
	}

  // Return the sitemap entries
  return siteMapEntries;
}

A sitemap with static data

This example creates a sitemap on the myRouter prefix by mapping an object's keys to an array of corresponding sitemap entries.

// In routers.js

import {WixRouterSitemapEntry} from 'wix-router';

// Sample data
const peopleData = {
   "Ash": {
     title:     "Ash Stowe",
     imageSite: "http://static.wixstatic.com/media/",
     image:     "b8f383e0fe2b478ea91362b707ef267b.jpg"
    },
   "Aiden": {
    title:      "Aiden Johnson",
    imageSite:  "http://static.wixstatic.com/media/",
    image:      "ca3c7ac5427e43928aa5f3f443ae2163.jpg"
   },
   "Jess": {
    title:      "Jess White",
    imageSite:  "http://static.wixstatic.com/media/",
    image:      "147fe6f37fe24e83977b4124e41b6d3d.jpg"

   },
   "Morgan": {
    title:      "Morgan James",
    imageSite:  "http://static.wixstatic.com/media/",
    image:      "59e1f2f4dbbc4f7c9d6e66e3e125d830.jpg"
   }
};

export function myRouter_SiteMap(sitemapRequest) {

  //Convert the data to sitemap entries
  const siteMapEntries = Object.keys(peopleData).map( (name) => {
    const data = peopleData[name];
    const entry = new WixRouterSitemapEntry(name);
    entry.pageName = "myRouter-page";
    entry.url = `/myRouter/${name}`;
    entry.title = data.title;
    return entry;
  } );

  // Return the sitemap entries
  return siteMapEntries;
}