Search.../

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 display 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 the Code File's Backend section of the Velo Sidebar. 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-frontend.

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

Notes:

  • The router() function also runs when you navigate to a router page in the Editor.

  • 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 (-).

Syntax

function router(request: WixRouterRequest): Promise<WixRouterResponse>

router Parameters

NAME
TYPE
DESCRIPTION
request

The routing request.

Returns

Fulfilled - Which page to display, redirect to, or which HTTP status code to respond with.

Return Type:

Was this helpful?

Router stub

This example creates a router on the myRouter prefix.

Copy Code
1export function myRouter_Router(request) {
2 // router code ...
3}
4
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.

Copy Code
1import {ok, notFound} from "wix-router";
2
3export function myRouter_Router(request) {
4
5 // URL looks like:
6 // https://mysite.com/myRouter/good
7 // or:
8 // https://user.wixsite.com/mysite/myRouter/good
9 const status = request.path[0];
10
11 if(status === "good") {
12 // Show a page
13 return ok("myRouter-page");
14 }
15 else {
16 // Return 404
17 return notFound();
18 }
19}
20
Router that checks requesting devices form factor

This example creates a router on the myRouter prefix that shows a desktop version of a page when the requesting devices form factor is a desktop. If the form factor of the requesting device is not a desktop, the router shows a mobile version of the page.

Copy Code
1import {ok} from "wix-router";
2
3export function myRouter_Router(request) {
4 if(request.formFactor === "desktop") {
5 // Show desktop page
6 return ok("desktop-page");
7 }
8 else {
9 // Show mobile page
10 return ok("mobile-page");
11 }
12}
13
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.

Copy Code
1import {ok, notFound} from "wix-router";
2
3// Sample data
4const peopleData = {
5 "Ash": {
6 title: "Ash Stowe",
7 imageSite: "https://static.wixstatic.com/media/",
8 image: "b8f383e0fe2b478ea91362b707ef267b.jpg"
9 },
10 "Aiden": {
11 title: "Aiden Johnson",
12 imageSite: "https://static.wixstatic.com/media/",
13 image: "ca3c7ac5427e43928aa5f3f443ae2163.jpg"
14 },
15 "Jess": {
16 title: "Jess White",
17 imageSite: "https://static.wixstatic.com/media/",
18 image: "147fe6f37fe24e83977b4124e41b6d3d.jpg"
19 },
20 "Morgan": {
21 title: "Morgan James",
22 imageSite: "https://static.wixstatic.com/media/",
23 image: "59e1f2f4dbbc4f7c9d6e66e3e125d830.jpg"
24 }
25};
26
27export function myRouter_Router(request) {
28
29 // Get item name from URL request
30 // URL looks like:
31 // https://mysite.com/myRouter/Morgan
32 // or:
33 // https://user.wixsite.com/mysite/myRouter/Morgan
34 const name = request.path[0];
35
36 // Get the item data by name
37 const data = peopleData[name];
38
39 // If the item exists
40 if(data) {
41
42 //Define SEO tags
43 const seoData = {
44 title: data.title,
45 description: `This is a description of ${data.title} page`,
46 noIndex: false,
47 metaTags: {
48 "og:title": data.title,
49 "og:image": data.imageSite + data.image
50 }
51 };
52
53 // Render item page, passing data and head info
54 return ok("myRouter-page", data, seoData);
55 }
56
57 // Return 404 if the item is not found
58 return notFound();
59}
60
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.

Copy Code
1import wixData from 'wix-data';
2import {ok, notFound} from 'wix-router';
3
4export function myRouter_Router(request) {
5
6 // Empty path - show index page
7 // URL looks like:
8 // https://mysite.com/myRouter
9 // or:
10 // https://user.wixsite.com/mysite/myRouter
11 if (request.path.length < 1) {
12 return ok("index-page");
13 }
14
15 // Path with item - show item page with data from collection
16 // URL looks like:
17 // https://mysite.com/myRouter/itemTitle
18 // or:
19 // https://user.wixsite.com/mysite/myRouter/itemTitle
20 // Retrieve data from collection
21 return wixData.query("myCollection")
22 .eq("title", request.path[0])
23 .find()
24 .then( (queryResult) => {
25 if (queryResult.length > 0) {
26 return ok("item-page", queryResult.items[0]);
27 }
28 return notFound();
29 } );
30}
31
Create a router that reads data from a collection

This example shows how to create a router that reads data from a collection. Depending on the URL used to reach the router, it then passes that data to an index page to display all the items in the collection, or to an individual item page to display detailed information about a specific item. You can test out the code in our example template.

Copy Code
1// Place this code in the routers.js file
2// of your site's Backend section.
3
4import {ok, notFound} from "wix-router";
5import wixData from 'wix-data';
6
7export async function helloworld_Router(request) {
8 console.log('Hello World router is routing...');
9
10 if (!request.path[0]) {
11 const { items: greetings } = await wixData.query('Greetings').find();
12
13 const seoData = {
14 title: 'Greetings Index',
15 description: 'Index of greetings',
16 noIndex: false
17 };
18
19 return ok('index-page', greetings, seoData);
20 } else {
21 const { items: greetings } = await wixData.query('Greetings')
22 .eq('slug', request.path[0])
23 .find();
24
25 if (greetings.length > 0) {
26 const greeting = greetings[0];
27
28 const seoData = {
29 title: greeting.title,
30 metaTags: [{
31 name: 'description',
32 content: greeting.description
33 }, {
34 name: 'og:title',
35 content: greeting.title
36 }],
37 };
38
39 return ok('item-page', greeting, seoData);
40 } else {
41 return notFound();
42 }
43 }
44}
45