<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Punam Pudasaini</title>
    <description>The latest articles on DEV Community by Punam Pudasaini (@punam_pudasaini_786bd95eb).</description>
    <link>https://dev.to/punam_pudasaini_786bd95eb</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F2501117%2Fee2dc597-eeb5-4c79-9f5a-52ef8643260a.jpg</url>
      <title>DEV Community: Punam Pudasaini</title>
      <link>https://dev.to/punam_pudasaini_786bd95eb</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/punam_pudasaini_786bd95eb"/>
    <language>en</language>
    <item>
      <title>How to Integrate Google Analytics in Your Next.js Application</title>
      <dc:creator>Punam Pudasaini</dc:creator>
      <pubDate>Tue, 10 Dec 2024 08:24:18 +0000</pubDate>
      <link>https://dev.to/punam_pudasaini_786bd95eb/how-to-integrate-google-analytics-in-your-nextjs-application-484i</link>
      <guid>https://dev.to/punam_pudasaini_786bd95eb/how-to-integrate-google-analytics-in-your-nextjs-application-484i</guid>
      <description>&lt;p&gt;Google Analytics is one of the most powerful tools to track and analyze website traffic. As a Next.js developer, integrating Google Analytics allows you to monitor user behavior, track pageviews, and gather valuable insights about your web application. In this blog post, we will explore how to seamlessly integrate Google Analytics into your Next.js application.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why Use Google Analytics in Next.js?
&lt;/h2&gt;

&lt;p&gt;Google Analytics helps you:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Track user interactions with your website or application.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Monitor page views and user navigation through your site.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Gain insights into how users are interacting with your application, including which pages are popular, the average time spent on each page, and where users are dropping off.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Optimize user experience by understanding their needs and behavior.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Prerequisites
&lt;/h2&gt;

&lt;p&gt;Before we dive into the code, make sure you have:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;A Google Analytics account: You can sign up at &lt;a href="https://developers.google.com/analytics" rel="noopener noreferrer"&gt;&lt;/a&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;A Google Analytics Tracking ID (also known as the Measurement ID). You can find this in the Google Analytics dashboard under Admin &amp;gt; Property Settings &amp;gt; Tracking Info.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Step 1: Install the Required Package
&lt;/h2&gt;

&lt;p&gt;While it is possible to integrate Google Analytics manually, there are some convenient packages available for Next.js that simplify this process, such as nextjs-google-analytics.&lt;/p&gt;

&lt;p&gt;To install the package, run the following command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install nextjs-google-analytics
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This package will automatically track pageviews and send the data to Google Analytics.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 2: Setup Google Analytics in Your Next.js Application
&lt;/h2&gt;

&lt;p&gt;To add Google Analytics to your Next.js project, we’ll integrate it into the _app.js or _app.tsx file, depending on whether you're using JavaScript or TypeScript. Here's how to do it:&lt;/p&gt;

&lt;p&gt;create separate component for GoogleAnalytics:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"use client";
import { GoogleAnalytics } from "nextjs-google-analytics";

