Skip to content

Commit

Permalink
Unify the analytics setup
Browse files Browse the repository at this point in the history
  • Loading branch information
paul-phan committed Apr 18, 2024
1 parent f61c8bd commit 0c05af1
Show file tree
Hide file tree
Showing 18 changed files with 105 additions and 75 deletions.
9 changes: 7 additions & 2 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
# Replace the values with your own
SESSION_SECRET="foobar"
PUBLIC_STOREFRONT_API_TOKEN=33ad0f277e864013b8e3c21d19432501
PUBLIC_STORE_DOMAIN=hydrogen-preview.myshopify.com
PUBLIC_CUSTOMER_ACCOUNT_API_CLIENT_ID=shp_3cecd990-4824-4e27-beb2-46c8e822ec14
PUBLIC_CUSTOMER_ACCOUNT_API_URL=https://shopify.com/55145660472
PUBLIC_CHECKOUT_DOMAIN=checkout.hydrogen.shop

## optional
#PRIVATE_STOREFRONT_API_TOKEN="your-private-storefront-api-token"

#WEAVERSE_PROJECT_ID="your-project-id"
# Weaverse setup
WEAVERSE_PROJECT_ID="your-project-id"
#WEAVERSE_API_KEY="your-weaverse-api-key"
#WEAVERSE_HOST="https://studio.weaverse.io"

# Additional services
#PUBLIC_GOOGLE_GTM_ID=G-R1KFYYKE48
#JUDGEME_PUBLIC_TOKEN="your-judgeme-public-token"

41 changes: 38 additions & 3 deletions app/components/CustomAnalytics.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
import {unstable_useAnalytics as useAnalytics} from '@shopify/hydrogen';
import {Script, unstable_useAnalytics as useAnalytics} from '@shopify/hydrogen';
import {useEffect} from 'react';
import {useLoaderData} from '@remix-run/react';
import {loader} from '~/root';

