<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Atacan Erdoğan on Medium]]></title>
        <description><![CDATA[Stories by Atacan Erdoğan on Medium]]></description>
        <link>https://medium.com/@datacann?source=rss-355ed011d32e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*j6y2cEoFjlikZI4Z078mPA.png</url>
            <title>Stories by Atacan Erdoğan on Medium</title>
            <link>https://medium.com/@datacann?source=rss-355ed011d32e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 08:58:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@datacann/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[SEO & Google Ads Integration in React and Next.js: A Developer’s Guide]]></title>
            <link>https://medium.com/@datacann/seo-google-ads-integration-in-react-and-next-js-a-developers-guide-753fec960341?source=rss-355ed011d32e------2</link>
            <guid isPermaLink="false">https://medium.com/p/753fec960341</guid>
            <category><![CDATA[seo]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Atacan Erdoğan]]></dc:creator>
            <pubDate>Mon, 14 Apr 2025 19:46:24 GMT</pubDate>
            <atom:updated>2025-04-14T19:51:26.674Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*wGJtuNhzftTrDHel1UZfOw.png" /></figure><p>As frontend developers, we often focus on building great UI and clean code — but that’s only half of the story. In many real-world applications, SEO (Search Engine Optimization) and SEA (Search Engine Advertising) play a critical role in product visibility, user acquisition, and even revenue.</p><p>In this article, I’ll walk you through how to apply **SEO best practices** and integrate **Google Ads tracking** in a React or Next.js project. We’ll cover:<br>- How to add essential meta tags<br>- How to configure sitemap and robots.txt<br>- When to use SSR/SSG for better indexing<br>- How to track conversions using Google Ads scripts</p><p>Let’s start by setting up a basic SEO foundation.</p><h3>1. Configuring Sitemap.xml and Robots.txt in Next.js</h3><p>Search engines like Google need guidance to crawl your site effectively. Two essential files help with that:</p><p>- **robots.txt** — tells crawlers which URLs should or shouldn’t be indexed.<br>- **sitemap.xml** — provides a complete list of your public URLs to index.</p><p>In a Next.js project, the easiest way to generate both files is using the [`next-sitemap`](<a href="https://www.npmjs.com/package/next-sitemap">https://www.npmjs.com/package/next-sitemap</a>) package.</p><h4>Step 1 — Install ‘next-stemap’</h4><pre>npm install next-sitemap</pre><h4>Step 2 — Create next-sitemap.config.js at the root of your project</h4><p>This file tells the plugin what your site URL is and how to generate the sitemap and robots.txt.</p><pre>// next-sitemap.config.js<br>module.exports = {<br>  siteUrl: &#39;https://your-domain.com&#39;, <br>  generateRobotsTxt: true, // Also generate robots.txt<br>  changefreq: &#39;daily&#39;,<br>  priority: 0.7,<br>};</pre><ul><li>siteUrl: Your full domain (with HTTPS), e.g. <a href="https://myportfolio.dev/">https://myportfolio.dev</a></li><li>generateRobotsTxt: If true, the plugin also creates a robots.txt file</li><li>changefreq: Suggests how often your content changes (for crawlers)</li><li>priority: Sets priority of pages for search engine crawling (0 to 1)</li></ul><h4>Step 3 — Add a postbuild script to package.json</h4><p>After building your Next.js app, we need to run next-sitemap to generate the files.json</p><pre>&quot;scripts&quot;: {<br>  &quot;build&quot;: &quot;next build&quot;,<br>  &quot;postbuild&quot;: &quot;next-sitemap&quot;<br>}</pre><ul><li>next build: Builds your app for production</li><li>postbuild: Automatically runs after build and creates sitemap.xml and robots.txt in the /public folder</li></ul><h3>2. Meta Tags and SEO Best Practices</h3><p>Meta tags are an essential part of SEO, as they provide critical information to search engines and social media platforms about your page content. In Next.js, we can use the &lt;Head&gt; component to add meta tags dynamically.</p><h4>2.1 Adding Essential Meta Tags</h4><p>Here’s an example of how to add meta tags for <strong>title</strong>, <strong>description</strong>, and <strong>keywords</strong>:</p><pre>import Head from &#39;next/head&#39;;</pre><pre>const SEO = () =&gt; (<br>  &lt;Head&gt;<br>    &lt;title&gt;SEO &amp; Google Ads Integration in Next.js&lt;/title&gt;<br>    &lt;meta name=&quot;description&quot; content=&quot;Learn how to integrate SEO and Google Ads in React and Next.js projects.&quot; /&gt;<br>    &lt;meta name=&quot;keywords&quot; content=&quot;SEO, Google Ads, Next.js, React&quot; /&gt;<br>  &lt;/Head&gt;<br>);</pre><h4>2.2 Open Graph &amp; Twitter Card Tags</h4><p>To improve how your page appears when shared on social media platforms, you should include <strong>Open Graph</strong> and <strong>Twitter Card</strong> tags. These meta tags control how your page looks when shared on platforms like Facebook and Twitter.</p><pre>&lt;Head&gt;<br>  &lt;meta property=&quot;og:title&quot; content=&quot;SEO &amp; Google Ads Integration in Next.js&quot; /&gt;<br>  &lt;meta property=&quot;og:description&quot; content=&quot;Learn how to integrate SEO and Google Ads in React and Next.js projects.&quot; /&gt;<br>  &lt;meta property=&quot;og:image&quot; content=&quot;https://your-domain.com/image.jpg&quot; /&gt;<br>  &lt;meta name=&quot;twitter:card&quot; content=&quot;summary_large_image&quot; /&gt;<br>  &lt;meta name=&quot;twitter:title&quot; content=&quot;SEO &amp; Google Ads Integration in Next.js&quot; /&gt;<br>  &lt;meta name=&quot;twitter:description&quot; content=&quot;Learn how to integrate SEO and Google Ads in React and Next.js projects.&quot; /&gt;<br>&lt;/Head&gt;</pre><p>These tags ensure that your page looks appealing when shared on platforms like Facebook or Twitter. However, an important point to note here is that <strong>you don’t need to include all the images from your app</strong>. Adding an image is only necessary if you want to customize how a specific image appears when shared on social media.</p><p>If you don’t add an image, social media platforms typically take the first image they find on the page. However, this image may not always be the best fit for social sharing.</p><p><strong>Extra Tip:</strong> Image sizes and aspect ratios matter for proper display on different platforms. For example, the summary_large_image card on Twitter recommends an image that is at least <strong>280x150px</strong>. Choosing the right image dimensions ensures your page looks professional when shared.</p><h3>Step 4 — Deploying Your Project &amp; Submitting to Google Search Console</h3><p>Once you’ve configured your meta tags, sitemap.xml, and robots.txt, it&#39;s time to take your project live and make sure Google can actually <em>see</em> your SEO setup.</p><p>Let’s break this down step by step:</p><h4>1 — Deploy to Vercel (or any hosting platform)</h4><p>The easiest way to host a Next.js app is through <a href="https://vercel.com/">Vercel</a>, which is optimized for server-side rendering and static site generation.</p><pre>npx vercel</pre><ul><li>Follow the CLI prompts</li><li>Choose your project folder</li><li>Connect your GitHub if necessary</li><li>After deployment, you’ll get a live link like:<br><a href="https://your-project-name.vercel.app/">https://your-project-name.vercel.app</a></li></ul><h4>2 — Verify Your Domain in Google Search Console</h4><p>Now that your site is live, you can ask Google to start indexing your pages.</p><blockquote><em>To do that:</em></blockquote><ol><li>Go to Google Search Console</li><li>Click <strong>“Add Property”</strong></li><li>Choose <strong>“URL prefix”</strong> and enter your deployed domain<br>e.g. <a href="https://your-project-name.vercel.app/">https://your-project-name.vercel.app</a></li><li>Verify using the <strong>HTML tag</strong> method (or use Google account)</li></ol><h4>3 — Submit sitemap.xml</h4><p>After verification:</p><ol><li>On the left panel, click <strong>Sitemaps</strong></li><li>In the field: enter sitemap.xml<br>e.g.<br><a href="https://your-project-name.vercel.app/sitemap.xml">https://your-project-name.vercel.app/sitemap.xml</a></li><li>Click <strong>Submit</strong></li></ol><p>If everything is configured correctly, you’ll see a “Success” message in a few seconds.</p><h4>4 — Test Your SEO</h4><p>Use tools like:</p><ul><li><strong>Google Lighthouse (built into Chrome DevTools)</strong><br>→ Run an SEO audit and check your meta tags</li><li><strong>Meta SEO Inspector (Chrome extension)</strong><br>→ Verify Open Graph, Twitter Cards, title, description, etc.</li></ul><h4>Extra Tip — Don’t Test on Localhost</h4><blockquote><em>SEO tools don’t work on </em><em>localhost.<br>To test your setup, always use the </em><strong><em>live domain</em></strong><em> after deploying.</em></blockquote><h3>2.4 — SSR, SSG, ISR: What Are They and How They Affect SEO?</h3><p>Next.js supports multiple rendering strategies, and each has a different impact on SEO.<br>Understanding the difference between them is essential for both performance and visibility in search engines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*xKB9LoLEF7bz_fG_O4fMBA.png" /></figure><h4>SSR with getServerSideProps</h4><pre>export async function getServerSideProps(context) {<br>  const res = await fetch(&#39;https://api.example.com/data&#39;);<br>  const data = await res.json();<br>  return { props: { data } };<br>}</pre><p>✅ Good for SEO, since bots always receive a fresh, server-rendered HTML<br>❌ Slower than static, since it renders on each request</p><h4>SSG with getStaticProps</h4><pre>export async function getStaticProps() {<br>  const res = await fetch(&#39;https://api.example.com/data&#39;);<br>  const data = await res.json();<br>  return { props: { data } };<br>}</pre><p>✅ Very fast and SEO-friendly<br>❌ Data is only updated at build time</p><h4>ISR with revalidate</h4><pre>export async function getStaticProps() {<br>  const res = await fetch(&#39;https://api.example.com/data&#39;);<br>  const data = await res.json();<br>  return {<br>    props: { data },<br>    revalidate: 60, // Rebuilds the page every 60 seconds<br>  };<br>}</pre><p>✅ Perfect for frequently-updating content<br>✅ Google sees pre-rendered HTML<br>✅ No need to rebuild entire app</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*gdDRQ8NmBmDsMwkEjrIRBQ.png" /></figure><h3>SEO Tip</h3><ul><li><strong>Always use one of these rendering strategies for content you want Google to index.</strong></li><li>Avoid client-only rendering (useEffect-based fetching) if SEO is important.</li><li>SSR and ISR ensure bots receive <strong>HTML content directly</strong>, not just empty divs.</li></ul><h3>3. Google Ads Integration (SEA) in Next.js</h3><p>SEO helps your content get discovered organically, but SEA (Search Engine Advertising) ensures you’re visible <em>right now</em>, especially on competitive keywords.</p><p>Let’s look at how to integrate <strong>Google Ads Tracking</strong>, including <strong>conversion tracking</strong>, into a React or Next.js project.</p><h4>3.1 Adding Google Ads Script</h4><p>To start tracking conversions or remarketing, you’ll need to add your <strong>Google Ads global site tag</strong> to your application.</p><p>You can get your tag from your Google Ads account under:<br>➡️ <em>Tools &amp; Settings → Conversions → Set up tag</em></p><h4>Step-by-step in Next.js</h4><h4>Step 1 — Add the script using &lt;Head&gt;</h4><p>In a layout component (or _app.js), add your Google Ads tag:</p><pre>import Head from &#39;next/head&#39;;<br><br>export default function Layout({ children }) {<br>  return (<br>    &lt;&gt;<br>      &lt;Head&gt;<br>        &lt;script<br>          async<br>          src={`https://www.googletagmanager.com/gtag/js?id=AW-XXXXXXXXXX`}<br>        &gt;&lt;/script&gt;<br>        &lt;script<br>          dangerouslySetInnerHTML={{<br>            __html: `<br>              window.dataLayer = window.dataLayer || [];<br>              function gtag(){dataLayer.push(arguments);}<br>              gtag(&#39;js&#39;, new Date());<br>              gtag(&#39;config&#39;, &#39;AW-XXXXXXXXXX&#39;);<br>            `,<br>          }}<br>        /&gt;<br>      &lt;/Head&gt;<br>      {children}<br>    &lt;/&gt;<br>  );<br>}</pre><blockquote><em>Replace </em><em>&#39;AW-XXXXXXXXXX&#39; with your actual Google Ads tracking ID.</em></blockquote><h4>3.2 — Google Ads Conversion Tracking (Form, Button, Pageview)</h4><p>Conversion tracking helps you understand what users do after clicking your ad.<br>For example:</p><ul><li>Did they submit a form?</li><li>Did they click a CTA button?</li><li>Did they reach a “Thank you” page?</li></ul><h4>What Is a Conversion?</h4><p>A conversion is <strong>a valuable user action</strong> — purchase, signup, click, etc.<br>We can track this with Google Ads by firing a custom event when the action happens.</p><h4>Option 1: Page-Based Conversion (e.g. “Thank You” page)</h4><p>If your user lands on a <strong>thank you page</strong> after submitting a form, you can fire a conversion like this:</p><pre>import { useEffect } from &#39;react&#39;;<br>import Head from &#39;next/head&#39;;<br><br>export default function ThankYou() {<br>  useEffect(() =&gt; {<br>    if (typeof window !== &#39;undefined&#39;) {<br>      window.gtag(&#39;event&#39;, &#39;conversion&#39;, {<br>        send_to: &#39;AW-XXXXXXXXXX/AbCdEfGhIjKlmNoP&#39;,<br>      });<br>    }<br>  }, []);<br><br>  return (<br>    &lt;&gt;<br>      &lt;Head&gt;<br>        &lt;title&gt;Thank You!&lt;/title&gt;<br>      &lt;/Head&gt;<br>      &lt;h1&gt;Thank you for your submission!&lt;/h1&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>Replace &quot;AW-XXXXXXXXXX/AbCdEfGhIjKlmNoP&quot; with your actual <strong>Google Ads conversion ID and label.</strong><br>You get these from the <strong>“Conversions” section</strong> in your Ads account.</p><h4>Option 2: Button Click Tracking</h4><p>If your goal is to track <strong>button clicks</strong>, you can add the same event to the onClick:</p><pre>const handleConversion = () =&gt; {<br>  if (typeof window !== &#39;undefined&#39;) {<br>    window.gtag(&#39;event&#39;, &#39;conversion&#39;, {<br>      send_to: &#39;AW-XXXXXXXXXX/AbCdEfGhIjKlmNoP&#39;,<br>    });<br>  }<br>};</pre><pre>&lt;button onClick={handleConversion}&gt;Submit&lt;/button&gt;</pre><h4>How to Test</h4><ol><li>Use <strong>Tag Assistant Chrome Extension</strong></li><li>Use Google Ads → Tools → Conversions → Status: “Verified”</li><li>Use Google Analytics (if linked) to see triggered events</li></ol><h4>Bonus Tip: Use it with Form Libraries</h4><p>If you’re using libraries like React Hook Form or Formik, you can call handleConversion() inside the onSubmit or handleSubmit functions after a successful submit.</p><h4>3.3 Event Tracking With Google Tag Manager (GTM)</h4><p>Sometimes managing all tracking scripts manually becomes hard to maintain — that’s where <strong>Google Tag Manager (GTM)</strong> comes in.</p><p>With GTM, you can manage all your tags (Google Ads, GA4, Facebook Pixel etc.) in one place — <strong>without changing your app code</strong> every time.</p><h4>Step 1 — Add GTM Script</h4><p>From your <a href="https://tagmanager.google.com/">GTM Dashboard</a>, create a new container.</p><p>Google will give you <strong>two snippets</strong>:</p><pre>&lt;script&gt;<br>  (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({&#39;gtm.start&#39;:<br>  new Date().getTime(),event:&#39;gtm.js&#39;});var f=d.getElementsByTagName(s)[0],<br>  j=d.createElement(s),dl=l!=&#39;dataLayer&#39;?&#39;&amp;l=&#39;+l:&#39;&#39;;j.async=true;j.src=<br>  &#39;https://www.googletagmanager.com/gtm.js?id=&#39;+i+dl;f.parentNode.insertBefore(j,f);<br>  })(window,document,&#39;script&#39;,&#39;dataLayer&#39;,&#39;GTM-XXXXXXX&#39;);<br>&lt;/script&gt;</pre><pre>&lt;noscript&gt;<br>  &lt;iframe src=&quot;https://www.googletagmanager.com/ns.html?id=GTM-XXXXXXX&quot;<br>  height=&quot;0&quot; width=&quot;0&quot; style=&quot;display:none;visibility:hidden&quot;&gt;&lt;/iframe&gt;<br>&lt;/noscript&gt;</pre><p>Replace GTM-XXXXXXX with your actual container ID.</p><p>In Next.js — Add Scripts</p><pre>// pages/_document.js<br>&lt;Head&gt;<br>  {/* GTM head script here */}<br>&lt;/Head&gt;<br>&lt;body&gt;<br>  {/* GTM body noscript iframe here */}<br>&lt;/body&gt;</pre><h4>Step 2 — Define a Custom Event in GTM</h4><ol><li>Go to your GTM container</li><li>Click <strong>“Triggers” → New → Trigger Type: Custom Event</strong></li><li>Set Event Name to purchase, formSubmit, etc.</li><li>Create a <strong>Tag</strong> that fires when that event occurs (e.g. Google Ads Conversion tag)</li></ol><h4>Step 3 — Fire Event from React</h4><p>In your component:</p><pre>window.dataLayer = window.dataLayer || [];<br>window.dataLayer.push({<br>  event: &#39;formSubmit&#39;,<br>  formType: &#39;contact&#39;,<br>});</pre><p>Now GTM will detect this and trigger your conversion.</p><h4>4. Test &amp; Validate SEO + Google Ads Setup</h4><p>Before publishing your site or launching ads, <strong>you need to test everything works.</strong><br>Here are some developer-friendly tools for that:</p><h4>4.1 SEO Testing Tools</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*FSk0b82aqvtvGXVvYihXsA.png" /></figure><h4>4.2 Google Ads &amp; GTM Test Tools</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*csUSZzd5lA4ZVCvkHTXrog.png" /></figure><p>Test these after deploying the project<br>Always use the <strong>live domain</strong>, not localhost, for testing with Google</p><h3>Step-by-Step Mini Project: SEO &amp; Google Ads Demo</h3><p>Let’s apply everything we’ve covered in a real-world Next.js project that integrates both SEO and Google Ads tracking.</p><h4>Step 1: Create a New Next.js Project</h4><p>Open your terminal and run:</p><pre>npx create-next-app seo-ads-demo<br>cd seo-ads-demo<br>npm install</pre><h4>Step 2: Project Structure</h4><p>Here’s the basic folder structure:</p><pre>/seo-ads-demo<br>├── pages/<br>│   ├── index.js         → Landing Page with Meta Tags<br>│   ├── contact.js       → Contact Form with event tracking<br>│   ├── thanks.js        → Conversion Thank You Page<br>│   ├── _app.js          → Google Ads Script<br>│   ├── _document.js     → Google Tag Manager Script<br>├── public/<br>│   ├── robots.txt<br>│   ├── sitemap.xml<br>│   └── logo.jpg         → Used for OG image<br>├── next-sitemap.config.js</pre><h4>Step 3: Install next-sitemap</h4><p>To generate robots.txt and sitemap.xml, install the package:</p><pre>npm install next-sitemap</pre><p>Then create a next-sitemap.config.js at the project root:</p><pre>module.exports = {<br>  siteUrl: &#39;https://your-domain.com&#39;,<br>  generateRobotsTxt: true,<br>  changefreq: &#39;daily&#39;,<br>  priority: 0.7,<br>};</pre><h4>Step 4: Update package.json</h4><p>Add a postbuild script to generate sitemap and robots.txt after build:</p><pre>&quot;scripts&quot;: {<br>  &quot;dev&quot;: &quot;next dev&quot;,<br>  &quot;build&quot;: &quot;next build&quot;,<br>  &quot;postbuild&quot;: &quot;next-sitemap&quot;<br>}</pre><p>Now that we have our structure ready…</p><h4>Step 5: Add SEO Meta Tags to the Home Page</h4><p>The homepage is where users and search engines often land first. Let’s make sure it has proper meta tags and Open Graph info.</p><p>Create or edit the pages/index.js file:</p><pre>import Head from &#39;next/head&#39;;<br><br>export default function Home() {<br>  return (<br>    &lt;&gt;<br>      &lt;Head&gt;<br>        &lt;title&gt;SEO &amp; Google Ads Integration in Next.js&lt;/title&gt;<br>        &lt;meta<br>          name=&quot;description&quot;<br>          content=&quot;Learn how to integrate SEO and Google Ads in React and Next.js projects.&quot;<br>        /&gt;<br>        &lt;meta<br>          name=&quot;keywords&quot;<br>          content=&quot;SEO, Google Ads, Next.js, React, Performance&quot;<br>        /&gt;<br><br>        {/* Open Graph Tags */}<br>        &lt;meta property=&quot;og:title&quot; content=&quot;SEO &amp; Google Ads in Next.js&quot; /&gt;<br>        &lt;meta<br>          property=&quot;og:description&quot;<br>          content=&quot;Boost your visibility using SEO &amp; Ads with Next.js&quot;<br>        /&gt;<br>        &lt;meta<br>          property=&quot;og:image&quot;<br>          content=&quot;https://your-domain.com/logo.jpg&quot;<br>        /&gt;<br><br>        {/* Twitter Card */}<br>        &lt;meta name=&quot;twitter:card&quot; content=&quot;summary_large_image&quot; /&gt;<br>        &lt;meta name=&quot;twitter:title&quot; content=&quot;SEO &amp; Google Ads in Next.js&quot; /&gt;<br>        &lt;meta<br>          name=&quot;twitter:description&quot;<br>          content=&quot;Step-by-step guide to SEO and Ads integration.&quot;<br>        /&gt;<br>      &lt;/Head&gt;<br><br>      &lt;main style={{ textAlign: &#39;center&#39;, marginTop: &#39;4rem&#39; }}&gt;<br>        &lt;h1&gt;Welcome to the SEO &amp; Google Ads Demo&lt;/h1&gt;<br>        &lt;p&gt;This project integrates all best practices step-by-step.&lt;/p&gt;<br>      &lt;/main&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><ul><li>You can customize the &lt;meta name=&quot;keywords&quot;&gt; list based on your app.</li><li>Don’t forget to replace &quot;https://your-domain.com/logo.jpg&quot; with the actual live domain where the image is hosted.</li><li>These tags are essential for SEO and social sharing (Facebook, Twitter, etc.)</li></ul><h4>SEO Meta Tag Test Result</h4><p>After adding the &lt;meta&gt; tags to our index.js, we wanted to verify if they’re working correctly on both search engines and social media platforms.</p><p>We used lighthouse to preview how our page would look when shared.</p><blockquote><em>✅ </em><strong><em>What did we test?</em></strong></blockquote><ul><li>Page Title</li><li>Description</li><li>Open Graph Preview (Facebook, LinkedIn)</li><li>Twitter Card</li></ul><h4>Lighthouse Audit Result</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*L-CSKN1Kxedw0r9CZBLpEw.png" /></figure><p>To ensure full SEO compatibility, we ran a Lighthouse test in Chrome DevTools.</p><p><strong>Passed Audits:</strong></p><ul><li>Document has a &lt;title&gt;</li><li>Document has a &lt;meta description&gt;</li><li>Page is not blocked from indexing</li><li>Valid robots.txt</li><li>All links are crawlable</li><li>Document has a valid hreflang</li></ul><blockquote><em>No </em><em>noindex headers detected. Meta tags were rendered correctly even for SSR.<br>Googlebot can now fully access and index the page content.</em></blockquote><h4>Final Notes</h4><p>Congratulations! Your Next.js project now has:</p><ul><li><strong>Fully crawlable content</strong></li><li><strong>Well-structured meta tags</strong></li><li><strong>SEO-optimized architecture</strong></li><li><strong>A production-ready sitemap and robots.txt configuration</strong></li></ul><p>You’ve just implemented an <strong>SEO foundation</strong> that’s ready for real-world deployment.</p><h4>Step 6: Add Google Ads Global Site Tag (gtag.js)</h4><p>To track conversions or page views in Google Ads, we need to add their global tracking script.</p><p>In a Next.js app, the best place to add global scripts is inside pages/_app.js using the next/script component.</p><pre>import Script from &#39;next/script&#39;;<br><br>export default function MyApp({ Component, pageProps }) {<br>  return (<br>    &lt;&gt;<br>      {/* Global Site Tag (gtag.js) - Google Ads */}<br>      &lt;Script<br>        strategy=&quot;afterInteractive&quot;<br>        src=&quot;https://www.googletagmanager.com/gtag/js?id=AW-XXXXXXXXXX&quot;<br>      /&gt;<br>      &lt;Script<br>        id=&quot;gtag-init&quot;<br>        strategy=&quot;afterInteractive&quot;<br>        dangerouslySetInnerHTML={{<br>          __html: `<br>              window.dataLayer = window.dataLayer || [];<br>              function gtag(){dataLayer.push(arguments);}<br>              gtag(&#39;js&#39;, new Date());<br>              gtag(&#39;config&#39;, &#39;AW-XXXXXXXXXX&#39;);<br>          `,<br>        }}<br>      /&gt;<br><br>      &lt;Component {...pageProps} /&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>Replace AW-XXXXXXXXXX with your real Google Ads Conversion ID.</p><h4>What does this do?</h4><ul><li>This script enables Google Ads to track visits and page views on your site.</li><li>When you create a <strong>conversion action</strong> in your Google Ads dashboard, it will be linked to the AW-XXXXXXXXXX ID here.</li><li>Without this script, Google Ads <strong>cannot track conversions</strong>, even if you set them up correctly in the dashboard.</li></ul><h4>What Did We Implement?</h4><ul><li>Added Google Ads script to &lt;Head&gt; (with correct AW-XXXXXX ID).</li><li>Triggered a conversion event on the /thanks page.</li><li>Ensured the script loads <strong>before</strong> the conversion event fires.</li></ul><h4>How to Test if gtag.js is Working?</h4><p>There are a few ways to check if your <strong>Google Ads tag</strong> is firing correctly:</p><p>To test and confirm if your gtag.js or Google Ads tags are working properly, it&#39;s helpful to install a browser extension:</p><p><strong>Install Google Tag Assistant (Legacy)</strong><br>→ Chrome Web Store — Tag Assistant</p><p>After installing:</p><ol><li>Go to your deployed project URL</li><li>Open the extension from your browser</li><li>Click “Enable” and refresh the page</li><li>You’ll see detected tags like gtag.js, AW-XXXXXXX, etc.</li></ol><p>📌 This tool helps you validate that your Google Ads tags are firing correctly and that events (like page_view) are being sent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*OY8mxkYaRPFhZWF_WD-ozw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*rFyjJm3nDEpoPRS78LtXhw.png" /></figure><p>The screenshot below confirms that the Google Ads Global Site Tag (gtag.js) is successfully tracking a page_view event:</p><ul><li>tid: Measurement ID (Google Ads Conversion ID)</li><li>dl: Page Location (Current URL)</li><li>dt: Page Title</li><li>en: Event Name (page_view)</li></ul><p>This ensures that Google Ads is receiving accurate data about page visits, which is essential for running conversion-based ad campaigns.</p><h4>Step 7: Contact Form + Conversion Thank You Page</h4><p>In this step, we’ll simulate a conversion flow in a real-world scenario. This is critical for tracking user actions (like lead submissions or purchases) with <strong>Google Ads</strong>.User lands on /contact</p><ul><li>A /contact page with a simple form.</li><li>On submit, redirect to a /thanks page.</li><li>Trigger a Google Ads conversion event on the /thanks page.</li></ul><h4>Important Notes:</h4><ul><li>Make sure to replace AW-XXXXXXXXXX/abc123XYZ456 with the <strong>actual conversion ID and label</strong> from Google Ads.</li><li>The gtag(&#39;event&#39;, &#39;conversion&#39;) is what tells Google Ads that a goal has been completed.</li></ul><h4>1 — Create pages/contact.js</h4><pre>import { useState } from &quot;react&quot;;<br>import { useRouter } from &quot;next/router&quot;;<br><br>export default function Contact() {<br>  const [name, setName] = useState(&quot;&quot;);<br>  const router = useRouter();<br><br>  const handleSubmit = (e) =&gt; {<br>    e.preventDefault();<br>    router.push(&quot;/thanks&quot;);<br>  };<br><br>  return (<br>    &lt;div style={{ padding: &quot;2rem&quot; }}&gt;<br>      &lt;h2&gt;Contact Us&lt;/h2&gt;<br>      &lt;form onSubmit={handleSubmit}&gt;<br>        &lt;input<br>          type=&quot;text&quot;<br>          placeholder=&quot;Your name&quot;<br>          value={name}<br>          onChange={(e) =&gt; setName(e.target.value)}<br>          required<br>        /&gt;<br>        &lt;button type=&quot;submit&quot;&gt;Send&lt;/button&gt;<br>      &lt;/form&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h4>2 — Create pages/thanks.js</h4><pre>import { useEffect } from &quot;react&quot;;<br>import Script from &quot;next/script&quot;;<br><br>export default function Thanks() {<br>  useEffect(() =&gt; {<br>    if (typeof window !== &quot;undefined&quot; &amp;&amp; window.gtag) {<br>      window.gtag(&quot;event&quot;, &quot;conversion&quot;, {<br>        send_to: &quot;AW-XXXXXXXXXX/abc123XYZ456&quot;, // Replace with your real ID<br>      });<br>    }<br>  }, []);<br><br>  return (<br>    &lt;&gt;<br>      &lt;h2&gt;Thank you for your message!&lt;/h2&gt;<br>      &lt;p&gt;We’ll get back to you soon.&lt;/p&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><h4>Contact Form + Conversion Test Result;</h4><p>To verify that the Google Ads <strong>conversion event</strong> is triggered properly after form submission, we used a simple contact → thank-you flow.</p><h4>What We Tested</h4><ul><li>Visiting /contact page</li><li>Filling out the form and clicking <strong>Send</strong></li><li>Getting redirected to /thanks page</li><li>Checking if the gtag(&#39;event&#39;, &#39;conversion&#39;) was successfully triggered</li></ul><h4>Tools Used for Verification</h4><h4>1. Google Tag Assistant (Legacy)</h4><ul><li>Before form submission: Only global site tag (gtag.js) was detected</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*h5vlczmrkoXTtLlfFMjGbw.png" /></figure><ul><li>After form submission: Google Ads Conversion tag appeared in the report</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*7B9HH7BCurpoqrMtCDsk7w.png" /></figure><h4>2. DevTools Network Tab</h4><ul><li>On the /thanks page, we opened DevTools → <strong>Network</strong> tab</li><li>Searched for: collect</li><li>Found a request to: https://www.google.com/collect?en=conversion...<br>Included correct AW-XXXXXX/label in parameters<br>This confirms the <strong>conversion event</strong> was sent to Google Ads</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*oXX3E_KgipjmB2pSWuaDfw.png" /></figure><h4>Step 8: Google Tag Manager (GTM) Integration in Next.js</h4><p>Google Tag Manager lets you manage and deploy tags (scripts) without directly editing your site’s code.</p><p>We’ll integrate it into our app and prepare for custom <strong>event tracking</strong> (like button clicks or form submissions).</p><h4>1 — Create a GTM Container</h4><ol><li>Go to <a href="https://tagmanager.google.com/">https://tagmanager.google.com/</a></li><li>Create an account &amp; container (choose “Web” as the target)</li><li>After creation, you’ll get a <strong>GTM ID</strong> like GTM-XXXXXXX</li></ol><h4>2 — Add GTM Snippet in _document.js</h4><p>We’ll inject the GTM script in the &lt;head&gt; and &lt;body&gt; using pages/_document.js.</p><pre>import Document, { Html, Head, Main, NextScript } from &#39;next/document&#39;;<br><br>export default class MyDocument extends Document {<br>  render() {<br>    return (<br>      &lt;Html&gt;<br>        &lt;Head&gt;<br>          {/* Google Site Verification */}<br>          &lt;meta<br>            name=&quot;google-site-verification&quot;<br>            content=&quot;IwEHYLoX5zFIYsdLvovNiW1v33Ms9Ks6_vIgYThFBLA&quot;<br>          /&gt;<br>          {/* Google Tag Manager */}<br>          &lt;script<br>            dangerouslySetInnerHTML={{<br>              __html: `<br>                (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({&#39;gtm.start&#39;:<br>                new Date().getTime(),event:&#39;gtm.js&#39;});var f=d.getElementsByTagName(s)[0],<br>                j=d.createElement(s),dl=l!=&#39;dataLayer&#39;?&#39;&amp;l=&#39;+l:&#39;&#39;;j.async=true;j.src=<br>                &#39;https://www.googletagmanager.com/gtm.js?id=&#39;+i+dl;f.parentNode.insertBefore(j,f);<br>              })(window,document,&#39;script&#39;,&#39;dataLayer&#39;,&#39;GTM-PJ79VL8C&#39;);<br>              `,<br>            }}<br>          /&gt;<br>        &lt;/Head&gt;<br>        &lt;body&gt;<br>          {/* Google Tag Manager (noscript) */}<br>          &lt;noscript&gt;<br>            &lt;iframe<br>              src=&quot;https://www.googletagmanager.com/ns.html?id=GTM-PJ79VL8C&quot;<br>              height=&quot;0&quot;<br>              width=&quot;0&quot;<br>              style={{ display: &#39;none&#39;, visibility: &#39;hidden&#39; }}<br>            &gt;&lt;/iframe&gt;<br>          &lt;/noscript&gt;<br><br>          &lt;Main /&gt;<br>          &lt;NextScript /&gt;<br>        &lt;/body&gt;<br>      &lt;/Html&gt;<br>    );<br>  }<br>}</pre><blockquote><em>Replace </em><em>&#39;GTM-XXXXXXX&#39; with your actual GTM ID.</em></blockquote><h4>Quick Explanation</h4><p><strong>GTM Setup</strong>: You added Google Tag Manager (GTM) to both the &lt;head&gt; and &lt;body&gt; sections of your application. The first script initializes GTM (JavaScript), and the &lt;noscript&gt; section ensures that GTM still functions on browsers where JavaScript is disabled.</p><p><strong>Button Click Event</strong>:</p><ul><li>When the “Send” button is clicked, the handleSubmit function in your React component is triggered.</li><li>Inside handleSubmit, you&#39;re pushing a custom event to the dataLayer:</li><li>This sends an event to GTM with details about the form submission.</li></ul><p><strong>Console Output</strong>:</p><ul><li>After clicking the button, if you check the window.dataLayer in your browser console, you should see the pushed event data. It should look something like this:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*k3B4YQfRPNxgMwjfiFuJ6A.png" /></figure><p>The form_submission event, along with the associated action, category, and label, will appear in the dataLayer.</p><p><strong>After the Event</strong>:</p><ul><li>The event data is sent to GTM, and you can use this data to trigger tags in Google Tag Manager. For example, you might have a tag configured to fire when the form_submission event is detected.</li><li>The page then redirects to the /thanks page after simulating a successful form submission.</li></ul><pre>import { useState } from &quot;react&quot;;<br>import { useRouter } from &quot;next/router&quot;;<br><br>export default function Contact() {<br>  const [name, setName] = useState(&quot;&quot;);<br>  const [isSubmitting, setIsSubmitting] = useState(false); <br>  const router = useRouter();<br><br>  const handleSubmit = (e) =&gt; {<br>    e.preventDefault();<br>    setIsSubmitting(true); <br><br>    if (typeof window !== &quot;undefined&quot;) {<br>      window.dataLayer = window.dataLayer || [];<br>      window.dataLayer.push({<br>        event: &quot;form_submission&quot;,<br>        action: &quot;submit_form&quot;,<br>        category: &quot;Contact Form&quot;,<br>        label: &quot;Send Button&quot;,<br>        name: name,<br>      });<br>    }<br><br>    setTimeout(() =&gt; {<br>      setIsSubmitting(false); <br>      router.push(&quot;/thanks&quot;);<br>    }, 1000); <br>  };<br><br>  return (<br>    &lt;div style={{ padding: &quot;2rem&quot; }}&gt;<br>      &lt;h2&gt;Contact Us&lt;/h2&gt;<br>      &lt;form onSubmit={handleSubmit}&gt;<br>        &lt;input<br>          type=&quot;text&quot;<br>          placeholder=&quot;Your name&quot;<br>          value={name}<br>          onChange={(e) =&gt; setName(e.target.value)}<br>          required<br>        /&gt;<br>        &lt;button type=&quot;submit&quot; disabled={isSubmitting}&gt;<br>          {isSubmitting ? &quot;Sending...&quot; : &quot;Send&quot;}<br>        &lt;/button&gt;<br>      &lt;/form&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>This is the full component for form and sending gtm events.</p><h3>Conclusion</h3><p>In this article, we walked through how to integrate SEO techniques into a modern web project step by step. On the SEO side, we implemented essential practices such as meta tags, OpenGraph configurations, sitemap and robots.txt setup, and discussed the differences between SSR and SSG.</p><p>We tested all of these steps in a simple Next.js project, organic and paid traffic strategies into a single, practical workflow.</p><h3>Thank You!</h3><p>Thanks for reading! I hope you found this article helpful.<br> If you have any questions, feedback, or just want to connect, feel free to reach out:</p><ul><li>📧 Email: atacanerdoan@gmail.com</li><li>💼 LinkedIn: <a href="https://www.linkedin.com/in/atacan-erdogan/">https://www.linkedin.com/in/atacan-erdogan/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=753fec960341" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React ile Progressive Web App (PWA) Geliştirme Rehberi]]></title>
            <link>https://medium.com/@datacann/react-ile-progressive-web-app-pwa-geli%C5%9Ftirme-rehberi-01073818f44a?source=rss-355ed011d32e------2</link>
            <guid isPermaLink="false">https://medium.com/p/01073818f44a</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[service-worker]]></category>
            <category><![CDATA[pwa]]></category>
            <category><![CDATA[progressive-web-app]]></category>
            <dc:creator><![CDATA[Atacan Erdoğan]]></dc:creator>
            <pubDate>Fri, 21 Feb 2025 11:14:10 GMT</pubDate>
            <atom:updated>2025-02-21T11:15:20.681Z</atom:updated>
            <content:encoded><![CDATA[<h3>PWA Nedir ve Neden Kullanmalıyız?</h3><p><strong>Progressive Web Apps (PWA)</strong>, web uygulamalarını mobil uygulamalar gibi çalıştıran bir teknolojidir. PWA’lar, hızlı yükleme süreleri, çevrimdışı çalışma yeteneği ve push bildirimleri gibi özelliklerle modern web uygulamalarına güç katar.</p><p>PWA kullanmanın avantajları:</p><ul><li><strong>Hızlı Yükleme:</strong> İçeriği önbelleğe alarak sayfa yükleme sürelerini azaltır.</li><li><strong>Çevrimdışı Çalışma:</strong> Kullanıcıların internet bağlantısı olmasa bile uygulamayı kullanabilmesini sağlar.</li><li><strong>Push Bildirimleri:</strong> Kullanıcı etkileşimini artırmak için bildirimler gönderebilir.</li><li><strong>Cihazlara Yüklenebilirlik:</strong> Kullanıcılar PWA’yı cihazlarının ana ekranına ekleyebilir.</li></ul><p>Bu yazıda <strong>React ile bir PWA geliştirme sürecini</strong> anlatacağım.</p><h3>React ile PWA Projesi Oluşturma</h3><p>Öncelikle bir React projesi oluşturalım ve PWA desteğini ekleyelim:</p><pre>npx create-react-app my-pwa-app --template cra-template-pwa<br>cd my-pwa-app<br>npm start</pre><p>Bu komut, <strong>service worker</strong> desteği ile gelen bir React projesi oluşturur.</p><blockquote><em>Eğer mevcut bir React projeniz varsa, </em><em>public/manifest.json ve </em><em>src/service-worker.js dosyalarını ekleyerek PWA desteği sağlayabilirsiniz.</em></blockquote><h3>1. Manifest.json Dosyası</h3><p>public/manifest.json dosyası, uygulamanın mobil cihazlarda nasıl görüneceğini belirler. Örneğin:</p><pre>{<br>  &quot;short_name&quot;: &quot;MyPWA&quot;,<br>  &quot;name&quot;: &quot;My Progressive Web App&quot;,<br>  &quot;icons&quot;: [<br>    {<br>      &quot;src&quot;: &quot;/icon-192x192.png&quot;,<br>      &quot;type&quot;: &quot;image/png&quot;,<br>      &quot;sizes&quot;: &quot;192x192&quot;<br>    }<br>  ],<br>  &quot;start_url&quot;: &quot;/&quot;,<br>  &quot;display&quot;: &quot;standalone&quot;,<br>  &quot;theme_color&quot;: &quot;#ffffff&quot;,<br>  &quot;background_color&quot;: &quot;#ffffff&quot;<br>}</pre><p>Bu dosya, <strong>ana ekran simgesi, başlangıç URL’si ve renk ayarları</strong> gibi bilgileri içerir.</p><h3>2. Offline.html Dosyası</h3><p>offline.html sayfası, internet bağlantısı <strong>kesildiğinde</strong> veya <strong>istek başarısız olduğunda</strong> kullanıcının <strong>göstermek için bir yedek sayfaya sahip olmasını sağlar</strong>.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;tr&quot;&gt;<br>&lt;head&gt;<br>  &lt;meta charset=&quot;UTF-8&quot;&gt;<br>  &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>  &lt;title&gt;Çevrimdışı&lt;/title&gt;<br>  &lt;style&gt;<br>    body {<br>      font-family: Arial, sans-serif;<br>      text-align: center;<br>      padding: 50px;<br>    }<br>  &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;h1&gt;Çevrimdışı Moddasınız&lt;/h1&gt;<br>  &lt;p&gt;Lütfen internet bağlantınızı kontrol edin ve tekrar deneyin.&lt;/p&gt;<br>&lt;/body&gt;<br>&lt;/html</pre><p>Bu html sayfasını offline durumdayken kullanıcıya göstereceğiz.</p><h3>3. Service Worker ile Önbellekleme ve Çevrimdışı Destek</h3><p>PWA’nın en önemli bileşeni <strong>Service Worker</strong>’dır. Service Worker, tarayıcı ile web sunucusu arasında çalışan bir betik dosyasıdır. Sayfanın yüklenmesini hızlandırır, çevrimdışı modda çalışmasını sağlar ve arka planda veri senkronizasyonu gibi gelişmiş özellikler sunar.</p><p>Service Worker temel olarak üç aşamada çalışır:</p><ol><li><strong>Kurulum (Install):</strong> Belirtilen dosyaları önbelleğe alır.</li><li><strong>Aktif Olma (Activate):</strong> Eski önbelleği temizler ve yeni önbelleği devreye alır.</li><li><strong>İstekleri Yakalayıp Yönlendirme (Fetch):</strong> Kullanıcının yaptığı ağ isteklerini önbellekten ya da ağdan getirerek yönetir.</li></ol><p>public/service-worker.js dosyası aşağıdaki gibi yapılandırılabilir:</p><pre>/* eslint-disable no-restricted-globals */<br>const CACHE_NAME = &#39;my-pwa-cache-v1&#39;;<br>const urlsToCache = [<br>  &#39;/&#39;,<br>  &#39;/index.html&#39;,<br>  &#39;/offline.html&#39;,<br>  &#39;/manifest.json&#39;,<br>  &#39;/favicon.ico&#39;,<br>  &#39;/icon-192x192.png&#39;,<br>  &#39;/static/js/main.chunk.js&#39;,<br>  &#39;/static/js/bundle.js&#39;,<br>  &#39;/static/css/main.chunk.css&#39;,<br>  &#39;/static/css/main.f855e6bc.css&#39;,<br>  &#39;/static/js/main.fe4b49b5.js&#39;,<br>];</pre><p>Burada önbelleğimizin adını ve önbellekte saklanması gereken dosyalarımızı belirledik.</p><pre>self.addEventListener(&#39;install&#39;, (event) =&gt; {<br>  event.waitUntil(<br>    caches.open(CACHE_NAME).then((cache) =&gt; {<br>      return cache.addAll(urlsToCache);<br>    })<br>  );<br>});</pre><ul><li>install olayı, Service Worker ilk defa yüklenirken veya güncellenirken tetiklenir.</li><li><strong>Amaç:</strong> Gerekli dosyaları önbelleğe almak.</li><li>caches.open(CACHE_NAME), belirlenen CACHE_NAME adında bir önbellek açar.</li><li>Eğer önceden böyle bir önbellek yoksa, yeni bir tane oluşturur.</li><li>cache nesnesi, açılan önbelleği temsil eder.</li><li>cache.addAll(urlsToCache), önceden belirlediğimiz <strong>tüm statik dosyaları</strong> (urlsToCache dizisindeki) önbelleğe ekler.</li><li>Bu sayede uygulama çevrimdışıyken bile bu dosyalar kullanılabilir.</li></ul><h3>Bu Kodu Neden Kullanıyoruz?</h3><ol><li><strong>İlk yüklemede gerekli dosyaları cache’e ekler.</strong><br>→ Kullanıcı sayfayı bir kere açtığında dosyalar önbelleğe alınır.</li><li><strong>Çevrimdışı destek sağlar.</strong><br>→ Kullanıcının internet bağlantısı kesilse bile sayfa yüklenebilir.</li><li><strong>Daha hızlı yükleme süresi sunar.</strong><br>→ Önceden cache’e alınmış dosyalar, ağdan indirmek yerine tarayıcı tarafından hemen gösterilir.</li></ol><pre>self.addEventListener(&#39;fetch&#39;, (event) =&gt; {<br>  if (event.request.mode === &#39;navigate&#39;) {<br>    event.respondWith(<br>      fetch(event.request).catch(() =&gt; caches.match(&#39;/offline.html&#39;))<br>    );<br>  } else {<br>    event.respondWith(<br>      caches.match(event.request).then((cachedResponse) =&gt; {<br>        return cachedResponse || fetch(event.request);<br>      })<br>    );<br>  }<br>});</pre><ul><li><strong>fetch olayı</strong>, kullanıcı herhangi bir kaynağa (örneğin bir sayfaya, CSS dosyasına, API’ye) istek yaptığında tetiklenir.</li><li><strong>Amaç:</strong> Önce cache’den veriyi çekmek, eğer yoksa internetten almak.</li></ul><pre>if (event.request.mode === &#39;navigate&#39;) {</pre><p>Eğer yapılan istek bir <strong>sayfa yükleme isteği</strong> (navigate), yani kullanıcı bir sayfayı açmaya çalışıyorsa bu blok çalışır.</p><ul><li><strong>fetch(event.request)</strong><br>→ İlk olarak, sayfa internetten <strong>canlı olarak</strong> yüklenmeye çalışılır.</li><li><strong>catch(() =&gt; caches.match(‘/offline.html’))</strong><br>→ Eğer internet yoksa (fetch() başarısız olursa), /offline.html adlı önbellekteki sayfa gösterilir.<br>→ <strong>Bu sayede, kullanıcı çevrimdışıyken özel bir &quot;Çevrimdışı Sayfa&quot; görebilir.</strong></li></ul><pre>} else {<br>  event.respondWith(<br>    caches.match(event.request).then((cachedResponse) =&gt; {<br>      return cachedResponse || fetch(event.request);<br>    })<br>  );<br>}</pre><ul><li>Sayfa yükleme isteği (navigate) değilse (örneğin bir <strong>CSS, JS veya API isteği</strong>), bu blok çalışır.</li><li><strong>caches.match(event.request)</strong><br>→ İlk olarak, istenen kaynağın (event.request) önbellekte olup olmadığı kontrol edilir.</li><li><strong>return cachedResponse || fetch(event.request)</strong><br>→ Eğer önbellekte varsa (cachedResponse), doğrudan onu döndür.<br>→ Eğer önbellekte yoksa, <strong>internetten getirmeye çalış</strong> (fetch(event.request)).</li></ul><h3>Bu Kodu Neden Kullanıyoruz?</h3><ol><li><strong>Çevrimdışı destek sağlamak için</strong><br>→ Kullanıcı interneti kesildiğinde <strong>önceden kaydedilmiş sayfa</strong> gösterilir.</li><li><strong>Hızlı yükleme sağlamak için</strong><br>→ CSS, JS gibi statik dosyalar önbellekten çağrılarak daha hızlı yüklenir.</li><li><strong>Kullanıcı deneyimini iyileştirmek için</strong><br>→ Eğer internet yoksa bile, en azından bir <strong>“offline.html”</strong> göstererek kötü bir deneyimi önler.</li></ol><pre>  self.addEventListener(&#39;activate&#39;, (event) =&gt; {<br>    const cacheWhitelist = [CACHE_NAME]; <br>    event.waitUntil(<br>      caches.keys().then((cacheNames) =&gt; {<br>        return Promise.all(<br>          cacheNames.map((cacheName) =&gt; {<br>            if (!cacheWhitelist.includes(cacheName)) {<br>              return caches.delete(cacheName);<br>            }<br>          })<br>        );<br>      })<br>    );<br>  });</pre><ul><li><strong>activate olayı</strong>, Service Worker’ın yüklendikten sonra etkinleştiği an tetiklenir.</li><li><strong>Amaç:</strong> Eski, gereksiz önbellekleri temizleyerek güncel önbelleği kullanmak.</li><li><strong>cacheWhitelist</strong> değişkeni, <strong>saklanması gereken geçerli önbellekleri</strong> tanımlar.</li><li>CACHE_NAME → <strong>Şu anki geçerli önbelleğin adı</strong> (my-pwa-cache-v1 gibi).</li><li><strong>caches.keys()</strong> → Tarayıcıda <strong>mevcut tüm önbelleklerin</strong> listesini alır.</li><li><strong>Amaç:</strong> Kullanılmayan önbellekleri belirlemek.</li><li><strong>cacheNames.map()</strong> → Mevcut önbellekler üzerinde döngü yapar.</li><li><strong>if (!cacheWhitelist.includes(cacheName))</strong><br>→ Eğer önbellek <strong>whitelist’te yoksa</strong>, yani artık kullanılmıyorsa:<br><strong>caches.delete(cacheName)</strong> → O önbelleği sil.</li></ul><h3>Bu Kodu Neden Kullanıyoruz?</h3><ol><li><strong>Önbellek şişmesini önlemek için</strong><br>→ Eski versiyonları temizleyerek <strong>gereksiz önbellekleri siler</strong>.<br>→ Örneğin, my-pwa-cache-v1 yerine yeni bir my-pwa-cache-v2 tanımlandıysa, v1 silinir.</li><li><strong>Yeni versiyonun doğru çalışmasını sağlamak için</strong><br>→ Kullanıcı eski bir önbellekten değil, <strong>yeni önbellekten yükleme yapar</strong>.</li><li><strong>Bellek tüketimini azaltmak için</strong><br>→ Tarayıcının depolama alanını optimize eder, <strong>gereksiz verileri kaldırır</strong>.</li></ol><pre>const CACHE_NAME = &#39;my-pwa-cache-v1&#39;;<br>const urlsToCache = [<br>  &#39;/&#39;,<br>  &#39;/index.html&#39;,<br>  &#39;/offline.html&#39;,<br>  &#39;/manifest.json&#39;,<br>  &#39;/static/js/main.chunk.js&#39;,<br>  &#39;/static/js/bundle.js&#39;,<br>  &#39;/static/css/main.chunk.css&#39;<br>];<br><br>// Service Worker Kurulumu (Install)<br>self.addEventListener(&#39;install&#39;, (event) =&gt; {<br>  event.waitUntil(<br>    caches.open(CACHE_NAME).then((cache) =&gt; {<br>      console.log(&#39;Cache oluşturuldu!&#39;);<br>      return cache.addAll(urlsToCache);<br>    })<br>  );<br>});<br><br>// Önbelleğe alınan içerikleri kullanma (Fetch)<br>self.addEventListener(&#39;fetch&#39;, (event) =&gt; {<br>  if (event.request.mode === &#39;navigate&#39;) {<br>    event.respondWith(<br>      fetch(event.request).catch(() =&gt; caches.match(&#39;/offline.html&#39;))<br>    );<br>  } else {<br>    event.respondWith(<br>      caches.match(event.request).then((cachedResponse) =&gt; {<br>        return cachedResponse || fetch(event.request);<br>      })<br>    );<br>  }<br>});<br><br>// Önbellek Temizleme (Activate)<br>self.addEventListener(&#39;activate&#39;, (event) =&gt; {<br>  const cacheWhitelist = [CACHE_NAME];<br>  event.waitUntil(<br>    caches.keys().then((cacheNames) =&gt; {<br>      return Promise.all(<br>        cacheNames.map((cacheName) =&gt; {<br>          if (!cacheWhitelist.includes(cacheName)) {<br>            return caches.delete(cacheName);<br>          }<br>        })<br>      );<br>    })<br>  );<br>});</pre><p><em>service-worker.js in tam hali.</em></p><h3>4. Service Worker Registiration</h3><p>Bu modül, <strong>Service Worker’ı</strong> (SW) tarayıcıya kaydeden (register) ve gerekirse kaldıran (unregister) bir modül.</p><pre>export function register(config) {<br>    if (&#39;serviceWorker&#39; in navigator) {<br>      window.addEventListener(&#39;load&#39;, () =&gt; {<br>        navigator.serviceWorker<br>          .register(&#39;http://localhost:3000/service-worker.js&#39;)<br>          .then((registration) =&gt; {<br>            console.log(&#39;Service Worker registered: &#39;, registration);<br>          })<br>          .catch((error) =&gt; {<br>            console.error(&#39;Service Worker registration failed: &#39;, error);<br>          });<br>      });<br>    }<br>  }</pre><p>Satır satır inceleyelim.</p><pre>if (&#39;serviceWorker&#39; in navigator)</pre><ul><li>Tarayıcının Service Worker destekleyip desteklemediğini kontrol eder.</li><li>Desteklemiyorsa fonksiyon çalışmaz.</li><li><strong>Eğer destekliyorsa</strong>, SW kaydetme sürecine devam eder.</li></ul><pre>window.addEventListener(&#39;load&#39;, () =&gt; { ... });</pre><p>Sayfa tamamen yüklendiğinde (load event’i) çalışır, Service Worker dosyasını (service-worker.js) kaydeder.</p><pre>navigator.serviceWorker<br>  .register(&#39;http://localhost:3000/service-worker.js&#39;)</pre><ul><li>Service Worker’ın dosya yolu belirlenir.</li><li>http://localhost:3000/service-worker.js yerel geliştirme ortamı için bir path.</li><li>Gerçek projelerde, &#39;/service-worker.js&#39; şeklinde kullanılır.</li></ul><pre>.then((registration) =&gt; {<br>    console.log(&#39;Service Worker registered: &#39;, registration);<br>})</pre><p>Başarıyla kaydedildiğinde <strong>tarayıcının Service Worker listesine eklenir</strong>.</p><pre>.catch((error) =&gt; {<br>    console.error(&#39;Service Worker registration failed: &#39;, error);<br>});</pre><p>Eğer hata olursa <strong>neden başarısız olduğu konsola yazdırılır</strong>.</p><pre>export function unregister() {<br>    if (&#39;serviceWorker&#39; in navigator) {<br>      navigator.serviceWorker.ready.then((registration) =&gt; {<br>        registration.unregister();<br>      });<br>    }<br>}</pre><p>Register fonksiyonunudan farklı olarak <em>registration.unregister()</em> ile service worker tarayıcıdan kaldırılır.</p><p>Tarayıcının Service Worker destekleyip desteklemediğini kontrol eder.</p><h3>5. PWA’yı Test Etme</h3><p>Öncelikle kodumuzu ayağa kaldıralım.</p><pre>npm run build<br>npm start</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4EqU3QCgcmpczA7S5z4VTA.png" /></figure><p>Açılan sayfaya baktığımızda <em>manifest.json</em> , ve <em>offline.html</em> i görebiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*_imEvnziVoZVEHJG8kr0sg.png" /></figure><p>Status’e baktığımızda 200 ü görürüz aynı zamanda bu response un ağ tarafından geldiğiniz gösterir.</p><p>Şimdi ekranı yenileyelim;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FAOvycFi0TWXYZRGUPwd_g.png" /></figure><p>Burada ise bu response lara bakarsak;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*Ke8DTaUKC_azNEj0GxHeEw.png" /></figure><p>Bu response ların service worker tarafından sağlandığını görebiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e7pcv-fwImEvX8_jjmfFKQ.png" /></figure><p>Application alanına bakarsak buradaki Service Workers ın activated and is running mesajını görürüz bu da service worker ın hatasız çalıştığını görürüz. Ayrıca unregister ile service worker ı kapatabiliriz. ( eğer bir bilgiyi service worker tarafında sağlıyorsak ve bir güncelleme geldiyse bu güncellemeyi service worker tarafına dinletmek için unregister olunabilir)</p><p>Eğer test ederken service workerı en baştan test etmek istersek Update on reload işaretlenip ardından unregister ile service worker’ın çalışmasını tekrar başlatabiliriz.</p><p>Offline ı işaretlersek de interneti kapatmış gibi PWA’yı test edebiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gjEcSoUDqtIemM9eG6mjyg.png" /></figure><p>Cache storage’a baktığımızda CACHE_NAME isimli bir array olarak bu dosyaları tutuyorduk burada da bu dosyaların önbelleğe alındığını görebiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aX96x4uqdd9JngZZbY8Wnw.png" /></figure><p>Network tabında offline ı seçerek veya</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6We0oySlabBIWZdob5xB-w.png" /></figure><p>Application tabındaki Service worker ın içinden offline seçerek tarayıcının offline moda girmesini sağlayabiliriz.</p><p>Burada ekrana bakarsak offline.html i gösterdiğimizi görürüz.</p><p>Eğer bu geliştirmeleri yapmasaydık</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YXu-wfjgCt3CT1TraqWWjw.png" /></figure><p>Offline modda bu hatayı alacaktık. (Cache lediğimiz dosyaları silip sayfayı seniledik)</p><h3>6. Sonuç</h3><h3>React ile PWA Geliştirme — Özet</h3><p>Bu rehberde, <strong>React ile Progressive Web App (PWA) geliştirme sürecini</strong> adım adım ele aldık.</p><p>✅ <strong>PWA Nedir?</strong> — Hızlı, çevrimdışı çalışabilen ve cihazlara yüklenebilen modern web uygulamalarıdır.<br>✅ <strong>React ile PWA Kurulumu</strong> — create-react-app kullanarak PWA desteği ekledik.<br>✅ <strong>Manifest.json</strong> – Uygulamanın adı, simgeleri ve tema renklerini tanımladık.<br>✅ <strong>Service Worker</strong> – Önbellekleme, çevrimdışı desteği ve isteklere yanıt verme mekanizmasını oluşturduk.<br>✅ <strong>Çevrimdışı Sayfa (offline.html)</strong> – Kullanıcı internet bağlantısı olmadığında gösterilecek özel bir sayfa ekledik.<br>✅ <strong>Service Worker Kayıt ve Yönetimi</strong> – Tarayıcıya SW kaydettik ve gerektiğinde güncelleme/kaldırma işlemlerini gerçekleştirdik.<br>✅ <strong>Test ve Optimizasyon</strong> – DevTools kullanarak uygulamayı test ettik ve çevrimdışı modda nasıl çalıştığını doğruladık.</p><p>Sonuç olarak, bu rehber ile <strong>React projelerini PWA’ya dönüştürerek daha hızlı, çevrimdışı destekli ve kullanıcı dostu web uygulamaları</strong> oluşturmayı öğrendik. Bundan sonra <strong>push bildirimleri ve arka plan senkronizasyonu</strong> gibi ek özellikler ekleyerek PWA’nızı daha da geliştirebilirsiniz! 🚀</p><p>Okuduğunuz için teşekkür ederim.</p><h4>Aşağıdaki bağlantılardan bana ulaşabilirsiniz</h4><h4>e-mail: atacanerdoan@gmail.com</h4><h4>linkedin: <a href="https://www.linkedin.com/in/atacan-erdogan/">https://www.linkedin.com/in/atacan-erdogan/</a></h4><h4>Kodları incelemek için;</h4><h4>GitHub: <a href="https://github.com/datacann/Pwa-App">https://github.com/datacann/Pwa-App</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01073818f44a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Firebase ile React ve Next.js Projelerinde Veritabanı Entegrasyonu: Başlangıç Rehberi]]></title>
            <link>https://medium.com/@datacann/firebase-ile-react-ve-next-js-projelerinde-veritaban%C4%B1-entegrasyonu-ba%C5%9Flang%C4%B1%C3%A7-rehberi-e0dc5b28867c?source=rss-355ed011d32e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0dc5b28867c</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[firestore]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Atacan Erdoğan]]></dc:creator>
            <pubDate>Sun, 10 Nov 2024 20:46:25 GMT</pubDate>
            <atom:updated>2024-11-10T20:49:07.819Z</atom:updated>
            <content:encoded><![CDATA[<p>Günümüzde birçok uygulama, kullanıcı verilerini saklamak ve yönetmek için bulut tabanlı hizmetlere yöneliyor. Firebase, Google’ın sunduğu güçlü ve kolay kullanımlı bir bulut platformudur ve React, Next.js gibi modern web uygulamalarında çok yaygın bir şekilde kullanılmaktadır. Firebase, veritabanı yönetimi, kimlik doğrulama, dosya depolama ve çok daha fazlasını tek bir platformda sunarak geliştiricilerin işini kolaylaştırır.</p><p>Bu yazıda, Firebase ile React ve Next.js projelerinizde nasıl çalışacağınızı adım adım göstereceğiz. Firebase’i projenize nasıl entegre edeceğiniz, veri alıp yazma işlemleri ve en iyi uygulama örnekleri üzerine odaklanacağız.</p><h4>Firebase Nedir?</h4><p>Firebase, Google tarafından sunulan bir platform olup, geliştiricilerin mobil ve web uygulamaları için veri yönetimi, kimlik doğrulama, depolama ve daha fazlasını kolayca yapmalarına olanak tanır. Firebase’in sunduğu hizmetlerden en önemlileri şunlardır:</p><ul><li><strong>Firebase Realtime Database</strong> veya <strong>Cloud Firestore</strong> (veri saklama)</li><li><strong>Firebase Authentication</strong> (kullanıcı kimlik doğrulama)</li><li><strong>Firebase Hosting</strong> (uygulama barındırma)</li><li><strong>Firebase Storage</strong> (dosya depolama)</li></ul><h4>Firebase Projesi Oluşturma ve Yapılandırma</h4><p>Firebase kullanmaya başlamak için ilk adım, Firebase Console üzerinden bir proje oluşturmak ve gerekli yapılandırma dosyalarını almak olacaktır. Bu işlem, Firebase’in sağladığı API’lere ve hizmetlere erişimi sağlayacak temel yapı taşlarını hazırlar. Aşağıda, bu işlemi adım adım nasıl yapabileceğinizi anlatacağım.</p><h4>Firebase Console’a Giriş Yapın</h4><p>Firebase kullanmaya başlamak için ilk önce Firebase Console adresine gitmeniz gerekiyor. Firebase Console, Firebase platformundaki tüm projelerinizin yönetildiği web arayüzüdür.</p><ol><li>Firebase Console’a gidin.</li><li>Eğer bir Google hesabınız varsa giriş yapın. Eğer yoksa, bir Google hesabı oluşturmanız gerekecek.</li></ol><h4>Yeni Bir Firebase Projesi Oluşturun</h4><p>Firebase Console’a giriş yaptıktan sonra yeni bir proje oluşturmak için şu adımları izleyin:</p><ol><li><strong>Yeni Proje Başlatın</strong>: Firebase Console ekranının sol üst köşesinde yer alan “Add project” (Proje ekle) butonuna tıklayın.</li><li><strong>Proje Adı</strong>: Projeniz için anlamlı bir isim seçin. Bu isim, Firebase platformunda projeyi tanıyabilmeniz için kullanılacaktır.</li><li><strong>Google Analytics’i Etkinleştirme (İsteğe Bağlı)</strong>: Google Analytics, projenizin kullanım verilerini toplamanıza olanak tanır. Bu adımı isterseniz etkinleştirebilirsiniz, ancak başlangıçta bunu atlayabilirsiniz.</li><li><strong>Proje Oluşturma</strong>: Tüm seçenekleri gözden geçirdikten sonra, “Create project” (Proje oluştur) butonuna tıklayın.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*rCUOrqJv3lc0_98oZSO3Ew.png" /><figcaption>Yeni proje yaratalım</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*QJHRaDdmkd9dn6Q5Qep4sg.png" /><figcaption>Proje adını girelim</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*w2mChzA0WRFhodysUCbaIw.png" /><figcaption>Google analytics kullanıp kullanmayacağımızı seçelim</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*2UGWO1PgQRouHTUgv6u8pA.png" /><figcaption>Account seçilip proje yaratalım</figcaption></figure><p>Bu adamdan sonra Firebase, projenizi oluşturacak ve birkaç saniye içinde Firebase Console’da yeni projeniz görünecektir.</p><p>Firebase’de bu işlemleri yaptıktan sonra projemize dönüp entegrasyon işlemlerimizi yapalım</p><h4>Firestore’da Veri Ekleme</h4><p>Firestore, veriyi belge şeklinde sakladığından, her belgeye veri eklemek için bir koleksiyon ve belge id’si belirtmeniz gerekecek. Firebase SDK ile veriyi ekleyebilirsiniz.</p><h4>Firestore Üzerinden Veri Ekleme</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BDwvAl4ATyL4SOKhveYNmg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*P2Oc6XCb1UvG1MBUDb3Zpg.png" /></figure><p>Start collection ile collection adımızı verip next e tıklayalım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*a-LjHbUH0pkAZS-5coeKUA.png" /></figure><p>Bu pencereden istediğimiz document ID değerini verebilir veya auto ile kendisinin bir id değeri vermesini sağlayabilirsiniz. Field, type ve value değerlerini verip bu değerleri projemize entegre edebiliriz ( Yazının devamında projenizde bu verileri nasıl çekebileceğiniz açıklanıyor ).</p><p><strong>Firebase SDK’yı Kullanarak Firestore’a Veri Eklemek</strong></p><p>Firestore’a veri eklemek için, projenizde önceden oluşturduğumuz firebase.js dosyasını kullanarak Firestore servislerini içe aktarabilirsiniz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*k1588jjqwdZs1FKoZJxxjA.png" /><figcaption>Firebase görüntüsü</figcaption></figure><p>Öncelikler firebase’de sol taraftaki console dan project settings’e gidelim. Your apps kısmında projeniz için gerekli bilgilere ulaşabilirsiniz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*K7BFW2CDdeZXwDs8JVi64g.png" /></figure><p>npm install firebase konutunu çalıştırdıktan sonra firebase tarafından aldığımız bilgileri direkt firebase.js dosyasında kullanabilirsiniz.</p><h4>Firestore Yapısı</h4><p>Firestore, verileri koleksiyonlar ve belgeler (documents) içinde saklar. Veritabanı yapınızın nasıl olacağına karar verirken, uygulamanızın gereksinimlerine göre koleksiyonlar ve belgeler oluşturabilirsiniz.</p><ul><li><strong>Koleksiyonlar (Collections)</strong>: Veritabanındaki bir grup benzer veriyi temsil eder. Örneğin, kullanıcılar için bir koleksiyon oluşturabilirsiniz.</li><li><strong>Belgeler (Documents)</strong>: Koleksiyonlar içindeki veriler, belgeler şeklinde saklanır. Her belge, bir idye sahip olup, içindeki alanlar (fields) ile veri tutar.</li></ul><h4>Firestore’da Veri Ekleme</h4><p>Firestore, veriyi belge şeklinde sakladığından, her belgeye veri eklemek için bir koleksiyon ve belge id’si belirtmeniz gerekecek. Firebase SDK ile veriyi ekleyebilirsiniz.</p><h4>Veri Ekleme</h4><p>React ve Next bileşeninizde, Firestore’a veri eklemek için aşağıdaki gibi bir fonksiyon oluşturabilirsiniz:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*Yb70zKbfYqQ5Uw1d1tSbgQ.png" /></figure><p>React veya Next bileşeni render edildiğinde Firestore veritabanına yeni bir kullanıcı belgesi (document) ekleyen bir useEffect hook&#39;umuz var.</p><p>Bu işlem kullanıcının ekrana girdiği değerleri firebase e yazdırarak da bir yapı kurulabilir.</p><p><strong>useEffect Hook</strong>:</p><ul><li>useEffect, React veya Next bileşenleri render edildiğinde veya belirli durumlar (dependencies) değiştiğinde yan etkiler (side effects) oluşturmak için kullanılan bir hook&#39;tur.</li><li>useEffect içindeki boş bağımlılık dizisi [] sayesinde, bu yan etki yalnızca bileşen ilk kez render edildiğinde (component mount) çalışacaktır. Yani, bileşen yeniden render edilse bile addUser yalnızca bir kez çağrılır.</li></ul><p><strong>addUser Fonksiyonu</strong>:</p><ul><li>addUser, async olarak tanımlanmış bir fonksiyondur ve Firestore&#39;a veri eklemek için asenkron bir işlem gerçekleştirir.</li><li>Bu fonksiyon, Firestore’daki &quot;users&quot; adlı koleksiyona yeni bir belge (document) ekler.</li></ul><p><strong>addDoc İşlevi</strong>:</p><ul><li>addDoc, Firestore&#39;da belirtilen koleksiyona yeni bir belge eklemek için kullanılan Firebase fonksiyonudur.</li><li>collection(db, &quot;users&quot;) ifadesi, veriyi &quot;users&quot; koleksiyonuna eklemek için bir referans oluşturur.</li><li>Bu referansla addDoc, &quot;users&quot; koleksiyonuna bir belge ekler ve bu belgeye şu alanları (fields) içerir:</li><li>name: &quot;John&quot;</li><li>lastName: &quot;Doe&quot;</li><li>email: &quot;john.doe@example.com&quot;</li></ul><p><strong>Document ID</strong>:</p><ul><li>addDoc işlemi başarılı olduğunda, Firestore otomatik olarak bu belgeye benzersiz bir id verir.</li><li>docRef.id ifadesi ile bu benzersiz belge kimliği konsola yazdırılır.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*npGn1mSvoQrsC0ia9f1yIg.png" /><figcaption>Firebase’deki çıktı bu şekilde oluşur</figcaption></figure><h4>Firestore’dan Veri Okuma</h4><p>Firestore’daki verilere erişmek için getDocs fonksiyonunu kullanabilirsiniz. Bu, koleksiyon içerisindeki tüm belgeleri çeker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*p5yhKzno9m5HSkWOtbLIlQ.png" /></figure><p><strong>Koleksiyon Referansı ve </strong><strong>getDocs İşlevi</strong>:</p><ul><li>getDocs işlevi, collection(db, &quot;users&quot;) ile Firestore’daki &quot;users&quot; adlı koleksiyondan tüm verileri çeker.</li><li>Bu çağrı, querySnapshot adında bir nesne döndürür; bu nesne koleksiyondaki belgelerin bir listesini içerir.</li></ul><p><strong>usersList Dizisine Verilerin Eklenmesi</strong>:</p><ul><li>querySnapshot.docs.map((doc) =&gt; doc.data()) ifadesi, her belge için yalnızca veri içeriğini (data) alır ve bu içerikleri usersList adlı bir diziye ekler.</li><li>Böylece usersList, &quot;users&quot; koleksiyonundaki tüm belgelerin bir listesini içerir.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*oVwWKNbIW2MUBRk7AUZsGg.png" /><figcaption>Firebase’den çekilen listenin konsol görünümü</figcaption></figure><h3>Özet</h3><p>Bu yazıda, Firebase’in Firestore veritabanını Next.js projemize entegre ederek nasıl veri ekleyebileceğimizi ve okuyabileceğimizi adım adım ele aldık. İlk olarak Firebase projesinin nasıl oluşturulacağı, yapılandırılacağı ve ardından Firestore veritabanının nasıl etkinleştirileceği anlatıldı. Projemize Firebase’i ekledikten sonra, bir addUser fonksiyonu ile veritabanına yeni bir belge eklemeyi ve getUsers fonksiyonuyla bu verileri çekip görüntülemeyi öğrendik. Bu rehber, Firebase ile çalışan projelerde temel veri yönetimi işlemlerini kurmak için sağlam bir başlangıç sağlar.</p><p>Okuduğunuz için teşekkür ederim.</p><h4>Aşağıdaki bağlantılardan bana ulaşabilirsiniz</h4><h4>mail: atacanerdoan@gmail.com</h4><h4>linkedin: <a href="https://www.linkedin.com/in/atacan-erdogan/">https://www.linkedin.com/in/atacan-erdogan/</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0dc5b28867c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lazy Loading ve Sonsuz Kaydırma: Intersection Observer ile Nasıl Yapılır?]]></title>
            <link>https://medium.com/@datacann/lazy-loading-ve-sonsuz-kayd%C4%B1rma-intersection-observer-ile-nas%C4%B1l-yap%C4%B1l%C4%B1r-8be20564453c?source=rss-355ed011d32e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8be20564453c</guid>
            <category><![CDATA[lazy-loading]]></category>
            <category><![CDATA[infinite-scroll]]></category>
            <category><![CDATA[intersection-observer-api]]></category>
            <dc:creator><![CDATA[Atacan Erdoğan]]></dc:creator>
            <pubDate>Tue, 29 Oct 2024 16:33:42 GMT</pubDate>
            <atom:updated>2024-10-29T17:05:06.791Z</atom:updated>
            <content:encoded><![CDATA[<p>Modern web geliştirme sürecinde performans optimizasyonu, kullanıcı deneyimi kadar önemli hale geldi. Günümüz kullanıcıları hızlı, verimli ve akıcı bir web deneyimi bekliyor. Bir sayfa yavaş yükleniyorsa veya çok fazla kaynağa ihtiyaç duyuyorsa, kullanıcılar alternatif sitelere yönelebiliyor. İşte tam bu noktada, web geliştirmede yükleme stratejileri öne çıkıyor: <strong>Lazy Loading</strong> (Tembel Yükleme) ve <strong>Sonsuz Kaydırma</strong> gibi teknikler, kullanıcıya içerikleri gereksiz yere yüklemeyerek hızlı bir deneyim sunmakta oldukça etkili. Bu yazıda, bu stratejileri <strong>Intersection Observer API</strong> kullanarak nasıl gerçekleştirebileceğinizi öğreneceksiniz.</p><h4>Intersection Observer Nedir?</h4><p>Intersection Observer API, bir öğenin viewport (ekran görünümü) içinde olup olmadığını izlemeye yarayan bir JavaScript API’sidir. Bu sayede, sayfanın farklı kısımlarını scroll ettiğinizde hangi öğelerin ekranda görünür olduğunu veya hangi öğelerin görünmez hale geldiğini takip edebilirsiniz. Intersection Observer, scroll eventleri yerine daha performans dostu bir çözüm sunar, çünkü gereksiz DOM manipülasyonlarını azaltır ve performansı artırır.</p><h4>Intersection Observer Kullanmanın Avantajları</h4><ol><li><strong>Performans Artışı:</strong> Tüm öğeleri bir seferde yüklemek yerine, yalnızca kullanıcıya görünür olanları yüklersiniz.</li><li><strong>Gereksiz İşlemden Kaçınma:</strong> Scroll eventleri yerine gözlemci olarak çalışan Intersection Observer, performansı düşürmeden içerik yükler.</li><li><strong>Basit ve Esnek Yapı:</strong> Tek bir API ile farklı yükleme ihtiyaçlarına göre kullanılabilir.</li></ol><h4>Lazy Loading Nasıl Yapılır?</h4><p>Lazy Loading, sayfadaki içeriklerin (örneğin resimlerin veya videoların) yalnızca ekranda göründüğünde yüklenmesi anlamına gelir. Bu, özellikle büyük boyutlu medya dosyaları olan sayfalarda sayfa yüklenme süresini hızlandırır ve tarayıcı kaynak kullanımını azaltır.</p><h4>Örnek: Resim Lazy Loading</h4><p><strong>1.Adım</strong></p><p>İlk olarak, resimleri data-src özelliği ile işaretleyelim:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/469/1*FeZX-l-34XB3RdfCKQxl8g.png" /></figure><p><strong>2.Adım</strong></p><p>Intersection Observer ile görünüme giren resimlerin data-src değerini src değerine atayan bir işlev yazalım:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*-CaD_h1Pl88IcEwKnGqjYw.png" /></figure><p>Bu kod, bir IntersectionObserver kullanarak lazy loading işlemi yapılırken gözlemleme koşullarını belirleyen options adlı bir ayar nesnesini tanımlar. options nesnesinde, IntersectionObserver&#39;ın hangi durumlarda tetikleneceğini belirleyen üç ana özellik bulunur:</p><ol><li><strong>root</strong>: Gözlemlenen öğelerin görünürlüğünü belirlemek için kullanılan bir referans noktasıdır.</li></ol><ul><li>root: null ayarı, gözlem alanı olarak tarayıcının görünüm alanını (viewport) kullanmamızı sağlar.</li><li>Bu durumda, öğe ekranın görünüm alanına girdiğinde gözlemlemeye başlar.</li><li>root özelliğine özel bir HTML öğesi atanabilir, bu durumda yalnızca o öğe içinde kaydırıldığında gözlemlenecektir.</li></ul><p>2. <strong>rootMargin</strong>: root alanının sınırlarına eklenebilecek veya çıkarılabilecek boşluk miktarını belirtir.</p><ul><li>rootMargin: &#39;0px&#39; olarak ayarlanmış, yani herhangi bir ekleme veya çıkarma olmadan tam olarak gözlem alanının sınırlarında tetiklenecek.</li><li>rootMargin özelliği negatif veya pozitif bir değer alabilir. Örneğin, rootMargin: &#39;50px&#39; olarak ayarlanırsa öğenin yüklenmesi, öğe görünüm alanına 50 piksel uzakta olduğunda başlayacaktır. Bu, öğeyi kullanıcı görmeden önce yüklemeye başlamak için kullanışlı olabilir.</li></ul><p>3. <strong>threshold</strong>: Gözlemlenen öğenin ne kadarının görünür olması gerektiğini ifade eden bir orandır (0 ile 1 arasında).</p><ul><li>threshold: 0.1 ile ayarlanmış, yani öğenin en az %10&#39;u görünür olduğunda IntersectionObserver tetiklenir.</li><li>Daha yüksek bir değer (örneğin, threshold: 1) kullanılırsa öğenin tamamı görünür hale geldiğinde işlem başlar.</li><li>Bu değer, gözlemleme hassasiyetini kontrol eder; düşük bir threshold değeri daha erken, yüksek bir değer daha geç yüklenmesini sağlar.</li></ul><p>Bu ayarlarla birlikte, IntersectionObserver, kullanıcı sayfayı kaydırdığında öğeler görünüm alanına belirlenen rootMargin ve threshold koşullarına göre girdiğinde tetiklenir.</p><p>IntersectionObserver nesnesi oluşturulması ve lazy loading işleminin başlatılmasını adım adım açıklayalım:</p><h4>1. IntersectionObserver Nesnesi Oluşturma</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*d-Rnl2vWSrO-BVvPHWTK_g.png" /></figure><p>IntersectionObserver nesnesi, entries adı verilen gözlem girdileri listesi ve observer nesnesi ile birlikte bir callback fonksiyonu alır. Gözlemlediğimiz öğe veya öğeler görünüm alanına girip çıkarken bu callback fonksiyonu çalışır.</p><h4>2. Callback Fonksiyonunda Girdilerin (entries) Döngü ile İşlenmesi</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/278/1*c4Ld-mkDpUdKAzOmnDV6ew.png" /></figure><p>entries listesinde gözlemlenen öğeler (bu örnekte resimler) için bir forEach döngüsü başlatıyoruz. Her entry, gözlemlenen öğeye ait verileri içerir. Bu veriler sayesinde öğenin görünür olup olmadığını kontrol edebiliriz.</p><h4>3. Gözlemlenen Öğenin Görünürlük Kontrolü</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*WV1VZrDc0G6-tDNUnxy8RA.png" /></figure><p>entry.isIntersecting, öğenin gözlem alanında görünür olup olmadığını doğrular. Bu true olduğunda, yani öğe görünür olduğunda, resim kaynak URL’sini güncelleriz ve resmi yüklü hale getiririz.</p><h4>4. Resmin src Özelliğini Güncelleme ve loaded Sınıfını Eklemek</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*Rdty-L6P3Cu1lJjTbBuFLw.png" /></figure><ul><li>entry.target, gözlemlenen öğeyi (burada img) temsil eder.</li><li>img.src = img.getAttribute(&#39;data-src&#39;); ile, data-src’de bulunan gerçek resim URL&#39;sini src özelliğine kopyalarız. Böylece resim yalnızca gerektiğinde yüklenir.</li><li>img.classList.add(&quot;loaded&quot;);, resim yüklendiğinde, loaded sınıfını ekler. Bu sınıfı CSS’te tanımlayarak stil veya geçiş efekti ekleyebiliriz (örneğin, opacity değişimi ile smooth bir geçiş sağlanabilir).</li></ul><h4>5. Gözlemlemeyi Bırakmak</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*owcPtTWwUuPB8ISBtT6fKw.png" /></figure><p>Bir kez yüklendikten sonra resmi tekrar gözlemlememize gerek olmadığı için observer.unobserve(img); ile img öğesinin gözlemden çıkarılması sağlanır. Bu, performansı optimize eder ve gereksiz gözlemleri engeller.</p><h4>6. Resmi Gözlemlemeye Başlamak</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/217/1*LhbS4QaNIPRi-A6nddkZkg.png" /></figure><p>Her bir img öğesi observer.observe(target); ile gözlemlenmeye başlar. Fonksiyonu, sayfada bulunan her bir lazy sınıfına sahip resim için çalıştırıyoruz.</p><h4>7. Sayfa Yüklendiğinde Lazy Loading İşlemini Başlatmak</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*xQsxk921Cf_CLFMH1oPvYw.png" /></figure><p>DOMContentLoaded olayını dinleyerek, sayfa yüklenir yüklenmez lazy load işlemini başlatırız.</p><ul><li>document.querySelectorAll(&#39;.lazy&#39;), .lazy sınıfına sahip tüm resimleri seçer.</li><li>forEach(img =&gt; lazyLoad(img)); ile, her bir img öğesi için lazyLoad fonksiyonunu çalıştırarak gözlem başlatılır.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*8CkABlO8YEsdzOBOQ3V6nA.png" /><figcaption><strong>Yapılan adımların genel görüntüsü</strong></figcaption></figure><h3>Sonsuz Kaydırma (Infinite Scroll) Nasıl Yapılır?</h3><p>Sonsuz kaydırma, özellikle içerik tabanlı platformlarda (sosyal medya, bloglar, alışveriş siteleri vb.) kullanıcıya yeni içerikler sunmak için yaygın olarak kullanılan bir tekniktir. Intersection Observer API ile bu işlevi oluşturmak oldukça kolaydır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/239/1*RlkUbktawvw9zDZEGgdQhQ.png" /></figure><p>HTML’de bir kapsayıcı (content) ve kaydırmanın sonunu belirleyecek bir sentinel öğesi ekleyelim.</p><p>Ardından, JavaScript ile sentinel öğesini izlemeye başlayalım:</p><h4>1. İçerik Yükleme Fonksiyonu: loadMoreContent</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*mr6US3xLZesHBU_5LsD3fQ.png" /></figure><ul><li><strong>contentDiv</strong>: Yeni içeriklerin ekleneceği div. id değeri content olan öğeyi seçiyoruz.</li><li><strong>for döngüsü</strong>: Beş tane yeni içerik öğesi eklemek için bir döngü kullanıyoruz.</li><li><strong>newContent</strong>: Yeni bir div öğesi oluşturup buna .item sınıfını ekliyoruz.</li><li><strong>textContent</strong>: Yeni div öğesinin içeriğini, Content item ve öğenin sırasına göre ayarlıyoruz.</li><li><strong>appendChild</strong>: Yeni öğeyi contentDiv içine ekleyerek sayfada görünmesini sağlıyoruz.</li></ul><h4>2. Gözlemci Oluşturma Fonksiyonu: createInfiniteScrollObserver</h4><p>Bu adımda, IntersectionObserver oluşturmak için bir fonksiyon tanımlıyoruz. Bu gözlemci, belirli bir öğenin görünüm alanına (viewport) girdiğinde loadMoreContent fonksiyonunu çağıracak.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*F5dPpwIFUryej39tzb6OAQ.png" /></figure><ul><li><strong>createInfiniteScrollObserver</strong>: Bu fonksiyon, sonsuz kaydırma gözlemcisini oluşturur ve gözlemlemesi için sentinel öğesini belirler.</li><li><strong>IntersectionObserver</strong>: entries adlı bir dizi alır ve görünür olup olmadığını takip eder.</li><li><strong>entries[0]</strong>: Gözlemlenen ilk öğedir (sentinel olarak adlandırılır).</li><li><strong>isIntersecting</strong>: Eğer true ise, gözlemlenen öğe görünüm alanına girmiştir. Bu durumda loadMoreContent çalışır.</li><li><strong>observe</strong>: document.getElementById(&#39;sentinel&#39;) öğesini gözlemlemeye başlatır.</li></ul><h4>3. Olay Dinleyici: DOMContentLoaded ile Gözlemciyi Başlatma</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*IPzYKoEm2aRzh3zdv2_2ow.png" /></figure><p>Son olarak, sayfa tamamen yüklendiğinde createInfiniteScrollObserver fonksiyonunu çalıştırmak için bir DOMContentLoaded olayı ekliyoruz. Bu, sayfa yüklenmeden önce gözlemciyi başlatmamızı önler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*hn8Jz9CYg5iufoEKkExHtA.png" /><figcaption><strong>Yapılan adımların genel görüntüsü</strong></figcaption></figure><h4>Genel Akış</h4><ol><li>Sayfa tamamen yüklendiğinde DOMContentLoaded olayı tetiklenir.</li><li>createInfiniteScrollObserver çalışır ve IntersectionObserver nesnesini oluşturur, ardından sentinel öğesini gözlemlemeye başlar.</li><li>Kullanıcı sayfanın altına kaydırdığında sentinel görünür hale gelir.</li><li>IntersectionObserver, sentinel görünür olduğunda loadMoreContent fonksiyonunu çağırarak yeni içerik ekler.</li><li>Süreç kullanıcı tekrar kaydırdıkça sonsuz bir döngü şeklinde devam eder.</li></ol><h4>Performans İpuçları</h4><ul><li><strong>rootMargin</strong> ve <strong>threshold</strong> değerlerini kullanarak yükleme eşiğini kontrol edebilirsiniz. Örneğin, içerikleri kullanıcı ekrana yaklaşmadan bir miktar önce yükleyerek sorunsuz bir kaydırma deneyimi sağlayabilirsiniz.</li><li><strong>Observer’ı Temizleyin:</strong> Sonsuz kaydırmada sonsuz sayıda öğe oluşabileceğinden, gerekmediğinde observer.unobserve() ile fazla öğeleri gözlemden çıkarın.</li></ul><h3>Sonuç</h3><p>Intersection Observer API ile Lazy Loading ve Sonsuz Kaydırma uygulamak, hem kullanıcı deneyimini iyileştirir hem de web performansını optimize eder. Büyük medya dosyaları veya yoğun içerik akışı olan sayfalarda bu tekniği kullanarak verimliliği artırabilirsiniz. Özellikle mobil cihazlarda hızın ve kaynak yönetiminin kritik olduğu günümüzde, Intersection Observer ile performansı iyileştirmek oldukça etkili bir yöntemdir.</p><p>Okuduğunuz için teşekkür ederim.</p><h4>Aşağıdaki bağlantılardan bana ulaşabilirsiniz</h4><h4>mail: atacanerdoan@gmail.com</h4><h4>linkedin: <a href="https://www.linkedin.com/in/atacan-erdogan/">https://www.linkedin.com/in/atacan-erdogan/</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8be20564453c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>