Remote Functions

Overview

Remote functions are JavaScript functions that are executed on the server-side under the hood without the need to care about the api endpoint used to do the job. It's a revolutionary feature that makes it easier to debug and maintain the interaction between the client and the server.

Usage

As a remote function is meant to appear as an ordinary client-side JavaScript function, it's exported as any other function from a NodeJS module whose filename is suffixed with .remote.js.

// timezone.remote.js

export const getTimezone = async (lat=31.20, long=29.92) => {
  const response = await fetch(`https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${long}&timezone=auto`);
  const data = await response.json();
  return {
    name: data["timezone"],
    abbr: data["timezone_abbreviation"],
    offset: data["utc_offset_seconds"],
  };
};
// App.jsx

import { getTimezone } from "./timezone.remote.js";

export default function App() {
  let $name = null;
  let $abbr = null;
  let $offset = null;
  getTimezone().then(({ name, abbr, offset }) => {
    $name = name;
    $abbr = abbr;
    $offset = offset;
  });
  return (
    <div>
      <h1>Timezone Information</h1>
      <p>City: Alexandria, Egypt</p>
      <ul>
        <li>Name: {$name}</li>
        <li>Abbreviation: {$abbr}</li>
        <li>Offset: {$offset}</li>
      </ul>
    </div>
  );
}

Limitations

As an implication of executing the function on the server-side, the following limitations apply:

  • Function has to be asynchronous and return a promise.
  • Disability to access anything on the client-side other than the arguments passed.
  • Arguments passed to the function are serialized and deserialized using JSON.
  • Values returned from the function are serialized and deserialized using JSON.

Browser Support

Remote functions rely on the Promise API which is supported by all modern browsers, but not by old browsers like Internet Explorer. Check the full list of supported browsers here.