export function CustomAnalytics() {
const {subscribe} = useAnalytics();
const {subscribe, canTrack} = useAnalytics();
const data = useLoaderData<typeof loader>();

useEffect(() => {
setTimeout(() => {
let isTrackingAllowed = canTrack();
console.log('CustomAnalytics - isTrackingAllowed', isTrackingAllowed);
}, 1000);
// Standard events
subscribe('page_viewed', (data) => {
console.log('CustomAnalytics - Page viewed:', data);
Expand All @@ -28,5 +35,33 @@ export function CustomAnalytics() {
});
}, []);

return null;
let id = data.googleGtmID;
if (!id) {
return null;
}

return (
<>
{/* Initialize GTM container */}
<Script
suppressHydrationWarning
dangerouslySetInnerHTML={{
__html: `
dataLayer = window.dataLayer || [];
function gtag(){
dataLayer.push(arguments)
};
gtag('js', new Date());
gtag({'gtm.start': new Date().getTime(),event:'gtm.js'})
gtag('config', "${id}");
`,
}}
/>

{/* Load GTM script */}
<Script async src={`https://www.googletagmanager.com/gtm.js?id=${id}`} />
</>
);
}
1 change: 1 addition & 0 deletions app/components/GenericError.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export function GenericError({
overflow: 'auto',
maxWidth: '100%',
}}
suppressHydrationWarning
dangerouslySetInnerHTML={{
__html: addLinksToStackTrace(error.stack),
}}
Expand Down
35 changes: 0 additions & 35 deletions app/components/GoogleTagManager.tsx

This file was deleted.

4 changes: 2 additions & 2 deletions app/entry.server.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ export default async function handleRequest(
const {nonce, header, NonceProvider} = createContentSecurityPolicy({
...getWeaverseCsp(request),
shop: {
checkoutDomain: context.env.PUBLIC_CHECKOUT_DOMAIN,
storeDomain: context.env.PUBLIC_STORE_DOMAIN,
checkoutDomain: context.env?.PUBLIC_CHECKOUT_DOMAIN,
storeDomain: context.env?.PUBLIC_STORE_DOMAIN,
},
});
const body = await renderToReadableStream(
Expand Down
6 changes: 2 additions & 4 deletions app/root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ import {NotFound} from './components/NotFound';
import styles from './styles/app.css?url';
import {DEFAULT_LOCALE, parseMenu} from './lib/utils';
import {GlobalStyle} from './weaverse/style';
import {GoogleGTM} from '~/components/GoogleTagManager';

// This is important to avoid re-fetching root queries on sub-navigations
export const shouldRevalidate: ShouldRevalidateFunction = ({
Expand Down Expand Up @@ -159,7 +158,6 @@ function App() {
</Analytics.Provider>
<ScrollRestoration nonce={nonce} />
<Scripts nonce={nonce} />
<GoogleGTM />
</body>
</html>
);
Expand Down Expand Up @@ -210,8 +208,8 @@ export function ErrorBoundary({error}: {error: Error}) {
<GenericError error={error instanceof Error ? error : undefined} />
)}
</Layout>
<ScrollRestoration nonce={nonce} />
<Scripts nonce={nonce} />
{/*<ScrollRestoration nonce={nonce} />*/}
{/*<Scripts nonce={nonce} />*/}
</body>
</html>
);
Expand Down
1 change: 1 addition & 0 deletions app/routes/($locale).policies.$policyHandle.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ export default function Policies() {
</PageHeader>
<div className="flex-grow w-full md:w-7/12">
<div
suppressHydrationWarning
dangerouslySetInnerHTML={{__html: policy.body}}
className="prose dark:prose-invert"
/>
Expand Down
32 changes: 17 additions & 15 deletions app/routes/($locale).products.$productHandle.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -148,21 +148,23 @@ export default function Product() {
return (
<>
<WeaverseContent />
<Analytics.ProductView
data={{
products: [
{
id: product.id,
title: product.title,
price: product.selectedVariant?.price.amount || '0',
vendor: product.vendor,
variantId: product.selectedVariant?.id || '',
variantTitle: product.selectedVariant?.title || '',
quantity: 1,
},
],
}}
/>
{product.selectedVariant && (
<Analytics.ProductView
data={{
products: [
{
id: product.id,
title: product.title,
price: product.selectedVariant?.price.amount || '0',
vendor: product.vendor,
variantId: product.selectedVariant?.id || '',
variantTitle: product.selectedVariant?.title || '',
quantity: 1,
},
],
}}
/>
)}
</>
);
}
Expand Down
5 changes: 4 additions & 1 deletion app/sections/blog-post.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,10 @@ let BlogPost = forwardRef<HTMLElement, BlogPostProps>((props, ref) => {
</div>
<Section as="article" padding="all" className="prose mx-auto">
<div className="lg:max-w-screen-lg md:max-w-screen-md max-w-screen-sm px-4 mx-auto space-y-8 md:space-y-16">
<div dangerouslySetInnerHTML={{__html: contentHtml}} />
<div
suppressHydrationWarning
dangerouslySetInnerHTML={{__html: contentHtml}}
/>
<div className="md:flex justify-between gap-2 space-y-2">
<div>
<strong>Tags:</strong>
Expand Down
1 change: 1 addition & 0 deletions app/sections/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ let Page = forwardRef<HTMLElement, PageProps>((props, ref) => {
>
<PageHeader heading={page.title}>
<div
suppressHydrationWarning
dangerouslySetInnerHTML={{__html: page.body}}
className="prose dark:prose-invert"
/>
Expand Down
5 changes: 3 additions & 2 deletions app/sections/product-information/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,8 @@ let ProductInformation = forwardRef<HTMLDivElement, ProductInformationProps>(
let atcText = selectedVariant?.availableForSale
? addToCartText
: selectedVariant?.quantityAvailable === -1
? unavailableText
: soldOutText;
? unavailableText
: soldOutText;
useEffect(() => {
if (!selectedVariant) {
setSelectedVariant(variants?.nodes?.[0]);
Expand Down Expand Up @@ -134,6 +134,7 @@ let ProductInformation = forwardRef<HTMLDivElement, ProductInformationProps>(
</p>
{children}
<p
suppressHydrationWarning
className="max-w-[600px] leading-relaxed"
dangerouslySetInnerHTML={{
__html: descriptionHtml,
Expand Down
1 change: 1 addition & 0 deletions app/sections/product-information/product-detail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export function ProductDetail({

<Disclosure.Panel className={'pb-4 pt-2 grid gap-2'}>
<div
suppressHydrationWarning
className="prose dark:prose-invert"
dangerouslySetInnerHTML={{__html: content}}
/>
Expand Down
1 change: 1 addition & 0 deletions app/sections/shared/Description.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ let Description = forwardRef<
alignmentClasses[alignment!],
className,
)}
suppressHydrationWarning
dangerouslySetInnerHTML={{__html: content}}
></Tag>
);
Expand Down
5 changes: 3 additions & 2 deletions app/sections/single-product/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,8 @@ let SingleProduct = forwardRef<HTMLElement, SingleProductProps>(
let atcText = selectedVariant?.availableForSale
? 'Add to Cart'
: selectedVariant?.quantityAvailable === -1
? 'Unavailable'
: 'Sold Out';
? 'Unavailable'
: 'Sold Out';
return (
<section ref={ref} {...rest} className="w-full py-12 md:py-24 lg:py-32">
<div className="container px-4 md:px-6 mx-auto">
Expand Down Expand Up @@ -94,6 +94,7 @@ let SingleProduct = forwardRef<HTMLElement, SingleProductProps>(
{children}
<p
className="max-w-[600px] leading-relaxed"
suppressHydrationWarning
dangerouslySetInnerHTML={{
__html: product?.descriptionHtml,
}}
Expand Down
6 changes: 5 additions & 1 deletion app/sections/testimonials/item.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,11 @@ let TestimonialItem = forwardRef<HTMLDivElement, TestimonialItemProps>(
<figure className="p-6 bg-gray-50 rounded">
<blockquote className="text-gray-500">
<h4 className="font-medium text-gray-900">{heading}</h4>
<p className="my-4" dangerouslySetInnerHTML={{__html: content}} />
<p
className="my-4"
suppressHydrationWarning
dangerouslySetInnerHTML={{__html: content}}
/>
</blockquote>
<figcaption className="flex items-center space-x-3">
<Image
Expand Down
1 change: 1 addition & 0 deletions app/weaverse/style.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ export function GlobalStyle() {
<style
id="global-theme-style"
key="global-theme-style"
suppressHydrationWarning
dangerouslySetInnerHTML={{
__html: `
:root {
Expand Down
3 changes: 3 additions & 0 deletions server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ export default {
env: Env,
executionContext: ExecutionContext,
): Promise<Response> {
// https://github.com/Shopify/hydrogen/issues/1998#issuecomment-2062161714
// globalThis.__H2O_LOG_EVENT = undefined;
globalThis.__remix_devServerHooks = undefined;
try {
/**
* Open a cache instance in the worker and a custom session instance.
Expand Down
23 changes: 15 additions & 8 deletions vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,26 @@ export default defineConfig({
plugins: [
hydrogen(),
oxygen(),
remix({
presets: [hydrogen.preset()],
future: {
v3_fetcherPersist: true,
v3_relativeSplatPath: false,
v3_throwAbortReason: true,
},
}),
remix({presets: [hydrogen.preset()]}),
tsconfigPaths(),
],
ssr: {
optimizeDeps: {
include: ['typographic-base/index', 'textr'],
},
},
server: {
warmup: {
clientFiles: [
'./app/entry.client.tsx',
'./app/root.tsx',
'./app/routes/**/*',
],
},
},
build: {
// Allow a strict Content-Security-Policy
// withtout inlining assets as base64:
assetsInlineLimit: 0,
},
});

0 comments on commit 0c05af1

Please sign in to comment.