'Remix.run environment variables in Catch/Error Boundary
In my remix.run Web-App there are different .env files, for each client there is one .env file. In these files I set the name of the client to show in my layout and as title in meta tag.
How can I access these env variables in CatchBoundary and ErrorBounday in root.tsx?
Since the website is rendered on the server there must be possibility to access environment variables in these Boundary functions I think.
What I don't want is to use nested boundaries by exporting these functions in every route redundantly.
Solution 1:[1]
You can send the environment variables from the loader function.
Uncomment one of the options below:
export async function loader() {
// Option 1: triggers CatchBoundary
// throw new Response(
// JSON.stringify({
// message: "Not Found",
// ENV: {
// PRIMARY_COLOR: process.env.PRIMARY_COLOR,
// },
// }),
// {
// status: 404,
// }
// );
// Option 2: triggers ErrorBoundary
throw new Error(
JSON.stringify({
message: "I am a failure!",
ENV: {
PRIMARY_COLOR: process.env.PRIMARY_COLOR,
},
})
);
}
For the CatchBoundary:
export function CatchBoundary() {
const caught = useCatch();
const data = JSON.parse(caught.data);
const PRIMARY_COLOR = data.ENV.PRIMARY_COLOR;
return (
<div>
<h1>Caught</h1>
<p>Status: {caught.status}</p>
<pre style={{ color: PRIMARY_COLOR }}>
<code>{JSON.stringify(data.message, null, 2)}</code>
</pre>
</div>
);
}
For the ErrorBoundary:
export function ErrorBoundary({ error }: { error: Error }) {
const data = JSON.parse(error.message);
const PRIMARY_COLOR = data.ENV.PRIMARY_COLOR;
return (
<div>
<h1>Error</h1>
<p style={{ color: PRIMARY_COLOR }}>{data.message}</p>
<p>The stack trace is:</p>
<pre>{error.stack}</pre>
</div>
);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | amimaro |
