CloudflarePages & Remix environment variables "context not defined" in loader

I’ve a Pages/Remix app running in dev but when I try to access environment variables in a loader, I get this error:

[ERROR] ReferenceError: context is not defined

The route with the loader looks like this:

import { useLoaderData } from "@remix-run/react";

export const loader = async () => {
  console.log("In the contact route loader...");
  return { mailgunApiKey: context.env.MAILGUN_API_KEY };
};

export default function Contact() {
  const { mailgunApiKey } = useLoaderData<typeof loader>();
  console.log(`Mailgun API key: ${ mailgunApiKey }`);

  return (
    <div>
      <p>PENDING: A contact form</p>
    </div>
  );
}

I tried deploying to see if it would work in Cloudflare but it fails there, too, albeit less informatively because I don’t have access to the server logs. The variable “MAILGUN_API_KEY” has been created for my Pages app and it is also set in the local file .dev.vars
Can anybody advise me on how I should access the environment variable, hopefully both in production and in development? Is there maybe some part of my setup that is misconfigured and that causes context to be undefined?

Thanks for any and all advice,
Doug.

Okay, it was a mixture of dumb mistakes on my part and some undocumented (that I could find) misdirection in the context object.
This fixed it, for me:

import { useLoaderData } from "@remix-run/react";

export const loader = async ({context}) => {
  return { mailgunApiKey: context.cloudflare.env.MAILGUN_API_KEY };
};

export default function Contact() {
  const { mailgunApiKey } = useLoaderData<typeof loader>();
  console.log(`Mailgun API key in component: ${ mailgunApiKey }`);

  return (
    <div>
      <p>PENDING: A contact form</p>
    </div>
  );
}

I hope this helps someone else! :slight_smile:

3 Likes