Environment Variables
Environment Variables are values that live on the server that your application can use. You may be familiar with the ubiquitous . Your deployment server probably automatically sets that to “production”.
Here are some example environment variables you might find in the wild:
DATABASE_URL
: The URL for a Postgres DatabaseSTRIPE_PRIVATE_KEY
: The key a checkout workflow will use on the serverSTRIPE_PUBLIC_KEY
: The key a checkout workflow will use on the browser
If you’re experience with web development is primarily with the JS frameworks in the last few years, you might think of these as something for your build to use. While they can be useful for bundling code, traditionally those are “build arguments” not environment variables. Environment variables are most useful at runtime on the server. For example, you can change an environment variable to change the behavior of your app without rebuilding or even redeploying.
Environment variables on your server will be handled by your host, for example:
If you’re using the Remix App Server, you can do this very quickly:
Edit your .env
file.
SOME_SECRET=super-secret
Then updated your package.json dev script to this:
Now you can access those values in your loaders/actions:
export function loader() {
console.log(process.env.SOME_SECRET);
}
Do not commit your .env
file to git, the point is that it contains secrets!
Browser Environment Variables
Some folks ask if Remix can let them put environment variables into browser bundles. It’s a common strategy in build-heavy frameworks. However, this approach is a problem for a few reasons:
- It’s not really an environment variable. You have to know which server you’re deploying to at build time.
- You can’t change the values without a rebuild and redeploy.
Instead we recommend keeping all of your environment variables on the server (all the server secrets as well as the stuff your JavaScript in the browser needs) and exposing them to your browser code through window.ENV
. Since you always have a server, you don’t need this information in your bundle, your server can provide the clientside environment variables in the loaders.
Return
ENV
for the client from the root loader - Inside your loader you can access your server’s environment variables. Loaders only run on the server and are never bundled into your client-side JavaScript.-
return {
ENV: {
STRIPE_PUBLIC_KEY: process.env.STRIPE_PUBLIC_KEY
}
};
}
export function Root() {
const data = useLoaderData();
return (
<html lang="en">
<head>
</head>
<body>
<Outlet />
<script
dangerouslySetInnerHTML={{
__html: `window.ENV = ${JSON.stringify(
data.ENV
)}`
}}
/>
<Scripts />
</body>
</html>
Access the values