Using environment variables is a little tricky in Remix, especially when you are using Cloudflare pages to deploy your Remix application. You can not access variables as you might be used to. You cannot use process.env
to access the environment variables.
While using @remix-run/cloudflare-pages
adapter, we do not declare our env variables in .env
files. Since Cloudflare Pages are powered by Functions, we need to define our local environment variables in .dev.vars
files. It has the same syntax as .env files.
ASSETS_DOMAIN=https://image-assets.hashnode.dev
API_URL=https://hashnode.dev
These variables are only accessible server side in action/loader functions. They will be available via context
.
import { LoaderFunctionArgs } from '@remix-run/cloudflare';
export async function loader({ request, context }: LoaderFunctionArgs) {
const ENV = context.cloudflare.env;
// now you can access all the variables inside
// .dev.vars file
const baseURL = ENV.API_URL;
}
If you want to use these variables in client-side, you can simply use useLoaderData()
or useRouteLoaderData()
hooks provided by the Remix.
Note: In production, you can simply navigate to Settings > Environment variables and add the required variables. For more information, please visit this page.
Conclusion
Thus, using env variables might be a little tricky, and you might think that this seems like a workaround as you have to pass these variables through loader/action functions every time you want to use them. One easy way might be you get env variables in the root loader and then use useRouteLoaderData()
every time you want it client side.