Skip to content

Commit

Permalink
refactor(google-analytics): Switch to V2 + Vite (remix-run#502)
Browse files Browse the repository at this point in the history
  • Loading branch information
machour authored May 31, 2024
1 parent fd37027 commit e973dc2
Show file tree
Hide file tree
Showing 14 changed files with 328 additions and 60 deletions.
84 changes: 84 additions & 0 deletions google-analytics/.eslintrc.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/**
* This is intended to be a basic starting point for linting in your app.
* It relies on recommended configs out of the box for simplicity, but you can
* and should modify this configuration to best suit your team's needs.
*/

/** @type {import('eslint').Linter.Config} */
module.exports = {
root: true,
parserOptions: {
ecmaVersion: "latest",
sourceType: "module",
ecmaFeatures: {
jsx: true,
},
},
env: {
browser: true,
commonjs: true,
es6: true,
},
ignorePatterns: ["!**/.server", "!**/.client"],

// Base config
extends: ["eslint:recommended"],

overrides: [
// React
{
files: ["**/*.{js,jsx,ts,tsx}"],
plugins: ["react", "jsx-a11y"],
extends: [
"plugin:react/recommended",
"plugin:react/jsx-runtime",
"plugin:react-hooks/recommended",
"plugin:jsx-a11y/recommended",
],
settings: {
react: {
version: "detect",
},
formComponents: ["Form"],
linkComponents: [
{ name: "Link", linkAttribute: "to" },
{ name: "NavLink", linkAttribute: "to" },
],
"import/resolver": {
typescript: {},
},
},
},

// Typescript
{
files: ["**/*.{ts,tsx}"],
plugins: ["@typescript-eslint", "import"],
parser: "@typescript-eslint/parser",
settings: {
"import/internal-regex": "^~/",
"import/resolver": {
node: {
extensions: [".ts", ".tsx"],
},
typescript: {
alwaysTryTypes: true,
},
},
},
extends: [
"plugin:@typescript-eslint/recommended",
"plugin:import/recommended",
"plugin:import/typescript",
],
},

// Node
{
files: [".eslintrc.cjs"],
env: {
node: true,
},
},
],
};
4 changes: 0 additions & 4 deletions google-analytics/.eslintrc.js

This file was deleted.

1 change: 0 additions & 1 deletion google-analytics/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,4 @@ node_modules

/.cache
/build
/public/build
.env
6 changes: 5 additions & 1 deletion google-analytics/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,14 @@ Open this example on [CodeSandbox](https://codesandbox.com):

This example shows how to use Google analytics with Remix.

First you have to get the Google analytics ID and add that key in the [.env.example](./.env.example) file.
- Copy `.env.example` to `.env`
- Configure your Google Analytics ID in the `.env` file (read from the `entry.server.tsx` file)
- Run the project

Check [app/root.tsx](./app/root.tsx) where page tracking code is added. For tracking events check [app/routes/contact.tsx](./app/routes/contact.tsx) file.

The Google Analytics tag is disabled in "development", you can enable it during your test, but make sure to only enable tracking in production.

## Related Links

[Google Analytics](https://analytics.google.com/analytics/web/)
159 changes: 159 additions & 0 deletions google-analytics/app/entry.server.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
import { PassThrough } from "node:stream";

import type { AppLoadContext, EntryContext } from "@remix-run/node";
import { createReadableStreamFromReadable } from "@remix-run/node";
import { RemixServer } from "@remix-run/react";
import { config } from "dotenv";
import * as isbotModule from "isbot";
import { renderToPipeableStream } from "react-dom/server";

// Load .env variables
config();

const ABORT_DELAY = 5_000;

export default function handleRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
remixContext: EntryContext,
loadContext: AppLoadContext,
) {
const prohibitOutOfOrderStreaming =
isBotRequest(request.headers.get("user-agent")) || remixContext.isSpaMode;

return prohibitOutOfOrderStreaming
? handleBotRequest(
request,
responseStatusCode,
responseHeaders,
remixContext,
)
: handleBrowserRequest(
request,
responseStatusCode,
responseHeaders,
remixContext,
);
}

// We have some Remix apps in the wild already running with isbot@3 so we need
// to maintain backwards compatibility even though we want new apps to use
// isbot@4. That way, we can ship this as a minor Semver update to @remix-run/dev.
function isBotRequest(userAgent: string | null) {
if (!userAgent) {
return false;
}

// isbot >= 3.8.0, >4
if ("isbot" in isbotModule && typeof isbotModule.isbot === "function") {
return isbotModule.isbot(userAgent);
}

// isbot < 3.8.0
if ("default" in isbotModule && typeof isbotModule.default === "function") {
return isbotModule.default(userAgent);
}

return false;
}

function handleBotRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
remixContext: EntryContext,
) {
return new Promise((resolve, reject) => {
let shellRendered = false;
const { pipe, abort } = renderToPipeableStream(
<RemixServer
context={remixContext}
url={request.url}
abortDelay={ABORT_DELAY}
/>,
{
onAllReady() {
shellRendered = true;
const body = new PassThrough();
const stream = createReadableStreamFromReadable(body);

responseHeaders.set("Content-Type", "text/html");

resolve(
new Response(stream, {
headers: responseHeaders,
status: responseStatusCode,
}),
);

pipe(body);
},
onShellError(error: unknown) {
reject(error);
},
onError(error: unknown) {
responseStatusCode = 500;
// Log streaming rendering errors from inside the shell. Don't log
// errors encountered during initial shell rendering since they'll
// reject and get logged in handleDocumentRequest.
if (shellRendered) {
console.error(error);
}
},
},
);

setTimeout(abort, ABORT_DELAY);
});
}

function handleBrowserRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
remixContext: EntryContext,
) {
return new Promise((resolve, reject) => {
let shellRendered = false;
const { pipe, abort } = renderToPipeableStream(
<RemixServer
context={remixContext}
url={request.url}
abortDelay={ABORT_DELAY}
/>,
{
onShellReady() {
shellRendered = true;
const body = new PassThrough();
const stream = createReadableStreamFromReadable(body);

responseHeaders.set("Content-Type", "text/html");

resolve(
new Response(stream, {
headers: responseHeaders,
status: responseStatusCode,
}),
);

pipe(body);
},
onShellError(error: unknown) {
reject(error);
},
onError(error: unknown) {
responseStatusCode = 500;
// Log streaming rendering errors from inside the shell. Don't log
// errors encountered during initial shell rendering since they'll
// reject and get logged in handleDocumentRequest.
if (shellRendered) {
console.error(error);
}
},
},
);

setTimeout(abort, ABORT_DELAY);
});
}
21 changes: 8 additions & 13 deletions google-analytics/app/root.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
import type { MetaFunction } from "@remix-run/node";
import { json } from "@remix-run/node";
// import { json } from "@remix-run/node";
import {
Link,
Links,
LiveReload,
Meta,
Outlet,
Scripts,
Expand Down Expand Up @@ -35,13 +32,7 @@ export const loader = async () => {
return json({ gaTrackingId: process.env.GA_TRACKING_ID });
};

export const meta: MetaFunction = () => ({
charset: "utf-8",
title: "New Remix App",
viewport: "width=device-width,initial-scale=1",
});

export default function App() {
export function Layout({ children }: { children: React.ReactNode }) {
const location = useLocation();
const { gaTrackingId } = useLoaderData<typeof loader>();

Expand All @@ -54,6 +45,8 @@ export default function App() {
return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<Meta />
<Links />
</head>
Expand Down Expand Up @@ -81,7 +74,6 @@ export default function App() {
/>
</>
)}

<header>
<nav>
<ul>
Expand All @@ -100,11 +92,14 @@ export default function App() {
</ul>
</nav>
</header>
<Outlet />
{children}
<ScrollRestoration />
<Scripts />
<LiveReload />
</body>
</html>
);
}

export default function App() {
return <Outlet />;
}
8 changes: 5 additions & 3 deletions google-analytics/app/routes/_index.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import type { MetaFunction } from "@remix-run/node";

export const meta: MetaFunction = () => ({
title: "Home",
});
export const meta: MetaFunction = () => [
{
title: "Home",
},
];

export default function Index() {
return (
Expand Down
8 changes: 5 additions & 3 deletions google-analytics/app/routes/dashboard.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import type { MetaFunction } from "@remix-run/node";

export const meta: MetaFunction = () => ({
title: "Dashboard",
});
export const meta: MetaFunction = () => [
{
title: "Dashboard",
},
];

export default function Dashboard() {
return (
Expand Down
8 changes: 5 additions & 3 deletions google-analytics/app/routes/profile.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import type { MetaFunction } from "@remix-run/node";

export const meta: MetaFunction = () => ({
title: "Profile",
});
export const meta: MetaFunction = () => [
{
title: "Profile",
},
];

export default function Profile() {
return (
Expand Down
Loading

0 comments on commit e973dc2

Please sign in to comment.