Skip to content

Commit

Permalink
Merge pull request #175 from MiyashitaLab/feat/google_analytics
Browse files Browse the repository at this point in the history
Google Analytics導入
  • Loading branch information
elecdeer authored Sep 1, 2023
2 parents 4379b10 + 7884f54 commit 008e9ef
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 0 deletions.
37 changes: 37 additions & 0 deletions src/components/feature/analytics/Analytics.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import Script from "next/script";
import { FC } from "react";

import { GOOGLE_ANALYTICS_ID } from "@/lib/environments";

/**
* Analytics関連のスクリプトを読み込む
*/
export const Analytics: FC = () => {
//本番環境以外では読み込まない
if (process.env.NODE_ENV !== "production") {
return <></>;
}

if (!GOOGLE_ANALYTICS_ID) {
console.warn("NEXT_PUBLIC_GOOGLE_ANALYTICS_ID is not defined.");
return <></>;
}

return (
<>
{/* Google Analytics */}
<Script
src={`https://www.googletagmanager.com/gtag/js?id=${GOOGLE_ANALYTICS_ID}`}
/>
<Script id="google-analytics">
{`
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'GA_MEASUREMENT_ID');
`}
</Script>
</>
);
};
1 change: 1 addition & 0 deletions src/components/feature/analytics/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { Analytics } from "./Analytics";
3 changes: 3 additions & 0 deletions src/lib/environments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,6 @@ export const CONTENTFUL_ENVIRONMENT =
export const ON_DEMAND_SECRET = validateEnvSet("ON_DEMAND_SECRET");

export const SLACK_WEBHOOK_URL = process.env["SLACK_WEBHOOK_URL"];

export const GOOGLE_ANALYTICS_ID =
process.env["NEXT_PUBLIC_GOOGLE_ANALYTICS_ID"];
3 changes: 3 additions & 0 deletions src/pages/_document.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { Html, Head, Main, NextScript } from "next/document";

import { Analytics } from "@/components/feature/analytics";

//ここに書いたものはstorybookでは読み込まれないので注意

export default function Document() {
Expand All @@ -9,6 +11,7 @@ export default function Document() {
<body>
<Main />
<NextScript />
<Analytics />
</body>
</Html>
);
Expand Down

0 comments on commit 008e9ef

Please sign in to comment.