Data access in Remix React.js web applications

Remix vastly simplifies access to backend processes by auto-generating all API calls between the browser and the web server. We only need to create the “loader()” function to get data from the server and the “action()” function to submit a form.

Reading Environment variable values

For security reasons the Node.js web application environment variables are not available in the browser, as those usually contain sensitive information, like database access credentials.

The “loader()” function can read and expose selected environment variables to the browser via the API.

Make sure you have created the /app/routes/_footer.tsx file to display the name of the environment. See Footer in the previous post.

Add the “loader()” function

  • Add the loader() function to the _index.tsx page to get the value of the “environment” environment variable.
  • We will pass the “environment” variable to the Footer to display the value there.
import { LoaderArgs, json} from "@remix-run/node";
import { useLoaderData } from "@remix-run/react";

export default function Index() {

  // -----------------------------------------
  // Get the data from the server side

  // Use "|| {}" to avoid TypeError: Cannot destructure property 'incidents' of 'useLoaderData(...)' as it is null.
  const { environment} = useLoaderData<typeof loader>() || {} ;
  
  // -----------------------------------------


  return (
    <div style={{ fontFamily: "system-ui, sans-serif", lineHeight: "1.8" }}>

      {/* Display the Header component */}
      <Header />

      <div className="pagecontent">
        Hello
      </div>

      {/* Display the Footer component */}
      <Footer environment={environment} />

    </div>
  );
}

Leave a comment

Your email address will not be published. Required fields are marked *