Skip to content

Instantly share code, notes, and snippets.

@kaznak
Last active June 27, 2024 05:38
Show Gist options
  • Save kaznak/fb30e01ca803a9c2dfecbabb4a41531d to your computer and use it in GitHub Desktop.
Save kaznak/fb30e01ca803a9c2dfecbabb4a41531d to your computer and use it in GitHub Desktop.
Remix で GA4 の Tracking ID をセットする時に使うコンポーネントの案
/**
* Loaders does not work, if some errors occurred.
* Thus the critical values are passed by in script element.
*/
export type Env = Partial<typeof process.env>;
declare global {
interface Window {
env: Env;
}
}
export function getEnv(varNames: string[]) {
let env: Env;
if (typeof process !== "undefined") {
env = process.env;
} else if (typeof window !== "undefined") {
env = window.env;
} else {
throw Error("both process and window are undefined.");
}
return Object.fromEntries(varNames.map((varName) => [varName, env[varName]]));
}
export interface EnvVarsProps {
env: Env;
nonce?: string;
}
export function EnvVars({ env, nonce }: EnvVarsProps) {
const nonceProps = nonce ? { nonce } : {};
return (
<script
dangerouslySetInnerHTML={{
__html: `window.env = ${JSON.stringify(env)}`,
}}
{...nonceProps}
/>
);
}
@kaznak
Copy link
Author

kaznak commented Jun 21, 2024

Remix で GA4 の Tracking ID セットする方法を色々試行錯誤してたんだけど、結局こんな感じで環境変数経由で渡して、 window.env にセットするようにしておいて、値を取り出す時は process.env と window.env の両方見るようにするのが確実なんかなと思ったけどどうなんだろう。
あと、 .server.ts/.client.ts で同名の関数定義して getEnv 内の条件分岐なくせたりしない?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment