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
Returns
Fulfilled - Which page to display, redirect to, or which HTTP status code to respond with.
Return Type:
Related Content:
Was this helpful?
This example creates a router on the myRouter
prefix.
1export function myRouter_Router(request) {2 // router code ...3}4
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.
1import {ok, notFound} from "wix-router";23export function myRouter_Router(request) {45 // URL looks like:6 // https://mysite.com/myRouter/good7 // or:8 // https://user.wixsite.com/mysite/myRouter/good9 const status = request.path[0];1011 if(status === "good") {12 // Show a page13 return ok("myRouter-page");14 }15 else {16 // Return 40417 return notFound();18 }19}20
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.
1import {ok} from "wix-router";23export function myRouter_Router(request) {4 if(request.formFactor === "desktop") {5 // Show desktop page6 return ok("desktop-page");7 }8 else {9 // Show mobile page10 return ok("mobile-page");11 }12}13
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.
1import {ok, notFound} from "wix-router";23// Sample data4const 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};2627export function myRouter_Router(request) {2829 // Get item name from URL request30 // URL looks like:31 // https://mysite.com/myRouter/Morgan32 // or:33 // https://user.wixsite.com/mysite/myRouter/Morgan34 const name = request.path[0];3536 // Get the item data by name37 const data = peopleData[name];3839 // If the item exists40 if(data) {4142 //Define SEO tags43 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.image50 }51 };5253 // Render item page, passing data and head info54 return ok("myRouter-page", data, seoData);55 }5657 // Return 404 if the item is not found58 return notFound();59}60
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.
1import wixData from 'wix-data';2import {ok, notFound} from 'wix-router';34export function myRouter_Router(request) {56 // Empty path - show index page7 // URL looks like:8 // https://mysite.com/myRouter9 // or:10 // https://user.wixsite.com/mysite/myRouter11 if (request.path.length < 1) {12 return ok("index-page");13 }1415 // Path with item - show item page with data from collection16 // URL looks like:17 // https://mysite.com/myRouter/itemTitle18 // or:19 // https://user.wixsite.com/mysite/myRouter/itemTitle20 // Retrieve data from collection21 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
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.
1// Place this code in the routers.js file2// of your site's Backend section.34import {ok, notFound} from "wix-router";5import wixData from 'wix-data';67export async function helloworld_Router(request) {8 console.log('Hello World router is routing...');910 if (!request.path[0]) {11 const { items: greetings } = await wixData.query('Greetings').find();1213 const seoData = {14 title: 'Greetings Index',15 description: 'Index of greetings',16 noIndex: false17 };1819 return ok('index-page', greetings, seoData);20 } else {21 const { items: greetings } = await wixData.query('Greetings')22 .eq('slug', request.path[0])23 .find();2425 if (greetings.length > 0) {26 const greeting = greetings[0];2728 const seoData = {29 title: greeting.title,30 metaTags: [{31 name: 'description',32 content: greeting.description33 }, {34 name: 'og:title',35 content: greeting.title36 }],37 };3839 return ok('item-page', greeting, seoData);40 } else {41 return notFound();42 }43 }44}45