Defines a backend function that can be called from the frontend.
The webMethod()
function is a wrapper used to export functions from backend code that can be called from the frontend.
The permissions
parameter is used to define which site visitors have permission to call the function produced by webMethod()
. Import the Permissions
enum from @wix/web-methods
to define the permissions.
Caution: Be careful when selecting a permission, as exposing a function with the wrong permissions can create security risks.
The options
parameter contains the cache
object which allows you to temporarily store the return values from web methods on Wix's infrastructure. When there are significant updates made to your site's data, call Invalidate Cache to clear caches, ensuring your site remains up to date for your visitors.
Important: The web method caching feature is currently only supported for developing sites.
Web methods must be defined in a file:
.web.js
extension when developing sites or apps in Blocks..web.ts
extension when developing apps using the CLI.function webMethod(
permissions: Permissions,
webFunction: Function,
options: Options,
): Function;
Name | Type | Description |
---|---|---|
permissions | Permissions | Permissions needed to call the function in frontend code. Permission options: - Permissions.Anyone : Any site visitor can call the function.- Permissions.Admin : Only site admins can call the function.- Permissions.SiteMember : Only site members can call the function. |
webFunction | Function | Function to wrap with webMethod() . This function must return serializable results. This function can be asynchronous. Note: You may need to elevate the permissions of API calls made in this function. |
options | Options | Web method options. |
options.cache | Cache | Criteria for caching the return value of the webFunction being passed. |
options.cache.tags | Array<string> | Required A list of tags used for categorizing and identifying cached return values. These tags are essential for managing and invalidating caches when necessary. |
options.cache.ttl | Number | Specifies the Time to Live (TTL) for cached return values, measured in seconds. This value indicates how long data remains in the cache before it is considered stale. Default: 604800 seconds (1 week). |
Function
The function specified in the webMethod()
call, wrapped with the webMethod()
function. This wrapped function always returns a promise that resolves to the response from the original function you provided.
import { webMethod, Permissions } from "@wix/web-methods";
export const multiply = webMethod(
Permissions.Anyone,
(a: number, b: number) => a * b,
);
With caching implemented
import { webMethod, Permissions } from "@wix/web-methods";
export const multiply = webMethod(
Permissions.Anyone,
(a: number, b: number) => a * b,
{
cache: {
tags: ["multiply", "math"],
},
},
);
Note: The passed function can be asynchronous, and must return serializable results.