export const GoogleAnalytic = () =&amp;gt; {
  return (
    &amp;lt;&amp;gt;
      &amp;lt;GoogleAnalytics
        trackPageViews
        gaMeasurementId="YOUR_GA_MEASUREMENT_ID" // Optional, can be set in .env
        debugMode={false} // Enable for debugging
      /&amp;gt;
    &amp;lt;/&amp;gt;
  );
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;app.tsx&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export default function RootLayout({
  children,
}: Readonly&amp;lt;{
  children: React.ReactNode;
}&amp;gt;) {
  return (
    &amp;lt;&amp;gt;
      &amp;lt;GoogleAnalytic /&amp;gt;
      {children}

    &amp;lt;/&amp;gt;
  );
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this setup:&lt;br&gt;
&lt;strong&gt;"use client"&lt;/strong&gt;: This directive ensures that the component is treated as a client-side component, which is necessary for useEffect and other client-side operations.&lt;br&gt;
&lt;strong&gt;GoogleAnalytics&lt;/strong&gt;: This component automatically tracks page views based on client-side navigation.&lt;/p&gt;
&lt;h2&gt;
  
  
  Step 3: Configure Google Analytics Scripts (Optional)
&lt;/h2&gt;

&lt;p&gt;If you prefer a manual setup or want to add additional customization, you can use the built-in Script component from Next.js to insert the Google Analytics tracking script into your application.&lt;/p&gt;

&lt;p&gt;Here’s how you can manually integrate the Google Analytics script in your app.tsx:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import Script from "next/script";
import { GoogleAnalytic } from "@/components/Analytics";

export default function RootLayout({
  children,
}: Readonly&amp;lt;{
  children: React.ReactNode;
}&amp;gt;) {
  return (
    &amp;lt;html lang="en"&amp;gt;
      &amp;lt;head&amp;gt;
        {/* Google Analytics */}
        &amp;lt;Script
          async
           src={`https://www.googletagmanager.com/gtag/js?id=YOUR_GA_MEASUREMENT_ID`}
        /&amp;gt;
        &amp;lt;Script id="google-analytics"&amp;gt;
          {`
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', 'YOUR_GA_MEASUREMENT_ID');
          `}
        &amp;lt;/Script&amp;gt;
      &amp;lt;/head&amp;gt;
      &amp;lt;body
        className={`your-className`}
      &amp;gt;
        {children}
      &amp;lt;/body&amp;gt;
    &amp;lt;/html&amp;gt;
  );
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Explanation:&lt;br&gt;
&lt;code&gt;**&amp;lt;script async&amp;gt;**&lt;/code&gt;: This ensures the Google Analytics script is loaded asynchronously, which helps prevent blocking the rendering of your page.&lt;/p&gt;
&lt;h2&gt;
  
  
  Step 4: Track Page Views with Google Analytics
&lt;/h2&gt;

&lt;p&gt;Once the Google Analytics script is in place, it will automatically start tracking pageviews on page load. However, Next.js is a Single Page Application (SPA), meaning that subsequent page navigations don't cause full page reloads, and we need to manually track those using the Router events.&lt;/p&gt;

&lt;p&gt;You can achieve this by listening for route changes and sending a pageview event to Google Analytics using the gtag function.&lt;br&gt;
Here’s how you can do this in your googleAnalytic.tsx:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"use client";
import { usePathname } from "next/navigation";
import { GoogleAnalytics } from "nextjs-google-analytics";
import { useEffect } from "react";

export const GoogleAnalytic = () =&amp;gt; {
  const pathname = usePathname(); // This gives the current path

  useEffect(() =&amp;gt; {
    if (!pathname) return;
    // Google Analytics configuration on route change
    window.gtag("config", "YOUR_GA_MEASUREMENT_ID", {
      page_path: pathname,
    });
  }, [pathname]); // Trigger effect whenever the pathname changes

  return (
    &amp;lt;&amp;gt;
      &amp;lt;GoogleAnalytics
        trackPageViews
        gaMeasurementId="YOUR_GA_MEASUREMENT_ID" // Optional, can be set in .env
        debugMode={false} // Enable for debugging
      /&amp;gt;
    &amp;lt;/&amp;gt;
  );
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;useEffect&lt;/strong&gt;: This listens to changes in the route using Next.js’s and sends a pageview to Google Analytics.&lt;br&gt;
window.gtag("config", ...): This sends the pageview event with the new URL path.&lt;/p&gt;
&lt;h2&gt;
  
  
  Step 5: Track Custom Events
&lt;/h2&gt;

&lt;p&gt;In addition to tracking page views, Google Analytics allows you to track custom events such as clicks, form submissions, or other user interactions. This is where the logEvent function comes in handy.&lt;/p&gt;

&lt;p&gt;The logEvent function sends event data to Google Analytics, allowing you to track specific interactions like button clicks.&lt;br&gt;
&lt;strong&gt;Add the logEvent Function&lt;/strong&gt;&lt;br&gt;
You can define the logEvent function inside a utility file or directly within your component. Here's the function you can use:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;type AnalyticsEvent = {
  action: string;
  category?: string;
  label?: string;
  value?: number;
};

export const logEvent = ({
  action,
  category,
  label,
  value,
}: AnalyticsEvent): void =&amp;gt; {
  if (typeof window.gtag === "function") {
    window.gtag("event", action, {
      event_category: category,
      event_label: label,
      value: value,
    });
  }
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Call logEvent on User Interactions&lt;/strong&gt;&lt;br&gt;
For example, let's say you want to track when a user clicks the "Login" button. You would add the logEvent function inside the onClick event handler.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export default function Login() {
  const handleLogin = () =&amp;gt; {
    // Log the download button click
    logEvent({
      action: "click",
      category: "Button",
      label: "Login",
      value: 1,
    });
  };

  return (
    &amp;lt;&amp;gt;
      {/* Example Button */}
      &amp;lt;button onClick={handleLogin}&amp;gt;Login&amp;lt;/button&amp;gt;
    &amp;lt;/&amp;gt;
  );
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Explanation:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;logEvent&lt;/strong&gt;: This function is called whenever a user clicks the "Login" button. The parameters action, category, label, and value allow you to customize the data sent to Google Analytics.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;action&lt;/strong&gt;: The type of event (e.g., "click").&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;category&lt;/strong&gt;: The category of the event (e.g., "Button").&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;label&lt;/strong&gt;: An optional label that helps identify the event (e.g., "Login").&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;value&lt;/strong&gt;: An optional numeric value (e.g., 1 to represent one click).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;onClick&lt;/strong&gt;: The handleLogin function is triggered by clicking the button, and it logs the custom event to Google Analytics.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Step 6: Verify Your Google Analytics Setup
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Open your site and navigate through some pages or click on login button.&lt;/li&gt;
&lt;li&gt;Go to your Google Analytics dashboard and navigate to the Events section.&lt;/li&gt;
&lt;li&gt;Navigate to the Realtime tab to see if the pageviews are being tracked correctly.&lt;/li&gt;
&lt;li&gt;After trigger custom trigger button, You should start seeing the custom event data appear under the Events reports in Google Analytics.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffjddpwyg700y014pydsq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffjddpwyg700y014pydsq.png" alt="Next Js + Google Tag Manager + Google Analytics" width="800" height="351"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Integrating Google Analytics in a Next.js application is essential for tracking user behavior, page views, and custom events. By combining Google Analytics' automatic page tracking with custom event tracking using the logEvent function, you can gain a deeper understanding of user interactions.&lt;/p&gt;

&lt;p&gt;Tracking custom events like button clicks, form submissions, or specific actions helps you optimize the user experience and make data-driven decisions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Additional Resources&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://developers.google.com/analytics" rel="noopener noreferrer"&gt;Google Analytics&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://nextjs.org/docs" rel="noopener noreferrer"&gt;Next.js Documentation&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Happy coding! &lt;/p&gt;

</description>
    </item>
    <item>
      <title>Setting Up a Node.js Development Environment with MySQL, Sequelize, and TypeScript</title>
      <dc:creator>Punam Pudasaini</dc:creator>
      <pubDate>Fri, 29 Nov 2024 16:24:40 +0000</pubDate>
      <link>https://dev.to/punam_pudasaini_786bd95eb/setting-up-a-nodejs-development-environment-with-mysql-sequelize-and-typescript-21n</link>
      <guid>https://dev.to/punam_pudasaini_786bd95eb/setting-up-a-nodejs-development-environment-with-mysql-sequelize-and-typescript-21n</guid>
      <description>&lt;h2&gt;
  
  
  &lt;strong&gt;Why Node.js with MySQL and Sequelize?&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Node.js is a powerful backend technology, and MySQL remains a popular relational database for many applications. Pairing it with Sequelize ORM simplifies database interactions, and TypeScript ensures type safety, improving developer productivity and reducing bugs.&lt;/p&gt;

&lt;p&gt;Now, let's get hands-on.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Getting Started&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Step 1: Setting Up the Project&lt;/strong&gt;
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir node-mysql-sequelize-ts
cd node-mysql-sequelize-ts
npm init -y

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;Step 2: Install Dependencies&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Install the required packages:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install express sequelize mysql2
npm install --save-dev typescript @types/node @types/express ts-node nodemon

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;Step 3: Configure TypeScript&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Generate a tsconfig.json:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;tsc --init
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Update the configuration:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "compilerOptions": {
    "target": "ES6",
    "module": "CommonJS",
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;Step 4: Setting Up Sequelize&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Create a src/config/database.ts file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Sequelize } from "sequelize";

const sequelize = new Sequelize("database_name", "username", "password", {
  host: "localhost",
  dialect: "mysql",
});

export default sequelize;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;Step 5: Model Definition&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Create src/models/User.ts:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { DataTypes, Model } from "sequelize";
import sequelize from "../config/database";

class User extends Model {}

User.init(
  {
    id: {
      type: DataTypes.INTEGER,
      autoIncrement: true,
      primaryKey: true,
    },
    name: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    email: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true,
    },
  },
  {
    sequelize,
    tableName: "users",
  }
);

export default User;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;Step 6: Connecting Sequelize with the App&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Database Sync&lt;br&gt;
In src/index.ts, synchronize Sequelize models:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import sequelize from "./config/database";
import User from "./models/User";

const start = async () =&amp;gt; {
  try {
    await sequelize.sync({ force: true }); // Creates tables
    console.log("Database synchronized!");
  } catch (error) {
    console.error("Error syncing database:", error);
  }
};

start();

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  *&lt;em&gt;Step 6: Testing the Setup *&lt;/em&gt;
&lt;/h2&gt;

&lt;p&gt;Add a Basic Route&lt;br&gt;
Update src/index.ts to include a test route:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import express, { Request, Response } from "express";
import sequelize from "./config/database";
import User from "./models/User";

const app = express();
const port = 3000;

app.get("/", async (req: Request, res: Response) =&amp;gt; {
  try {
    const users = await User.findAll();
    res.json(users);
  } catch (error) {
    res.status(500).send("Database error");
  }
});

app.listen(port, async () =&amp;gt; {
  console.log(`Server running on http://localhost:${port}`);
  await sequelize.authenticate();
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;Start the development server:&lt;/strong&gt;
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm run dev

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
  </channel>
</rss>
