Code only works in preview mode(updating database)

This code was put into masterPage.js but only works when run in preview mode. The ip is obtained when run normally but the database is not updating.

import  { 

    fetch 
} 
**from**  'wix-fetch' ; 
import  wixData  **from**  'wix-data' ; 

$w . onReady ( **function**  () { 
    
    fetch (<ip getting website>, { 

            method :  'get' 

        }) 

        . then (( httpResponse ) => { 

            **if**  ( httpResponse . ok ) { 

                **return**  httpResponse . json (); 

            } 

        }) 

        . then (( json ) => { 
            
            **const**  ipaddress  =  json . query ; 
            **let**  city  =  json . city ; 
            **if**  ( city  !==  **null**  &&   city  !==  '' ) 
            { 
                //$w("#text6").text = json.query; //set city name for text27 in frontend. 
            **let**  toInsert  = { 
  
  
  "ip" :    json . query 
  
}; 
                //$w("#text6").text = json.query; //set city name is blank or null then it will show blank. 
wixData . insert ( "ips" ,  toInsert ). then (( item ) => { 
console . log ( item );  //see item below 
    }) 
  . **catch** (( err ) => { 
    console . log ( err ); 
  }); 
            } 
            **else** 
            { 

                //return '';\ 
                **let**  toInsert  = { 
  
  
  "ip" :    json . query 
  
}; 
                //$w("#text6").text = json.query; //set city name is blank or null then it will show blank. 
wixData . insert ( "ips" ,  toInsert ). then (( item ) => { 
console . log ( item );  //see item below 
    }) 
  . **catch** (( err ) => { 
    console . log ( err ); 
  }); 
            } 
            // return ipaddress; 
        }); 

});