Backend code called on page load is running twice

Global page code and code inside of onReady() will usually run twice by default, once in the backend and once in the browser.

You can use the .env property from the Rendering API to detect and choose which environment the page code runs in.

For example, the following code prevents a CMS item from being saved twice:

import wixData from 'wix-data';
import wixWindowFrontend from 'wix-window-frontend';

let toInsert = {
  "field1": "Some value",
  "field2": "Some other value"
};

$w.onReady(function () {
  if (wixWindowFrontend.rendering.env === "browser") {
    return wixData.insert("myCollection", toInsert)
      .then( (item) => {
        $w("#myText").text = item.title;
      } );
  }
} );

Learn more about the Page Rendering Process for sites built on Wix or Wix Studio in the following help article: