visit
Web modules are exclusive to Velo and enable you to write functions that
run server-side in the backend, and easily call them in your client-side code. With web modules you can import functions from backend into files or scripts in page code or public files, knowing they will run server-side in the backend. Velo handles all the client-server communication required to enable this access. See the advanced tip below if you want to know how this communication is handled.
Advanced: How Web Modules Work - Behind the Scenes
When you import a web module on the client-side you get a proxy function to the web module function. This proxy function uses an XMLHttpRequest to invoke the function in the backend. The runtime listens to those
invocations and calls the appropriate function.
// Filename: backend/sendEmail.jsw (web modules need to have a *.jsw* extension)
import {fetch} from 'wix-fetch';
// wix-fetch is the API we provide to make https calls in the backend
const API_KEY = "the api key for the backend service that sends email";
export function sendEmail (address, subject, body) {
return fetch("//a-backend-service-that-sends-email.com/send?APIKey=" + API_KEY, {
method: 'post',
body: JSON.stringify({address, subject, body})
}).then(function(response) {
if (response.status >= 200 && response.status < 300)
return response.text();
else
throw new Error(response.statusText);
});
};
import {sendEmail} from 'backend/sendEmail.jsw';
export function sendButton_onClick(event) {
sendEmail(
$w("#addressInput").value,
$w("#subjectInput").value,
$w("#bodyInput").value)
.then(function() {
console.log("email was sent");
}
);
}
Using Web Module Functions in Backend
You can import a web module function into another module in backend.// Filename: aModule.jsw (web modules need to have a *.jsw* extension)
export function multiply(factor1, factor2) {
return factor1 * factor2;
}
import {multiply} from 'backend/aModule';
multiply(4,5).then(function(product) {
console.log(product);
// Logs: 20
});
You can log messages to the console in web modules and they will be
displayed in the client's console log, even though the code is running in the backend.
Previously published at