Search.../

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 router can be a code router or the data binding router that binds data to a dynamic 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 the Code File's Backend section of the Velo Sidebar. The function is called as described above.

Use this hook with a code router 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.

Syntax

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

beforeRouter 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?

Before router stub

This example creates a before router hook on the myRouter prefix.

Copy Code
1// In routers.js
2
3export function myRouter_beforeRouter(request) {
4 // before router code ...
5}
6
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.

Copy Code
1// In routers.js
2
3import {forbidden, next} from 'wix-router';
4
5export function myRouter_beforeRouter(request) {
6 if (some_condition)
7 return next();
8 else
9 return forbidden();
10}
11
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.

Copy Code
1// In routers.js
2
3import {forbidden, next} from 'wix-router';
4
5export function myRouter_beforeRouter(request) {
6 if (request.path.length > 1 && request.path[0] === "admin") {
7 if (request.user && request.user.role == "Admin")
8 return next();
9 else
10 return forbidden();
11 }
12
13 return next();
14}
15