<?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 Thomas Augot on Medium]]></title>
        <description><![CDATA[Stories by Thomas Augot on Medium]]></description>
        <link>https://medium.com/@thomasaugot?source=rss-8df0d3754eb0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*bWiwSt4z7q2PJanaagZGOg.png</url>
            <title>Stories by Thomas Augot on Medium</title>
            <link>https://medium.com/@thomasaugot?source=rss-8df0d3754eb0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 17:28:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thomasaugot/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[I Built a Lead-Qualifying Chatbot in Next.js]]></title>
            <link>https://medium.com/@thomasaugot/i-built-a-lead-qualifying-chatbot-in-next-js-559d7404977a?source=rss-8df0d3754eb0------2</link>
            <guid isPermaLink="false">https://medium.com/p/559d7404977a</guid>
            <category><![CDATA[gemini]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[ai-chatbot]]></category>
            <dc:creator><![CDATA[Thomas Augot]]></dc:creator>
            <pubDate>Tue, 16 Jun 2026 17:29:34 GMT</pubDate>
            <atom:updated>2026-06-16T17:33:12.816Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>I Built a Lead-Qualifying Chatbot in Next.js With the Gemini API and No Chatbot SDK. Here’s What Actually Mattered</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X_Ift68pTXAsJirxFQPc6A.png" /></figure><p>I almost reached for a chatbot SDK. There are a dozen of them now, all promising a drop-in widget with a config object and a webhook. I had a client who wanted a chat assistant on their Next.js site that could answer questions about the business and quietly figure out whether the person on the other end was a real lead worth following up with. The fast move was to wire up a hosted service and move on.</p><p>I didn’t, and I’m glad. I stayed inside the framework I already had, Next.js, and skipped the hosted chat product entirely. The whole thing ended up being one API route, one React hook, and a carefully written system prompt. No third-party SDK, no vendor lock-in, no monthly per-conversation bill. The Gemini API does the hard part, and the rest is plumbing I fully control.</p><p>This article is about that plumbing, because the plumbing is where every tutorial waves its hands. Streaming the response is the easy 20 percent. The other 80 percent is conversation state, the first turn that Gemini secretly rejects, getting structured data out of a model that wants to chat, and keeping bots from running up your token bill. I’ll show you the parts I had to figure out the hard way.</p><h3><strong>What this covers</strong></h3><p>A streaming chat endpoint using Gemini 2.5 Flash, with the system prompt doing the conversational logic instead of a state machine in your code. How to feed conversation history back to the model correctly, including the one rule that will throw a 400 on your very first message if you miss it. How to make the model emit machine-readable output mid-conversation without breaking the chat. And the defenses you need before this touches production, because a public endpoint that calls a paid API is a target.</p><p>Everything here is from a real build that’s live. The stack is Next.js with the App Router, the official `@google/generative-ai` package, and a plain React hook for the client. No other dependencies for the chat itself.</p><h3><strong>The model does the logic, not your code</strong></h3><p>The instinct with a qualifying chatbot is to build a state machine. Ask question one, store the answer, ask question two, and so on. I started down that road and the code got ugly fast, because real people don’t answer in order. Someone types one sentence that answers four of your questions at once, and a rigid script asks the next scripted question anyway and sounds like a broken form.</p><p>So I moved the logic into the system prompt and let Gemini drive. The prompt defines phases, an intent-routing phase, a qualification phase, and a free question-and-answer phase, and the model decides when to move between them. My code does almost no conversational reasoning. It streams text and watches for one signal that qualification is done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*7IMtnPjSj_4KPlh6o9eEHw.png" /><figcaption>Capture of the chat bot live on my website <a href="https://www.helloimtom.dev/en">https://www.helloimtom.dev/</a></figcaption></figure><p>Here is the shape of the instruction block that sits on top of the knowledge base:</p><pre><br>const QUALIFY_INSTRUCTIONS = `<br>PHASE 0 — INTENT<br>Read the visitor&#39;s first message and route:<br>- If they describe building something, go to PHASE 1 and qualify it.<br>- If it&#39;s a general question, go straight to PHASE 2. Do NOT ask qualification questions.<br>- If it&#39;s ambiguous, ask ONE short clarifying question.<br><br>PHASE 1 — QUALIFICATION (adaptive)<br>Ask ONE question per message, max 2 sentences, no preamble.<br>Adapt to previous answers. Never re-ask something already answered.<br>If a rich answer covers multiple topics at once, skip ahead.<br><br>When you have covered the core topics, respond with ONLY this JSON on a single line:<br>{&quot;event&quot;:&quot;qualify_done&quot;,&quot;data&quot;:{&quot;goal&quot;:&quot;...&quot;,&quot;scope&quot;:&quot;...&quot;,&quot;timeline&quot;:&quot;...&quot;,&quot;budget&quot;:&quot;...&quot;,&quot;contact_pref&quot;:&quot;...&quot;}}<br><br>PHASE 2 — FREE QUESTIONS<br>Answer questions using your knowledge base. Max 3 sentences. No more JSON.`</pre><p>The word that earns its place there is “adaptive.” The model already knows how to hold a conversation. Fighting that with branching code throws away the one thing it’s good at. My job is to tell it what I need and to recognize when it’s done, not to micromanage every turn.</p><p>This shifts the design effort from your TypeScript to your prompt, and that’s a real trade. A vague prompt gives you a vague chatbot, and you debug it by reading transcripts, not stack traces. But the result speaks like a person instead of a survey, and that difference is the entire point of using a language model at all.</p><h3><strong>The first turn Gemini rejects</strong></h3><p>Here’s the one that cost me twenty minutes of confusion. Gemini’s chat API requires the conversation history to begin with a user turn. Not an assistant turn, a user turn. If your history starts with a model message, the request fails.</p><p>This bites you specifically because of good UX. I wanted the assistant to greet the visitor first, an opening line that appears before they type anything, so the chat never sits there empty. I render that greeting on the client with no API call at all, which also means the chat can’t error on open and costs nothing for people who never reply.</p><pre>const GREETING = &quot;Hi, I&#39;m the assistant here. How can I help?&quot;</pre><p>That greeting gets recorded in the conversation history as an assistant message, so the model has context once the user replies. Which means the history I send to Gemini starts with an assistant turn, which is exactly what it refuses.</p><p>The fix is to strip any leading model turns before sending, after building the history but before starting the chat.</p><pre>const history = messages.slice(0, -1).map((m) =&gt; ({<br>  role: m.role === &quot;assistant&quot; ? &quot;model&quot; : &quot;user&quot;,<br>  parts: [{ text: m.content }],<br>}))<br><br>// Gemini requires history to begin with a &quot;user&quot; turn. The UI seeds an opening<br>// assistant greeting locally, so strip any leading model turns before sending.<br>while (history.length &amp;&amp; history[0].role === &quot;model&quot;) history.shift()</pre><p>Note two details: Gemini uses `model` as the role name, not `assistant`, so you map it. And you slice off the last message because that one gets sent separately to `sendMessageStream`, not as history. Getting either of those wrong produces a different confusing error, so they’re worth saying out loud.</p><h3><strong>Streaming the response</strong></h3><p>The streaming itself is the part the docs cover well, so I’ll keep it short. You create the model with your system instruction, start a chat with the cleaned history, and pipe the token stream into a `ReadableStream` that the route returns as plain text.</p><pre>const genAI = new GoogleGenerativeAI(apiKey)<br>const model = genAI.getGenerativeModel({<br>  model: &quot;gemini-2.5-flash&quot;,<br>  systemInstruction: SYSTEM_INSTRUCTION,<br>})<br><br>const chat = model.startChat({ history })<br>const result = await chat.sendMessageStream(lastMessage.content)<br><br>const encoder = new TextEncoder()<br>const readable = new ReadableStream({<br>  async start(controller) {<br>    for await (const chunk of result.stream) {<br>      const text = chunk.text()<br>      if (text) controller.enqueue(encoder.encode(text))<br>    }<br>    controller.close()<br>  },<br>})<br><br>return new Response(readable, {<br>  headers: { &quot;Content-Type&quot;: &quot;text/plain; charset=utf-8&quot; },<br>})</pre><p>I stream plain text, not server-sent events or a JSON protocol. The client reads the body with a `TextDecoder` and appends chunks. For a single-turn request-response chat, the extra ceremony of SSE buys nothing, and plain text is trivial to consume on the client.</p><p>`gemini-2.5-flash` is the right tier here. It’s fast enough that the streaming feels live, cheap enough that an always-on widget doesn’t hurt, and more than smart enough to follow a structured prompt and hold a conversation. I did not need the Pro model for this, and reaching for it would have made every reply slower and pricier for no gain.</p><blockquote>To put a number on cheap, the API runs on prepaid credit. You load a balance and each call draws against it. I put in 10 euros of credit to test with, expecting to watch it drain. As of June 2026 a full conversation through this assistant, a greeting, a qualification round, and a few follow-up questions, cost me around one cent in euros per chat, which is quite cheap to me. Not one cent per message, one cent for the whole exchange. That balance is effectively bottomless for anything at contact-form volume.</blockquote><p>That economics changes how you think about abuse. The risk isn’t your hosting falling over, it’s bots quietly draining prepaid credit one cheap call at a time, which is exactly why the defenses later in this article are speed bumps rather than fortresses. You’re protecting a balance, not surviving a load test.</p><h3><strong>Getting structured data out of a conversation</strong></h3><p>This is the trick that makes the whole thing useful instead of just chatty. I need two different kinds of output from the same model in the same stream. Most of the time it produces conversational text for the human. But when qualification finishes, I need a clean object I can drop into an email and a CRM, not a paragraph I have to parse with regret.</p><p>The prompt handles this by instructing the model to emit a single line of JSON, and only JSON, when it has gathered what it needs. The client watches the accumulated stream for that JSON and pulls it out.</p><pre>function extractJson(text: string, start: number): string | null {<br>  let depth = 0<br>  for (let i = start; i &lt; text.length; i++) {<br>    if (text[i] === &quot;{&quot;) depth++<br>    else if (text[i] === &quot;}&quot;) { depth--; if (depth === 0) return text.slice(start, i + 1) }<br>  }<br>  return null<br>}<br><br>const jsonStart = accumulated.indexOf(&#39;{&quot;event&quot;:&#39;)<br>const jsonBlock = jsonStart !== -1 ? extractJson(accumulated, jsonStart) : null<br>const cleanText = jsonBlock ? accumulated.replace(jsonBlock, &quot;&quot;).trim() : accumulated.trim()</pre><p>I find the JSON by its opening marker, then walk the braces to find the matching close. A naive approach grabs everything from the first brace to the last brace in the string, which breaks the moment the model includes a brace anywhere else. Counting depth handles nested objects and stray braces correctly, and it’s a dozen lines.</p><p>The same parsing idea drives the quick-reply buttons. After each question, the model appends suggested replies on the last line in a format I defined, and the client strips them out of the displayed text.</p><pre>function parseChips(text: string): { text: string; chips: string[] } {<br>  const m = text.match(/\[\[\s*chips\s*:([^\]]*)\]\]/i)<br>  if (!m) return { text: text.trim(), chips: [] }<br>  const chips = m[1].split(&quot;|&quot;).map(s =&gt; s.trim()).filter(Boolean)<br>  const clean = text.replace(m[0], &quot;&quot;).trim()<br>  return { text: clean, chips }<br>}</pre><p>The model writes `[[chips: I have a project | Just a question | Something else]]` and the user sees three buttons. This is a small thing that changes the feel completely. People click far more than they type, and letting the model suggest the options per question, instead of hardcoding them, means the buttons stay relevant to whatever it just asked.</p><p>The honest limitation here is that you are trusting the model to follow a format. It mostly does, and when it doesn’t, the fallback is graceful, no JSON found means the text renders as a normal message, no chip markers found means no buttons. Nothing crashes. But if you needed a hard guarantee of structured output, you’d reach for the model’s function-calling or response-schema features instead of pattern matching a text stream. For a chat where the structured event is one signal among many conversational turns, parsing the stream was the lighter tool, and the failure mode is “no buttons this turn,” not a broken app.</p><p>— — — Bonus — — —</p><h3><strong>Defending a public endpoint that spends money</strong></h3><p>This is the section the tutorials skip, and it’s the one that matters most once the thing is live. You have a public route that calls a paid API. Left open, it’s an invitation, someone runs up your Gemini bill, or just floods your inbox through the contact handler.</p><p>I layered three cheap defenses, none of which need a database. First, a per-IP rate limit held in memory, active only in production so local testing stays unthrottled.</p><pre>const ipRequests = new Map&lt;string, { count: number; windowStart: number }&gt;()<br>const WINDOW_MS = 60 * 60 * 1000<br>const MAX_REQUESTS = 60<br><br>function isRateLimited(ip: string): boolean {<br>  const now = Date.now()<br>  const entry = ipRequests.get(ip)<br>  if (!entry || now - entry.windowStart &gt; WINDOW_MS) {<br>    ipRequests.set(ip, { count: 1, windowStart: now })<br>    return false<br>  }<br>  if (entry.count &gt;= MAX_REQUESTS) return true<br>  entry.count++<br>  return false<br>}</pre><p>The in-memory map resets on restart and doesn’t share state across instances, so it’s a speed bump, not a fortress. For a single-instance deployment it’s plenty. If you scale horizontally, you move this to Redis, and the interface stays the same.</p><p>Second, a honeypot. A hidden input that humans never see and never fill, but bots fill automatically because they fill every field. If it arrives with a value, the request is a bot, and I reject it before spending a single token.</p><pre>const { messages, _hp, _ts } = body<br>if (_hp) return new Response(&quot;bad_request&quot;, { status: 400 })</pre><p>Third, Cloudflare Turnstile, and this is the one with a design decision worth explaining. Turnstile is a CAPTCHA replacement that mostly runs invisibly. The tempting implementation is to block any request that fails verification. I made it fail-open instead.</p><pre>const tsSecret = process.env.TURNSTILE_SECRET_KEY<br>if (tsSecret &amp;&amp; _ts) {<br>  try {<br>    const tsRes = await fetch(&quot;https://challenges.cloudflare.com/turnstile/v0/siteverify&quot;, {<br>      method: &quot;POST&quot;,<br>      headers: { &quot;Content-Type&quot;: &quot;application/json&quot; },<br>      body: JSON.stringify({ secret: tsSecret, response: _ts }),<br>    })<br>    const tsData = await tsRes.json() as { success: boolean; &quot;error-codes&quot;?: string[] }<br>    if (!tsData.success) {<br>      console.warn(&quot;Turnstile check failed (proceeding):&quot;, tsData[&quot;error-codes&quot;])<br>    }<br>  } catch (e) {<br>    console.warn(&quot;Turnstile verify request errored (proceeding):&quot;, e)<br>  }<br>}</pre><p>Turnstile fails for reasons that have nothing to do with the user being a bot. A network that blocks Cloudflare, an aggressive ad blocker, an expired token, a transient error on Cloudflare’s side. Blocking a real person from talking to a business because their browser extension tripped a check is a worse outcome than letting through the rare bot that also clears the honeypot and the rate limit. So a failed or missing check gets logged and the request proceeds. Turnstile is one signal in the stack, not the gate.</p><p>The distinction I want to leave you with is between defenses that should hard-fail and defenses that should soft-fail. The honeypot hard-fails, because a filled honeypot is unambiguous, no real user trips it. The rate limit hard-fails, because the cap is generous enough that a real person won’t hit it. Turnstile soft-fails, because its false positives land on real users. Deciding which is which for each defense is the actual security work, and it’s more important than which library you picked.</p><h3><strong>Building the public-key part for Docker (optional — if you use Docker in your server)</strong></h3><p>One last trap, because it’s specific to deploying a Next.js app with Gemini in a container. The Turnstile site key is a `NEXT_PUBLIC_` variable, which means Next inlines it into the client bundle at build time, not runtime. If your Dockerfile builds the app without that variable present, the key is undefined in the shipped JavaScript, and the widget silently renders with nothing.</p><p>The fix is to pass public variables as build arguments, declared before the build step.</p><pre>ARG NEXT_PUBLIC_TURNSTILE_SITE_KEY<br>ENV NEXT_PUBLIC_TURNSTILE_SITE_KEY=$NEXT_PUBLIC_TURNSTILE_SITE_KEY<br><br>COPY . .<br>RUN npm run build</pre><p>Runtime environment variables, the ones you set in `docker-compose` or your platform’s dashboard, arrive too late for anything `NEXT_PUBLIC_`. The secret key, which only the server touches, is the opposite, it stays a runtime variable and never goes near the build. Mixing those two up gives you a widget that works locally and quietly does nothing in production, which is the worst kind of bug.</p><h3><strong>Another little bonus, capturing the conversations that never finish</strong></h3><p>Here’s a pattern I added late and would now build from the start. Most people who open a chat assistant leave without submitting anything. They ask a couple of questions, get their answer, and close the tab. By default you learn nothing from them, which is a waste, because the questions they asked are a free stream of insight into what visitors actually want.</p><p>So I send the transcript anyway when someone leaves mid-conversation, flagged as incomplete. The trick is doing it reliably during page unload, when a normal `fetch` gets killed the moment the browser tears the page down. The browser has an API built for exactly this, `navigator.sendBeacon`, which queues a small POST that survives the page closing.</p><pre>const flushAbandoned = useCallback(() =&gt; {<br>  if (abandonedSentRef.current || sentRef.current) return<br>  // &quot;Meaningful&quot; = at least two real user replies, skips drive-by opens.<br>  const userTurns = historyRef.current.filter(m =&gt; m.role === &quot;user&quot;).length<br>  if (userTurns &lt; 2) return<br>  abandonedSentRef.current = true<br><br>  const payload = JSON.stringify({ incomplete: true, conversation: historyRef.current })<br><br>  if (typeof navigator !== &quot;undefined&quot; &amp;&amp; navigator.sendBeacon) {<br>    navigator.sendBeacon(&quot;/api/contact&quot;, new Blob([payload], { type: &quot;application/json&quot; }))<br>  } else {<br>    fetch(&quot;/api/contact&quot;, { method: &quot;POST&quot;, body: payload, keepalive: true }).catch(() =&gt; {})<br>  }<br>}, [])</pre><p>Three guards make this behave. The `abandonedSentRef` ensures it fires at most once, because the unload events can stack and you don’t want three copies of the same transcript. The `sentRef` check skips people who already submitted properly, no point flagging a completed lead as abandoned. And the two-reply minimum filters out drive-by opens, someone who clicks the bubble and immediately leaves generated nothing worth an email.</p><p>I wire it to the events that actually fire on leave, which is the second subtle part. `beforeunload` is unreliable on mobile, so the pair that works is `pagehide` plus a `visibilitychange` handler that checks for the hidden state.</p><pre>useEffect(() =&gt; {<br>  const onHide = () =&gt; { if (document.visibilityState === &quot;hidden&quot;) flushAbandoned() }<br>  window.addEventListener(&quot;pagehide&quot;, flushAbandoned)<br>  document.addEventListener(&quot;visibilitychange&quot;, onHide)<br>  return () =&gt; {<br>    window.removeEventListener(&quot;pagehide&quot;, flushAbandoned)<br>    document.removeEventListener(&quot;visibilitychange&quot;, onHide)<br>    flushAbandoned()<br>  }<br>}, [flushAbandoned])</pre><p>The cleanup function calls `flushAbandoned` too, which covers the case where the chat component unmounts without the page unloading, a route change, or a widget being closed. The once-only guard means this extra call is free if the beacon already went out.</p><p>The endpoint on the receiving side needs the same defenses as everything else, because it’s now a second public route that can be hammered. The honeypot and rate limit I described earlier apply here unchanged. A pattern that emails you on every page unload is a pattern a bot will happily exploit if you leave it open.</p><h3><strong>Closing</strong></h3><p>The version of this I almost built, a hosted widget with a config object, would have been running in an afternoon. The version I did build took longer and taught me where the real edges are, the first-turn rule, the brace-counting parser, the fail-open security call. I own all of it, it costs me the price of Gemini tokens and nothing else, and when the client wants the assistant to behave differently, I edit a prompt instead of filing a support ticket.</p><p>That’s the case for building it yourself, not that it’s harder sicne nowadays building with AI makes it all so much easier, but that the hard parts are the parts worth understanding. The model is a commodity now. The judgment about how to wrap it is the work.</p><p><em>If you know of a better solutions, some things I can add up to my method or simply just say hi!, speak to me through my AI chatbot assistant at </em><a href="https://www.helloimtom.dev/en"><em>https://www.helloimtom.dev/</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=559d7404977a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Got My Next.js Portfolio to Score 100% on Lighthouse Accessibility]]></title>
            <link>https://medium.com/@thomasaugot/how-i-got-my-next-js-portfolio-to-score-100-on-lighthouse-accessibility-0405c3582f3a?source=rss-8df0d3754eb0------2</link>
            <guid isPermaLink="false">https://medium.com/p/0405c3582f3a</guid>
            <category><![CDATA[web-accessibility-a11y]]></category>
            <category><![CDATA[accessibility]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Thomas Augot]]></dc:creator>
            <pubDate>Sat, 28 Mar 2026 17:51:06 GMT</pubDate>
            <atom:updated>2026-03-28T17:51:06.432Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*hSh0GosEEeMPPSgXuRA20Q.png" /><figcaption><a href="https://www.helloimtom.dev/fr">https://www.helloimtom.dev/</a></figcaption></figure><p><em>A practical, honest account of everything I changed, why it matters, and how you can apply the same patterns to any animated React app.</em></p><p>I want to be upfront about something: before working on this, I thought my portfolio was accessible enough.</p><p>Until that day when I got a call for a job position requesting experience in Accessible web, and I personally had none specifically. And so I decided to really dig into it and learn the true fundamentals of it, and what’s best to learn that put it at practice.</p><p>Back to my portfolio website, It had semantic HTML in most places as we always are told we should care about it. It kind ofmostly worked with a keyboard. It looked fine in a browser. The animations were as smooth as I could manage to get them. The design was deliberate.</p><p>Then I ran an audit on Chrome’s Lighthouse.</p><p>Accessibility: <strong>74</strong>…</p><p>Not terrible. But not good. And for a site I was using to represent my work, that number felt like a contradiction. So I fixed it. Properly. All the way to 100.</p><p>This article documents everything I did, what the problems were, why they existed, and how I resolved each one. It’s written for developers who already know how to build React and/or Next.js apps but want to understand what “accessible” actually means in a custom, animated, 3D-heavy React interface and not just a static marketing page.</p><h3>What Lighthouse Is Actually Testing</h3><p>Lighthouse doesn’t test whether your site is <em>practically usable</em> by people with disabilities, that requires real user testing. What it does is audit a set of rules that are highly correlated with accessibility: correct semantics, sufficient contrast, proper ARIA usage, label associations, focus management, language declaration, and more.</p><p>Hitting 100 on Lighthouse is a strong foundation. It won’t catch everything, but it does ensure your app isn’t making obvious structural mistakes that trip up screen readers, keyboard users, or assistive technology in general.</p><p>The most important thing I learned: <strong>accessibility is not a list of fixes. It’s a way of building.</strong></p><h3>The core Problems I Had</h3><p>These are the issues that brought my score down and, more importantly, made the site genuinely hard to use for anyone who wasn’t clicking with a mouse.</p><h4>More Than One &lt;main&gt; Landmark</h4><p>My layout had a &lt;main&gt; in the root layout, and another one inside a terminal surface that rendered the active stage. Screen readers use landmarks to navigate. Two &lt;main&gt; regions is ambiguous so, the user doesn&#39;t know which one contains the primary content.</p><p><strong>Fix:</strong> One &lt;main&gt; per page, period. The terminal surface became a &lt;section&gt; instead.</p><h4>Focus Drifted When the Stage Changed</h4><p>This is the most common and most damaging accessibility bug in SPA-like interfaces.</p><p>When the user navigated from the hero section to the projects section, the visual content changed, but focus stayed on whatever triggered the navigation. Screen reader users were left talking to a ghost.</p><p><strong>Fix:</strong> A dedicated useStageFocus hook that moves focus to the new stage container once the transition completes.</p><p>Here is the code for those who want to reuse it:</p><pre>// hooks/useStageFocus.ts<br><br>import { useEffect, useRef } from &quot;react&quot;;<br><br>export function useStageFocus(activeStage: string) {<br>  const containerRef = useRef&lt;HTMLElement&gt;(null);<br><br>  useEffect(() =&gt; {<br>    const timeout = setTimeout(() =&gt; {<br>      containerRef.current?.focus({ preventScroll: true });<br>    }, 300); // wait for transition<br><br>    return () =&gt; clearTimeout(timeout);<br>  }, [activeStage]);<br><br>  return containerRef;<br>}</pre><p>Then in the terminal/stage container:</p><pre>const stageRef = useStageFocus(activeStage);<br><br>&lt;section<br>  ref={stageRef}<br>  tabIndex={-1} // makes it programmatically focusable without adding to tab order<br>  id=&quot;stage-content&quot;<br>&gt;<br>  {/* stage content */}<br>&lt;/section&gt;</pre><p>tabIndex={-1} is the key here , as it makes the element focusable via .focus() in JavaScript without inserting it into the natural Tab order. This is exactly right for focus management targets.</p><h4>Custom Terminal UI Without Semantic Structure</h4><p>The terminal surface looked great but communicated nothing to assistive technology. No headings. No regions. No labels.</p><p><strong>Fix:</strong> Each stage got a semantic wrapper and a heading, either visible (hero) or hidden with sr-only (other stages).</p><pre>const stageContentHeadingId = `stage-content-heading-${stage}`;<br><br>&lt;section aria-labelledby={stageContentHeadingId}&gt;<br>  {stage !== &quot;hero&quot; &amp;&amp; (<br>    &lt;h2 id={stageContentHeadingId} className=&quot;sr-only&quot;&gt;<br>      {stageLabel} {/* e.g. &quot;Projects&quot;, &quot;About&quot;, &quot;Contact&quot; */}<br>    &lt;/h2&gt;<br>  )}<br>  {/* content */}<br>&lt;/section&gt;</pre><p>The sr-only class hides the heading visually while keeping it in the accessibility tree:</p><pre>.sr-only {<br>  position: absolute;<br>  width: 1px;<br>  height: 1px;<br>  padding: 0;<br>  margin: -1px;<br>  overflow: hidden;<br>  clip: rect(0, 0, 0, 0);<br>  white-space: nowrap;<br>  border-width: 0;<br>}</pre><h4>Decorative Three.js Scenes and Glows in the Accessibility Tree</h4><p>Every &lt;canvas&gt;, glow wrapper, orbit ring, and decorative &lt;div&gt; was discoverable by screen readers. This polluted the tree with noise.</p><p><strong>Fix:</strong> aria-hidden=&quot;true&quot; on every decorative wrapper. alt=&quot;&quot; on every decorative image.</p><pre>{/* Three.js canvas wrapper — purely visual */}<br>&lt;div aria-hidden=&quot;true&quot; className=&quot;absolute inset-0 pointer-events-none&quot;&gt;<br>  &lt;canvas ref={canvasRef} /&gt;<br>&lt;/div&gt;<br><br>{/* Decorative image */}<br>&lt;Image src=&quot;/grain.png&quot; alt=&quot;&quot; aria-hidden=&quot;true&quot; /&gt;</pre><p>This alone can significantly clean up what a screen reader user encounters.</p><h4>Contact Form With No Real Labels</h4><p>The form had pretty (according to me, …) styled terminal-style prompts that <em>looked</em> like labels but weren’t connected to the inputs in any programmatic way. Placeholders were doing double duty.</p><p><strong>Fix:</strong> Proper &lt;label&gt; with htmlFor, id, name, required, autoComplete, inputMode, aria-invalid, aria-describedby, and role=&quot;alert&quot; on inline errors.</p><pre>&lt;label htmlFor=&quot;contact-email&quot;&gt;<br>  &lt;span className=&quot;text-primary text-xs&quot;&gt;❯ email --address&lt;/span&gt;<br>&lt;/label&gt;<br><br>&lt;input<br>  id=&quot;contact-email&quot;<br>  name=&quot;email&quot;<br>  type=&quot;email&quot;<br>  autoComplete=&quot;email&quot;<br>  inputMode=&quot;email&quot;<br>  required<br>  aria-invalid={fieldErrors.email ? &quot;true&quot; : &quot;false&quot;}<br>  aria-describedby={fieldErrors.email ? &quot;contact-email-error&quot; : undefined}<br>/&gt;<br><br>{fieldErrors.email &amp;&amp; (<br>  &lt;p id=&quot;contact-email-error&quot; role=&quot;alert&quot; className=&quot;text-xs text-red-300 mt-1&quot;&gt;<br>    {fieldErrors.email}<br>  &lt;/p&gt;<br>)}</pre><p>Two things worth calling out here:</p><p><strong>inputMode=&quot;email&quot;</strong> is separate from type=&quot;email&quot;. The type controls browser validation. The inputMode tells mobile operating systems which soft keyboard to show, the one with @ and .com visible. A small detail that matters for mobile UX.</p><p><strong>role=&quot;alert&quot;</strong> makes the error announce itself immediately to screen readers without requiring focus to move to it. Combined with aria-describedby, the field and its error are programmatically linked.</p><p>Form-level feedback (submission success/failure) uses aria-live=&quot;polite&quot; instead, so it announces without interrupting:</p><pre>&lt;div role=&quot;status&quot; aria-live=&quot;polite&quot; className=&quot;sr-only&quot;&gt;<br>  {submitMessage}<br>&lt;/div&gt;</pre><h4>Focus Rings Showing During Mouse/Touch Interaction</h4><p>Focus rings are essential for keyboard users. They’re also visually distracting for pointer users, and most design systems either kill them entirely (bad) or let them show everywhere (annoying).</p><p><strong>Fix:</strong> Track input modality on the &lt;html&gt; element and conditionally style focus rings.</p><pre>// In a top-level client component<br><br>useEffect(() =&gt; {<br>  const onKeyDown = () =&gt;<br>    document.documentElement.setAttribute(&quot;data-input-modality&quot;, &quot;keyboard&quot;);<br>  const onPointerDown = () =&gt;<br>    document.documentElement.setAttribute(&quot;data-input-modality&quot;, &quot;pointer&quot;);<br><br>  window.addEventListener(&quot;keydown&quot;, onKeyDown);<br>  window.addEventListener(&quot;pointerdown&quot;, onPointerDown);<br><br>  return () =&gt; {<br>    window.removeEventListener(&quot;keydown&quot;, onKeyDown);<br>    window.removeEventListener(&quot;pointerdown&quot;, onPointerDown);<br>  };<br>}, []);</pre><pre>/* globals.css */<br><br>.keyboard-focus-ring:focus {<br>  outline: none;<br>}<br><br>[data-input-modality=&quot;keyboard&quot;] .keyboard-focus-ring:focus {<br>  outline: 2px solid var(--color-primary);<br>  outline-offset: 3px;<br>  border-radius: 3px;<br>}</pre><p>Every interactive element gets className=&quot;keyboard-focus-ring&quot;. This means keyboard users always see where they are. Pointer users never see a ring appear on click. Both groups get the experience they expect.</p><h4>Icon-Only Buttons With No Accessible Name</h4><p>My theme toggle, motion toggle, back-to-top button, and mobile nav arrows all had icons but no text. Screen readers announced them as &quot;button&quot;completely useless sinc eit doesn’t tell what this button does, only what it is.</p><p><strong>Fix:</strong> aria-label on every icon-only control. aria-hidden=&quot;true&quot; on the icon inside. aria-pressed on toggles.</p><pre>{/* Theme toggle */}<br>&lt;button<br>  type=&quot;button&quot;<br>  onClick={toggleTheme}<br>  aria-pressed={isDark}<br>  aria-label={isDark ? &quot;Switch to light mode&quot; : &quot;Switch to dark mode&quot;}<br>  className=&quot;keyboard-focus-ring&quot;<br>&gt;<br>  &lt;Sun aria-hidden=&quot;true&quot; size={15} /&gt;<br>&lt;/button&gt;<br><br>{/* Mobile nav */}<br>&lt;button<br>  onClick={goToNext}<br>  disabled={!canGoDown || isMorphing}<br>  aria-label=&quot;Next section&quot;<br>  className=&quot;keyboard-focus-ring&quot;<br>&gt;<br>  &lt;svg aria-hidden=&quot;true&quot;&gt;...&lt;/svg&gt;<br>&lt;/button&gt;</pre><p>The aria-label is dynamic — it always describes <em>what will happen</em>, not the current state. &quot;Switch to light mode&quot; tells the user the action. aria-pressed={isDark} tells them the current state. Together, they give a complete picture.</p><p>disabled is also doing accessibility work here: it prevents activation during transitions and is announced as unavailable by screen readers.</p><h4>Mobile Menu Interaction Bugs</h4><p>The mobile menu opened visually but became non-interactive in certain states because inert was applied to the wrong subtree. There was also a z-index issue where the fixed top nav intercepted taps on the close button area.</p><p><strong>Fix:</strong> The menu is now treated as a dialog-like surface with full semantics:</p><pre>&lt;div<br>  role=&quot;dialog&quot;<br>  aria-modal=&quot;true&quot;<br>  aria-label=&quot;Navigation menu&quot;<br>  id=&quot;mobile-menu&quot;<br>&gt;<br>  {/* menu content */}<br>&lt;/div&gt;<br><br>&lt;button<br>  aria-expanded={isMenuOpen}<br>  aria-controls=&quot;mobile-menu&quot;<br>  aria-label={isMenuOpen ? &quot;Close menu&quot; : &quot;Open menu&quot;}<br>  className=&quot;keyboard-focus-ring&quot;<br>&gt;<br>  {/* icon */}<br>&lt;/button&gt;</pre><p>When the menu opens: focus moves inside. When it closes: focus returns to the toggle. Body scroll is locked. The top nav gets pointer-events-none so it doesn&#39;t intercept the close button.</p><h4>Portfolio Hidden Panels Still Accessible</h4><p>The project panels used CSS to hide inactive slides, but they remained in the tab order and the accessibility tree. A keyboard user could Tab into an invisible panel.</p><p><strong>Fix:</strong> Inactive panels get aria-hidden=&quot;true&quot; and inert. Active panel has neither.</p><pre>&lt;div<br>  aria-hidden={!isActive}<br>  inert={!isActive ? &quot;&quot; : undefined}<br>  className={`panel ${isActive ? &quot;active&quot; : &quot;&quot;}`}<br>&gt;<br>  {/* project content */}<br>&lt;/div&gt;</pre><p>The inert attribute is now well-supported and is the cleanest way to completely remove a subtree from both the accessibility tree and keyboard interaction simultaneously.</p><h4>No lang Attribute on &lt;html&gt;</h4><p>This is a WCAG Level A requirement. Without it, screen readers use their default language engine, which may mispronounce content in French or Spanish.</p><p>In app/[locale]/layout.tsxor the root layout depending on your projec architecture:</p><pre>export default function LocaleLayout({<br>  children,<br>  params,<br>}: {<br>  children: React.ReactNode;<br>  params: { locale: string };<br>}) {<br>  return (<br>    &lt;html lang={params.locale}&gt;<br>      &lt;body&gt;{children}&lt;/body&gt;<br>    &lt;/html&gt;<br>  );<br>}</pre><p>One line. WCAG 3.1.1. Always set it.</p><h3>The Skip Link</h3><p>Keyboard users need a way to bypass repeated navigation and jump directly to the main content. This is what a skip link does.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*802R5TC-EVkuH-g5FY89qg.png" /></figure><pre>// components/ui/SkipLink.tsx<br>&quot;use client&quot;;<br><br>export function SkipLink({ targetId }: { targetId: string }) {<br>  const handleClick = (e: React.MouseEvent&lt;HTMLAnchorElement&gt;) =&gt; {<br>    e.preventDefault();<br>    const target = document.getElementById(targetId);<br>    if (target) {<br>      target.focus({ preventScroll: true });<br>      target.scrollIntoView({ behavior: &quot;smooth&quot;, block: &quot;start&quot; });<br>    }<br>  };<br><br>  return (<br>    &lt;a<br>      href={`#${targetId}`}<br>      onClick={handleClick}<br>      className=&quot;<br>        sr-only focus:not-sr-only<br>        fixed top-4 left-4 z-[9999]<br>        px-4 py-2 rounded<br>        bg-background text-foreground<br>        border border-primary<br>        text-sm font-medium<br>        keyboard-focus-ring<br>      &quot;<br>    &gt;<br>      Skip to content<br>    &lt;/a&gt;<br>  );<br>}</pre><p>The key detail: it prevents default so it doesn’t write #stage-content into the URL bar. It focuses programmatically instead. Same behavior, cleaner URL.</p><p>Used in app/[locale]/layout.tsx:</p><pre>&lt;SkipLink targetId=&quot;stage-content&quot; /&gt;<br>&lt;Navbar /&gt;<br>&lt;main id=&quot;main-content&quot;&gt;<br>  &lt;section id=&quot;stage-content&quot; tabIndex={-1}&gt;<br>    {children}<br>  &lt;/section&gt;<br>&lt;/main&gt;</pre><h3>Reduced Motion: A Full System, Not a Media Query</h3><p>My app has typing animations, cursor blinking, terminal morphs, 3D floating scenes, and panel transitions. Without a motion preference system, this is genuinely rough for people with vestibular sensitivities.</p><p>The system has three layers:</p><ol><li><strong>System preference: </strong>prefers-reduced-motion is respected by default.</li><li><strong>App override: </strong>a visible toggle lets users flip the preference without going to OS settings.</li><li><strong>Persistent choice: </strong>stored in localStorage so the preference survives page reloads.</li></ol><p>In short, I make heavy animations and transitions optional, more or less.</p><pre>// contexts/MotionPreferenceContext.tsx<br>&quot;use client&quot;;<br><br>import { createContext, useContext, useEffect, useState } from &quot;react&quot;;<br><br>type MotionPreference = &quot;full&quot; | &quot;reduced&quot;;<br><br>const MotionPreferenceContext = createContext&lt;{<br>  preference: MotionPreference;<br>  toggle: () =&gt; void;<br>}&gt;({<br>  preference: &quot;full&quot;,<br>  toggle: () =&gt; {},<br>});<br><br>export function MotionPreferenceProvider({<br>  children,<br>}: {<br>  children: React.ReactNode;<br>}) {<br>  const [preference, setPreference] = useState&lt;MotionPreference&gt;(&quot;full&quot;);<br><br>  useEffect(() =&gt; {<br>    const stored = localStorage.getItem(&quot;motion-preference&quot;);<br>    if (stored === &quot;reduced&quot; || stored === &quot;full&quot;) {<br>      setPreference(stored);<br>    } else {<br>      const systemReduced = window.matchMedia(<br>        &quot;(prefers-reduced-motion: reduce)&quot;<br>      ).matches;<br>      setPreference(systemReduced ? &quot;reduced&quot; : &quot;full&quot;);<br>    }<br>  }, []);<br><br>  const toggle = () =&gt; {<br>    setPreference((prev) =&gt; {<br>      const next = prev === &quot;full&quot; ? &quot;reduced&quot; : &quot;full&quot;;<br>      localStorage.setItem(&quot;motion-preference&quot;, next);<br>      return next;<br>    });<br>  };<br><br>  return (<br>    &lt;MotionPreferenceContext.Provider value={{ preference, toggle }}&gt;<br>      {children}<br>    &lt;/MotionPreferenceContext.Provider&gt;<br>  );<br>}<br><br>export const useMotionPreference = () =&gt; useContext(MotionPreferenceContext);</pre><p>In animation code:</p><pre>const { preference } = useMotionPreference();<br>const isReduced = preference === &quot;reduced&quot;;<br><br>gsap.to(element, {<br>  duration: isReduced ? 0 : 0.6,<br>  y: isReduced ? 0 : -20,<br>  opacity: 1,<br>});</pre><p>Reduced mode is not “kill all motion.” It’s a calmer language: shorter durations, more fades instead of spatial movement, instant typing, static 3D. beacuse the idea wasn’t to kill the polish transitions style I wanted to convey but rather to soften things.</p><h3>Touch Targets: 44px Minimum</h3><p>WCAG 2.5.5 (and Apple’s Human Interface Guidelines) both set 44px as the minimum touch target size. A nav button that looks large can still have a smaller actual interactive area.</p><pre>@media (max-width: 767px) {<br>  nav button,<br>  nav a,<br>  form button {<br>    min-height: 44px;<br>    min-width: 44px;<br>  }<br>}</pre><p>Also worth adding for mobile swipe navigation:</p><pre>body {<br>  overscroll-behavior: none; /* prevents iOS rubber-band interfering with swipe */<br>}<br><br>.terminal-surface {<br>  user-select: none; /* prevents accidental text selection during swipe */<br>}<br><br>.terminal-surface input,<br>.terminal-surface textarea {<br>  user-select: text; /* re-enable for form fields */<br>}</pre><h3>aria-current on Navigation</h3><p>This one is simple but often missed. Desktop nav items should expose which section is active:</p><pre>&lt;a<br>  href={`/${locale}/${stagePath}`}<br>  aria-current={isActive ? &quot;page&quot; : undefined}<br>  className=&quot;keyboard-focus-ring&quot;<br>&gt;<br>  {label}<br>&lt;/a&gt;</pre><p>Screen readers announce &quot;Projects, current page&quot; instead of just &quot;Projects&quot;. One attribute, big difference.</p><h3>A Practical Testing Checklist</h3><p>Run this before shipping any significant UI change.</p><h4>Keyboard</h4><ul><li>Can the entire flow be completed with keyboard alone?</li><li>Is Tab order logical top-to-bottom, left-to-right?</li><li>Is focus always visible when in keyboard mode?</li><li>Does focus <em>not</em> appear during pointer interaction?</li><li>After stage/panel changes, does focus land in the new section?</li></ul><h4>Screen Reader &amp; Semantics</h4><ul><li>Exactly one &lt;main&gt; per page?</li><li>Every major section has a heading or aria-label?</li><li>Decorative layers are aria-hidden=&quot;true&quot;?</li><li>Icon-only buttons have aria-label?</li><li>Toggle buttons use aria-pressed?</li><li>&lt;html lang&gt; is set to the correct locale?</li><li>Skip link present and functional?</li></ul><h4>Forms</h4><ul><li>Every field has a &lt;label&gt; with htmlFor?</li><li>id and name present on all inputs?</li><li>Required fields marked with required?</li><li>Error messages linked via aria-describedby?</li><li>Submit feedback exposed via aria-live?</li></ul><h4>Motion</h4><ul><li>System prefers-reduced-motion is respected?</li><li>User override toggle works and persists?</li><li>Reduced mode still communicates transitions clearly?</li><li>Looping decorative animations are removed or frozen in reduced mode?</li></ul><h4>Mobile</h4><ul><li>Touch targets ≥ 44px on mobile?</li><li>Swipe navigation doesn’t cause accidental text selection?</li><li>Mobile menu opens, closes, and handles focus correctly?</li><li>Position indicators are aria-hidden=&quot;true&quot;?</li></ul><h4>Hidden Panels / Portfolio</h4><ul><li>Hidden panels are aria-hidden=&quot;true&quot; and inert?</li><li>Active panel gets focus after navigation?</li><li>CTA zones are pinned structurally, not relying on accidental spacing?</li></ul><h3>What I’d Tell My Past Self</h3><p>Accessibility is not an audit you run at the end. It’s not a checklist you tick once. It’s a set of building habits that, once internalized, cost almost nothing extra per component.</p><p>The patterns I used: useStageFocus, modality tracking, aria-hidden on decorative layers, real labels on form fields, aria-pressed on toggles, … none of them are complicated. Most take five minutes to implement correctly, especially with AI. They just require <em>knowing</em> they exist and above all that they&#39;re needed hy more than we may think.</p><p>The bigger mindset shift is this: every time you build a new interactive element, the first question isn’t “how does this look?” It’s “what is this, can it be focused, is it decorative, and if its state changes , who knows about it?”</p><p>If you can answer those four questions for every UI element you build, you’ll stay at 100.</p><h3>Resources you can also check:</h3><ul><li><a href="https://www.w3.org/WAI/WCAG22/quickref/">WCAG 2.2 Quick Reference</a></li><li><a href="https://webaim.org/resources/contrastchecker/">WebAIM Contrast Checker</a></li><li><a href="https://www.deque.com/axe/devtools/">axe DevTools Chrome Extension</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles">MDN: ARIA Authoring Practices</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/inert">The </a><a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/inert">inert attribute — MDN</a></li></ul><p>And of course my previous articles:</p><ul><li><a href="https://medium.com/@thomasaugot/how-to-keep-rich-animations-snappy-in-next-js-15-46d90f503b15">How to Keep Rich Animations Snappy in Next.js 15</a></li><li><a href="https://medium.com/@thomasaugot/optimizing-gsap-animations-in-next-js-15-best-practices-for-initialization-and-cleanup-2ebaba7d0232">Optimizing GSAP Animations in Next.js 15</a></li><li><a href="https://medium.com/@thomasaugot/how-to-set-up-google-analytics-with-google-tag-manager-in-next-js-15-in-2025-dedfcaee875a">Google Analytics with GTM in Next.js 15</a></li></ul><p><em>If this saved you time or helped you think about accessibility differently, feel free to leave a comment or share it with someone who’s building something custom. The more we normalize accessible-by-default thinking in the frontend community, the better :)</em></p><p>And please, visit my portfolio website <a href="https://www.helloimtom.dev/en">https://www.helloimtom.dev/</a> and share with me your feedback!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0405c3582f3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Keep Rich Animations Snappy in Next.js 15]]></title>
            <link>https://medium.com/@thomasaugot/how-to-keep-rich-animations-snappy-in-next-js-15-46d90f503b15?source=rss-8df0d3754eb0------2</link>
            <guid isPermaLink="false">https://medium.com/p/46d90f503b15</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[gsap]]></category>
            <dc:creator><![CDATA[Thomas Augot]]></dc:creator>
            <pubDate>Mon, 26 Jan 2026 12:48:56 GMT</pubDate>
            <atom:updated>2026-01-26T12:48:56.354Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hb-fUaNfRVfkUXPx-5RAZw.png" /></figure><p>It’s been a few years now that I’ve been working with Next.js, and I have to say: out of all the animation libraries in the ecosystem, GSAP is by far my favorite.</p><p>Yes, some of its concepts can feel tough to manage at first. Yes, the library is heavy. But when used well, it brings that extra touch everyone expects from a modern website.</p><p>Animations make a page feel alive , but they also come with a cost. If you’re not careful, they can slow down the browser before the first meaningful paint even happens.</p><p>Next.js 15 gives us powerful tools like streaming, selective hydration, and modern bundling that allow rich motion and fast load times to coexist. But that only works if your animation workflow respects how the browser actually renders a page.</p><p>I learned this the hard way.</p><p>Like many devs, I got excited. I added GSAP everywhere. Animations on every section, every page, every scroll. It felt amazing… until I noticed that my initial load time was almost always slower, and bugs started popping up, a looot of bugs.</p><p>So here’s what I’ve learned over time — through research, experimentation, and real production mistakes.</p><p>Let’s start with <strong>how Next.js actually loads a page</strong>, because that’s where most animation problems begin.</p><h3>The Browser Gets Something to Draw First</h3><p>When a visitor hits your page, Next.js doesn’t wait for all JavaScript to load before doing anything. Instead, it streams HTML to the browser as soon as it’s ready.</p><p>That means the browser can start drawing the layout: the hero, the header, the menu without waiting for animations, event handlers, or heavy client-side logic. This is a huge win for perceived performance.</p><p>Once that HTML is visible, JavaScript “hydrates” the interactive parts on top of it. The key idea here is simple: <strong>HTML paints first. Then the fun stuff wakes up.</strong></p><p>This is why it’s so important to mark <strong>only the components that truly need client-side behavior</strong> with &quot;use client&quot;. If you force the entire page to be client-rendered, you throw away all these benefits and make the browser wait for JavaScript before showing anything.</p><h3>Build as Much as Possible Ahead of Time (SSG / DSG)</h3><p>If a page’s content doesn’t change per visitor, Next.js can build it ahead of time.</p><ul><li>With <strong>Static Site Generation (SSG)</strong>, the HTML is created during the build and served straight from a CDN. No server work on each request. Just fast HTML delivered instantly.</li><li><strong>Deferred Static Generation (DSG)</strong> works similarly, but lets the page be built once and cached while still supporting occasional updates.</li></ul><p>The big idea is this: The less work Next.js has to do at request time, the faster the browser receives something to render.</p><p>When the browser isn’t blocked by slow data fetching or server rendering, animations can start sooner and feel smoother because the page is already there.</p><h3><strong>Bring in the Big Code Only When Needed (Lazy Loading)</strong></h3><p>Not everything needs to be part of the first JavaScript bundle.</p><p>Below-the-fold sections, heavy widgets, sliders, or carousels don’t need to load immediately. Next.js lets you split these into separate chunks using dynamic() imports.</p><p>For example, a testimonials section doesn’t need to load before the hero animation finishes because users won’t see it yet.</p><pre>&quot;use client&quot;;<br><br>import dynamic from &quot;next/dynamic&quot;;<br>import HeroSection from &quot;@/components/pages/homepage/Herosection&quot;;<br><br>const TestimonialsSection = dynamic(<br>  () =&gt; import(&quot;@/components/pages/homepage/TestimonialsSection&quot;),<br>  {<br>    ssr: false, // don’t render server-side, so this chunk only downloads in the browser<br>    loading: () =&gt; &lt;div className=&quot;placeholder&quot;&gt;Loading testimonials…&lt;/div&gt;,<br>  }<br>);<br><br>const Homepage = () =&gt; (<br>  &lt;&gt;<br>    &lt;HeroSection /&gt;<br>    {/* This component downloads only when the client hits this render path */}<br>    &lt;TestimonialsSection /&gt;<br>  &lt;/&gt;<br>);<br><br>export default Homepage;</pre><p>This keeps the initial download lighter and gives the browser breathing room during those critical first frames.</p><blockquote><strong><em>Quick note:</em></strong><em> disabling SSR like this is powerful, but should be used intentionally. That content won’t exist until JavaScript loads, which is fine for non-critical sections.</em></blockquote><h3>Use CSS to Keep Layout Stable, GSAP for the Motion</h3><p>The browser <em>hates</em> when elements jump around mid-render. That’s why layout stability matters so much. Before any animation runs, you should “claim” layout space with CSS:</p><ul><li>fixed heights</li><li>padding</li><li>grid gaps</li><li>aspect ratios</li></ul><p>Once the layout is stable, animations should stick to properties like transform and opacity. These run on the compositor layer and don’t force layout recalculation.</p><p>GSAP is fantastic for timing, staggering, and easing , but CSS should do the heavy lifting of keeping the page steady.</p><p>Personally, I try to use <strong>CSS animations whenever possible</strong>, and reach for GSAP only when I need sequencing, scroll logic, or fine-grained control. Fewer JS animations usually means fewer cleanup bugs and fewer initialization issues.</p><h3><strong>Schedule Animation Work in Phases</strong></h3><p>One mistake I made early on was triggering <em>everything</em> at once. A better approach is to <strong>phase your animations</strong>:</p><ul><li><strong>Critical animations</strong><br> Hero title entrance, overlays, primary transitions — these run immediately once the page is ready.</li><li><strong>Next repaint animations</strong><br> Arrows, secondary UI elements, counters — scheduled inside requestAnimationFrame.</li><li><strong>Decorative or below-the-fold animations</strong><br> Delayed slightly with setTimeout. They can wait.</li></ul><p>This pacing avoids long frames and keeps the page responsive, even when many animations are involved.</p><h3>A Reusable GSAP Scheduling Hook</h3><p>⚠️ <strong>Important note:</strong><br> This hook is <em>not</em> something you’re expected to write early on. Think of it as a pattern you grow into once animations start piling up and you need structure.</p><p>This is a custom hook I like to reuse across my Next.js projects. It lets me:</p><ul><li>group animations by priority</li><li>avoid running everything at once</li><li>ensure proper cleanup when components unmount</li></ul><pre>&#39;use client&#39;;<br><br>import { gsap, useGSAP } from &#39;@/lib/gsap&#39;;<br><br>export type AnimationInit = () =&gt; void | (() =&gt; void);<br><br>export interface AnimationSchedule {<br>  critical?: AnimationInit[];<br>  raf?: AnimationInit[];<br>  timeout?: AnimationInit[] | { actions: AnimationInit[]; delay?: number }[];<br>}<br><br>interface UseGSAPAnimationsOptions {<br>  delay?: number;<br>  dependencies?: any[];<br>}<br><br>export function useGSAPAnimations(<br>  init: (() =&gt; AnimationSchedule | void | (() =&gt; void)) | AnimationSchedule,<br>  options: UseGSAPAnimationsOptions = {}<br>) {<br>  const { delay = 0, dependencies = [] } = options;<br><br>  useGSAP(() =&gt; {<br>    const ctx = gsap.context(() =&gt; {<br>      const runAnimation = () =&gt; {<br>        try {<br>          const result = typeof init === &#39;function&#39; ? init() : init;<br><br>          if (isSchedule(result)) {<br>            return runSchedule(result);<br>          }<br><br>          if (typeof result === &#39;function&#39;) {<br>            return result;<br>          }<br>        } catch (error) {<br>          console.error(&#39;Error initializing animation:&#39;, error);<br>        }<br>      };<br><br>      if (delay &gt; 0) {<br>        const timer = window.setTimeout(() =&gt; {<br>          runAnimation();<br>        }, delay);<br><br>        return () =&gt; clearTimeout(timer);<br>      }<br><br>      return runAnimation();<br>    });<br><br>    return () =&gt; {<br>      ctx.revert();<br>    };<br>  }, [delay, ...dependencies]);<br>}<br><br>const isSchedule = (value: unknown): value is AnimationSchedule =&gt; {<br>  return (<br>    typeof value === &#39;object&#39; &amp;&amp;<br>    value !== null &amp;&amp;<br>    (&#39;critical&#39; in (value as object) ||<br>      &#39;raf&#39; in (value as object) ||<br>      &#39;timeout&#39; in (value as object))<br>  );<br>};<br><br>const runSchedule = (schedule: AnimationSchedule) =&gt; {<br>  const rafHandles: number[] = [];<br>  const timeoutHandles: number[] = [];<br>  const cleanupFns: (() =&gt; void)[] = [];<br><br>  const runActions = (actions: AnimationInit[] | undefined) =&gt; {<br>    if (!actions) return;<br>    actions.forEach((action) =&gt; {<br>      const cleanup = action();<br>      if (typeof cleanup === &#39;function&#39;) {<br>        cleanupFns.push(cleanup);<br>      }<br>    });<br>  };<br><br>  runActions(schedule.critical);<br><br>  if (schedule.raf) {<br>    schedule.raf.forEach((action) =&gt; {<br>      const id = requestAnimationFrame(() =&gt; runActions([action]));<br>      rafHandles.push(id);<br>    });<br>  }<br><br>  const timeoutEntries = Array.isArray(schedule.timeout)<br>    ? schedule.timeout.map((entry) =&gt;<br>        typeof entry === &#39;function&#39; ? { actions: [entry], delay: 0 } : entry<br>      )<br>    : [];<br><br>  timeoutEntries.forEach((entry) =&gt; {<br>    const handle = window.setTimeout(() =&gt; runActions(entry.actions), entry.delay ?? 0);<br>    timeoutHandles.push(handle);<br>  });<br><br>  return () =&gt; {<br>    rafHandles.forEach((id) =&gt; cancelAnimationFrame(id));<br>    timeoutHandles.forEach((id) =&gt; clearTimeout(id));<br>    cleanupFns.forEach((fn) =&gt; fn());<br>  };<br>};</pre><p><strong>Centralize the GSAP import</strong><br>GSAP often ends up imported in many places. Instead of pulling it directly everywhere, I like to create a <strong>single wrapper file</strong>.</p><p>Think of it like one electrical panel instead of rewiring every room separately.</p><pre>/**<br> * GSAP Initialization<br> * Central location for GSAP plugin registration.<br> */<br><br>import { gsap } from &#39;gsap&#39;;<br>import { ScrollTrigger } from &#39;gsap/ScrollTrigger&#39;;<br>import { ScrollToPlugin } from &#39;gsap/ScrollToPlugin&#39;;<br>import { MotionPathPlugin } from &#39;gsap/MotionPathPlugin&#39;;<br>import { useGSAP } from &#39;@gsap/react&#39;;<br>--&gt; and all other plugins from gsap you can need<br><br>// Register all GSAP plugins once<br>let pluginsRegistered = false;<br><br>export function initGSAP() {<br>  // Only register on client side<br>  if (typeof window === &#39;undefined&#39;) return;<br>  if (pluginsRegistered) return;<br><br>  gsap.registerPlugin(useGSAP, ScrollTrigger, ScrollToPlugin, MotionPathPlugin);<br>  pluginsRegistered = true;<br>}<br><br>// Auto-initialize on import (for convenience) - only on client side<br>if (typeof window !== &#39;undefined&#39;) {<br>  initGSAP();<br>}<br><br>// Export for manual initialization if needed<br>export { gsap, ScrollTrigger, ScrollToPlugin, MotionPathPlugin, useGSAP };</pre><p>Then later in your files that need any of these imports, do:</p><pre>import { gsap, useGSAP } from &#39;@/lib/gsap&#39;;<br><br>...</pre><p>This keeps configuration consistent and avoids scattered setup logic across the codebase.</p><h3><strong>Why All of This Matters</strong></h3><p>The goal is to let Next.js 15 do what it does best:</p><ul><li>stream HTML early</li><li>cache what can be cached</li><li>hydrate only what truly needs JavaScript</li></ul><p>By combining:</p><ul><li>SSG / DSG</li><li>lazy loading</li><li>layout-stable CSS</li><li>GSAP for motion control</li><li>phased animation scheduling</li></ul><p>…you allow the browser to show something meaningful fast, and then layer smooth animations on top without hurting performance.</p><p>That’s the practical path to making big animations feel crisp, not heavy, and to building pages that feel alive without slowing everything down.</p><p><em>Could this be pushed further? Do you know about other techniques? Please reach out :)</em></p><p><a href="https://www.helloimtom.dev/fr">https://www.helloimtom.dev/</a></p><p><strong>GitHub: </strong><a href="https://github.com/thomasaugot">https://github.com/thomasaugot</a></p><p><strong>LinkedIn: </strong><a href="https://www.linkedin.com/in/thomas-augot/">https://www.linkedin.com/in/thomas-augot/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46d90f503b15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Set Up Google Analytics with Google Tag Manager in Next.js 16 — Updated May 2026]]></title>
            <link>https://medium.com/@thomasaugot/how-to-set-up-google-analytics-with-google-tag-manager-in-next-js-15-in-2025-dedfcaee875a?source=rss-8df0d3754eb0------2</link>
            <guid isPermaLink="false">https://medium.com/p/dedfcaee875a</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[nextjs-15]]></category>
            <category><![CDATA[google-analytics]]></category>
            <category><![CDATA[google-tag-manager]]></category>
            <dc:creator><![CDATA[Thomas Augot]]></dc:creator>
            <pubDate>Thu, 27 Nov 2025 12:43:52 GMT</pubDate>
            <atom:updated>2026-05-10T11:47:44.475Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NUwuj_NBQdYvyqCP6iIiCA.png" /></figure><p>Setting up Google Analytics and Google Tag Manager in a modern Next.js 15 project <em>should</em> be simple, but most tutorials you’ll find online are outdated, incomplete, or refer to older versions of GA4, GTM, or even Next.js itself.</p><p>I spent more time than I’d like to admit figuring out what was missing, and so this guide exists to save you that time.</p><p>This article explains <strong>exactly how to set everything up correctly in 2025</strong>, including advanced tracking:</p><ul><li>CTA click tracking</li><li>Scroll depth tracking</li><li>Contact form interaction tracking</li><li>Form submit success tracking</li></ul><p>All using Next.js 15 &amp; 16, Google Tag Manager (from now on you may read “GTM”), and Google Analytics 4 (GA4), with a modern, reliable and scalable setup.</p><h3><strong>My Use Case</strong></h3><p>I recently built a website in <strong>Next.js 15</strong> for my company. The goal was to gather traffic insights for marketing and product decisions.</p><p>During research, I learned that:</p><ul><li>GA4’s built-in tracking alone is limited</li><li>GTM allows cleaner, safer, easier tracking</li><li>Using both together is the recommended approach in 2025</li><li>Both are completely free</li></ul><p>So here is exactly how to set everything up, without outdated tutorials, assumptions, or missing steps.</p><h3><strong>What Google Tag Manager Actually Does</strong></h3><p>Google Tag Manager (GTM) is a <strong>centralized hub for tracking scripts</strong>. Instead of hardcoding analytics snippets or events in your code, GTM allows you to:</p><ul><li>Add and remove tracking scripts without deploying code</li><li>Use custom triggers and conditions</li><li>Test your tagging setup before publishing</li><li>Push custom events (CTA clicks, form events, etc.)</li><li>Keep your website clean and maintainable</li></ul><p>GTM listens for events, reacts based on your configuration, and sends data to GA4 or any other tool.</p><p>Now let’s install everything step-by-step.</p><h3><strong>Setting Up Google Analytics in Next.js 16 Using Google Tag Manager</strong></h3><h4><strong>Prerequisites</strong></h4><ul><li>A <strong>Next.js 15</strong> project</li><li>A <strong>GA4 property</strong></li><li>A <strong>Google Tag Manager</strong> account</li></ul><p>⚠️ <strong>Next.js 16 note:</strong> Next.js 16 replaces middleware.ts with proxy.ts as the routing interception file. Nothing in this guide creates a middleware.ts, so you&#39;re safe — just don&#39;t add one manually. If you need to protect analytics-related routes, edit proxy.ts.</p><p><strong>Step 1 — Create Your Google Tag Manager Container</strong></p><p>1. Go to <a href="https://tagmanager.google.com/">https://tagmanager.google.com</a></p><p>2. Click <strong>Create Account</strong></p><p>3. Add a new <strong>Container</strong></p><p>4. Choose <strong>Web</strong> as the target platform (if you aim at tracking events on a webpage of course…)</p><p>5. Copy your <strong>Container ID</strong> (GTM-XXXXXXX).</p><h4><strong>Step 2 — Install @next/third-parties</strong></h4><p>This is the official Next.js package for optimized, hydration-aware script loading.</p><pre>npm install @next/third-parties@latest</pre><h4><strong>Step 3 — In your code, add GTM to Your Root Layout</strong></h4><p>Edit your root layout: app/layout.tsx or app/layout.js.</p><pre>import { GoogleTagManager } from &#39;@next/third-parties/google&#39;<br><br>export default function RootLayout({ children }) {<br>  return (<br>    &lt;html lang=&quot;en&quot;&gt;<br>      &lt;GoogleTagManager gtmId=&quot;GTM-XXXXXXX&quot; /&gt;<br>      &lt;body&gt;{children}&lt;/body&gt;<br>    &lt;/html&gt;<br>  )<br>}</pre><p>Push this to production and wait a few minutes — GTM does <strong>not</strong> show up instantly.</p><p>The component handles:</p><ul><li>GTM loading after hydration</li><li>noscript fallback iframe</li><li>performance-optimized script injection</li></ul><h4><strong>Step 4 — Connect GA4 Inside Google Tag Manager</strong></h4><p>Inside GTM:</p><p>1. Go to <strong>Tags → New</strong></p><p>2. Name it: GA4 — Page View</p><p>3. Tag Type → <strong>Google Analytics → Google Tag</strong></p><p>4. Enter your <strong>Measurement ID</strong> (G-XXXXXXXXXX)</p><p><em>Find it in GA4 under: Admin (click the gear icon at the bottom left of the panel) → Data Streams → Web Stream Details:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I9FWPrs9QmMhes73PRm4Ow.png" /></figure><p>5. Trigger: <strong>All Pages</strong></p><p>6. Save → Submit (publish), pass it a version name if you want, it works without.</p><p>Now GTM will forward page views to GA4.</p><h3><strong>Step 5 — Verify Tracking</strong></h3><h4><strong>Option A — Use Tag Assistant</strong></h4><p>1. Go to <a href="https://tagassistant.google.com/">https://tagassistant.google.com</a></p><p>2. Enter your site URL</p><p>3. Start debugging</p><p>4. You should see:</p><ul><li>GTM container is loaded</li><li>GA4 tags firing on page load</li></ul><h4><strong>Option B — GA4 Real-Time Reports</strong></h4><p>1. Go to GA4 → <strong>Reports → Realtime</strong></p><p>2. Open your website in a private window</p><p>3. You should appear within seconds</p><h3>⚠️ <strong>If Tracking Doesn’t Work</strong></h3><h4><strong>No GA4 data appearing</strong></h4><ul><li>Check Measurement ID (one wrong letter breaks everything)</li></ul><h4><strong>“Tag Installed Incorrectly” warning</strong></h4><p>Remove any <strong>manual GTM or GA code</strong> from your HTML</p><p>Only use @next/third-parties/google</p><h4><strong>No data unless user accepts cookies</strong></h4><p>If your website uses a cookie banner:</p><p>➜ <strong>Analytics will not work until analytics cookies are accepted </strong>(GTM and GA4 are blocked by default.)</p><p>Test by clearing cookies → reloading site → accepting analytics.</p><h3>⭐ Special bonus: <strong>Advanced Tracking Setup</strong></h3><p>So my colleague in charge of the marketing wanted to know literally everything: where visitors click, where they scroll, etc.</p><p>These are the exact GTM configurations I made that are working in production.</p><p>We will track:</p><p>1. CTA clicks</p><p>2. Scroll depth (25%, 50%, 75%, 90%)</p><p>3. Contact form service selection</p><p>4. Form submit success</p><p>Before we start, understand the event types:</p><h3><strong>Automatic vs Manual Events</strong></h3><h4><strong>Automatic events</strong> (GTM detects them):</h4><ul><li>Page views</li><li>Clicks</li><li>Scroll depth</li></ul><h4><strong>Manual events</strong> (your code must push them):</h4><ul><li>cta_click</li><li>form_service_selected</li><li>form_submit_success</li></ul><p>Manual events follow this pattern:</p><pre>window.dataLayer.push({<br>  event: &quot;event_name&quot;,<br>  key: &quot;value&quot;,<br>})</pre><p>Then GTM triggers GA4 based on that event.</p><h3><strong>1. CTA Click Tracking</strong></h3><p>Goal: Track the CTA label and destination url.</p><p>There are <strong>two correct methods</strong>. Pick one (Hint: I usually hate no code options, so I went for Method B…).</p><h3><strong>Method A — DOM Variables (No code needed)</strong></h3><h4><strong>HTML</strong></h4><pre>&lt;Link<br>  className=&quot;cta-tag&quot;<br>  data-cta_text=&quot;Contact&quot;<br>  data-cta_url=&quot;/contact&quot;<br>&gt;<br>  Contact<br>&lt;/Link&gt;</pre><h4><strong>In GTM → Variables → New</strong></h4><p>Create:</p><h4><strong>DOM — CTA Text</strong></h4><ul><li>Type: DOM Element</li><li>Selector: .cta-tag</li><li>Attribute: data-cta_text</li></ul><h4><strong>DOM — CTA URL</strong></h4><ul><li>Type: DOM Element</li><li>Selector: .cta-tag</li><li>Attribute: data-cta_url</li></ul><h4><strong>Trigger → New → Click — All Elements</strong></h4><ul><li>Fire on: Some Clicks</li><li>Condition: Click Classes <strong>contains</strong> cta-tag</li><li>Name: Trigger — CTA Click</li></ul><h4><strong>Tag → New → Google Tag</strong></h4><ul><li>Event name: cta_click</li><li>Parameters:</li></ul><p>cta_text → {{DOM — CTA Text}}</p><p>cta_url → {{DOM — CTA URL}}</p><h3><strong>Method B — Custom HTML Listener (The one I recommend, also because I read it is more reliable)</strong></h3><p>This is the version used in my project (and more reliable).</p><p><strong>Create this tag in GTM → Tags → New → Custom HTML</strong></p><pre>&lt;script&gt;<br>(function() {<br>  document.addEventListener(&#39;click&#39;, function(e) {<br>    var target = e.target.closest(&#39;.cta-tag&#39;);<br>    if (target) {<br>      window.dataLayer.push({<br>        event: &#39;cta_click&#39;,<br>        cta_text: target.getAttribute(&#39;data-cta_text&#39;),<br>        cta_url: target.getAttribute(&#39;data-cta_url&#39;)<br>      });<br>    }<br>  });<br>})();<br>&lt;/script&gt;</pre><h4><strong>Trigger</strong></h4><ul><li>Trigger type: <strong>Custom Event</strong></li><li>Event name: cta_click</li></ul><h4><strong>GA4 Tag</strong></h4><ul><li>Event name: cta_click</li><li>Parameters:</li></ul><p>cta_text (Data Layer Variable)</p><p>cta_url (Data Layer Variable)</p><h3><strong>2. Scroll Depth Tracking (25%, 50%, 75%, 90%)</strong></h3><h4><strong>Enable Built-In Variables</strong></h4><p>GTM → Variables → Configure → enable:</p><ul><li>Scroll Depth Threshold</li><li>Scroll Depth Units</li><li>Scroll Direction</li></ul><h4><strong>Trigger → Scroll Depth</strong></h4><ul><li>Vertical Scroll: ON</li><li>Percentages: 25,50,75,90 (Be careful, use comas “,” and not slashes “/” between the numbers)</li><li>Name: Trigger — Scroll Depth</li></ul><h4><strong>GA4 Tag</strong></h4><ul><li>Event name: scroll_depth</li><li>Parameter:</li></ul><p>scroll_percent → {{Scroll Depth Threshold}}</p><h3><strong>3. Contact Form: Service Selected Tracking</strong></h3><h4><strong>HTML</strong></h4><pre>&lt;button class=&quot;contact-service-button&quot; data-service=&quot;strategy&quot;&gt;<br>  Strategy<br>&lt;/button&gt;</pre><h4><strong>DOM Variable</strong></h4><ul><li>Name: DOM — Form Service</li><li>Type: DOM Element</li><li>Selector: .contact-service-button</li><li>Attribute: data-service</li></ul><h4><strong>Trigger</strong></h4><ul><li>Click — All Elements</li><li>Condition: Click Classes contains contact-service-button</li><li>Name: Trigger — Form Service Selected</li></ul><h4><strong>GA4 Tag</strong></h4><ul><li>Event name: form_service_selected</li><li>Parameter:</li></ul><p>service_name → {{DOM — Form Service}}</p><h3><strong>4. Form Submit Success Tracking</strong></h3><h4><strong>Push event from your code</strong></h4><pre>if (typeof window !== &quot;undefined&quot; &amp;&amp; window.dataLayer) {<br>  window.dataLayer.push({<br>    event: &quot;form_submit_success&quot;,<br>    form_name: &quot;contact_form&quot;,<br>    service_name: formData.service || &quot;not_selected&quot;<br>  });<br>}</pre><h4><strong>Trigger</strong></h4><ul><li>Type: Custom Event</li><li>Event name: form_submit_success</li></ul><h4><strong>GA4 Tag</strong></h4><ul><li>Event Name: form_submit_success</li><li>Parameters:</li></ul><p>form_name</p><p>service_name</p><h3>Final Step: Register Your Custom Event Parameters in GA4</h3><p>For your CTA clicks, scroll depth, or form events to appear inside GA4 reports, you must register each event parameter as a <strong>Custom Dimension</strong>.</p><h4>Go to:</h4><p><strong>GA4 → Admin (the gear icon at the bottom left corner again) → Property → Custom definitions → Create custom dimension</strong></p><p>Create one for each parameter used in your events:</p><pre>| Dimension Name | Scope | Event Parameter|<br>| -------------- | ----- | ---------------|<br>| CTA Text       | Event | cta_text       |<br>| CTA URL        | Event | cta_url        |<br>| Scroll Percent | Event | scroll_percent |<br>| Service Name   | Event | service_name   |</pre><p><em>¡Please bear in mind! for the parameters you have a dropdown, but the values of events we are looking for aren’t there, you must type them manually, you will se it lets you do it.</em></p><h3><strong>⚠️ Critical: Implementing the Event Listeners</strong></h3><p><strong>Important: </strong>The GTM configurations above will only work if your code actually pushes events to the `dataLayer`. Here’s what you need to implement:</p><p><strong>Method A: GTM Custom HTML Tag (As described above)</strong></p><p>If you’re using the Custom HTML tag approach in GTM, you’re all set — GTM will inject the listeners.</p><p><strong>Method B: Next.js Implementation (Recommended by me)</strong></p><p>For better type safety, debugging, and control, implement the tracking directly in your Next.js app:</p><ul><li><strong>Step 1: Create Event Utility</strong></li></ul><p>Create <strong>utils/gtm-events.ts</strong>:</p><pre>interface GTMEvent {<br>  event: string;<br>  [key: string]: unknown;<br>}<br><br>export const pushToDataLayer = (eventData: GTMEvent) =&gt; {<br>  if (typeof window !== &#39;undefined&#39; &amp;&amp; window.dataLayer) {<br>    window.dataLayer.push(eventData);<br>  }<br>};<br><br>export const trackCTAClick = (ctaText: string, ctaUrl: string) =&gt; {<br>  pushToDataLayer({<br>    event: &#39;cta_click&#39;,<br>    cta_text: ctaText,<br>    cta_url: ctaUrl,<br>  });<br>};<br><br>export const trackScrollDepth = (scrollPercent: number) =&gt; {<br>  pushToDataLayer({<br>    event: &#39;scroll_depth&#39;,<br>    scroll_percent: scrollPercent.toString(),<br>  });<br>};<br><br>export const trackFormServiceSelection = (serviceName: string) =&gt; {<br>  pushToDataLayer({<br>    event: &#39;form_service_selected&#39;,<br>    service_name: serviceName,<br>  });<br>};<br><br>declare global {<br>  interface Window {<br>    dataLayer: any[];<br>  }<br>}</pre><ul><li><strong>Step 2: Create Analytics Hook</strong></li></ul><p>Create <strong>hooks/useAnalyticsTracking.ts</strong>:</p><pre>&#39;use client&#39;;<br><br>import { useEffect, useRef } from &#39;react&#39;;<br>import { trackCTAClick, trackScrollDepth } from &#39;@/utils/gtm-events&#39;;<br><br>export function useAnalyticsTracking() {<br>  const scrollThresholds = useRef(new Set&lt;number&gt;());<br>  const hasInitialized = useRef(false);<br><br>  useEffect(() =&gt; {<br>    if (typeof window === &#39;undefined&#39; || hasInitialized.current) return;<br>    hasInitialized.current = true;<br><br>    // CTA Click Tracking<br>    const handleCTAClick = (event: MouseEvent) =&gt; {<br>      const target = event.target as HTMLElement;<br>      const ctaElement = target.closest(&#39;[data-cta_click=&quot;true&quot;]&#39;);<br><br>      if (ctaElement) {<br>        const ctaText = ctaElement.getAttribute(&#39;data-cta_text&#39;) || &#39;Unknown&#39;;<br>        const ctaUrl = ctaElement.getAttribute(&#39;data-cta_url&#39;) || &#39;&#39;;<br>        trackCTAClick(ctaText, ctaUrl);<br>      }<br>    };<br><br>    // Scroll Depth Tracking<br>    const handleScroll = () =&gt; {<br>      const windowHeight = window.innerHeight;<br>      const documentHeight = document.documentElement.scrollHeight;<br>      const scrollTop = window.scrollY;<br>      const scrollPercent = Math.round(<br>        ((scrollTop + windowHeight) / documentHeight) * 100<br>      );<br><br>      const milestones = [25, 50, 75, 90, 100];<br>      milestones.forEach((milestone) =&gt; {<br>        if (scrollPercent &gt;= milestone &amp;&amp; !scrollThresholds.current.has(milestone)) {<br>          scrollThresholds.current.add(milestone);<br>          trackScrollDepth(milestone);<br>        }<br>      });<br>    };<br><br>    document.addEventListener(&#39;click&#39;, handleCTAClick, true);<br>    window.addEventListener(&#39;scroll&#39;, handleScroll, { passive: true });<br>    handleScroll(); // Initial check<br><br>    return () =&gt; {<br>      document.removeEventListener(&#39;click&#39;, handleCTAClick, true);<br>      window.removeEventListener(&#39;scroll&#39;, handleScroll);<br>    };<br>  }, []);<br>}</pre><ul><li><strong>Step 3: Create Tracker Component</strong></li></ul><p>Create <strong>components/AnalyticsTracker.tsx</strong>:</p><pre>&#39;use client&#39;;<br><br>import { useAnalyticsTracking } from &#39;@/hooks/useAnalyticsTracking&#39;;<br><br>export default function AnalyticsTracker() {<br>  useAnalyticsTracking();<br>  return null;<br>}</pre><ul><li><strong>Step 4: Add to your Layout file:</strong></li></ul><p>In <strong>app/layout.tsx</strong>:</p><pre>import AnalyticsTracker from &quot;@/components/AnalyticsTracker&quot;;<br><br>export default function LocaleLayout({ children }) {<br>  return (<br>    &lt;&gt;<br>      &lt;AnalyticsTracker /&gt;<br>      {children}<br>    &lt;/&gt;<br>  );<br>}</pre><ul><li><strong>Step 5: Mark Your CTAs</strong></li></ul><p>Ensure all CTA elements have the tracking attributes:</p><pre>&lt;Link<br>  href=&quot;/contact&quot;<br>  data-cta_click=&quot;true&quot;<br>  data-cta_text=&quot;Contact Us&quot;<br>  data-cta_url=&quot;/contact&quot;<br>&gt;<br>  Contact Us<br>&lt;/Link&gt;</pre><ul><li><strong>Step 6: Track Form Service Selection</strong></li></ul><p>In your contact form:</p><pre>import { trackFormServiceSelection } from &#39;@/utils/gtm-events&#39;;<br><br>// In button onClick<br>onClick={() =&gt; {<br>  setFormData({ ...formData, service: service.value });<br>  trackFormServiceSelection(service.value);<br>}}</pre><h3><strong>Why This Approach is Better</strong></h3><ol><li><strong>Type Safety</strong>— TypeScript catches errors at compile time</li><li><strong>Debugging</strong>— Console logs show exactly what events fire</li><li><strong>Testing</strong>— Can unit test the tracking functions</li><li><strong>Version Control</strong>— Changes tracked in Git</li><li><strong>Performance</strong> — No waiting for GTM to inject scripts</li></ol><h3><strong>Verification</strong></h3><p>Open browser DevTools → Console. You should see:</p><pre>[GTM Event] { event: &#39;cta_click&#39;, cta_text: &#39;Contact&#39;, cta_url: &#39;/contact&#39; }<br>[GTM Event] { event: &#39;scroll_depth&#39;, scroll_percent: &#39;25&#39; }<br>[GTM Event] { event: &#39;form_service_selected&#39;, service_name: &#39;automation&#39; }</pre><h3><strong>The Most Critical Step You Must Not Forget</strong></h3><h4><strong>Register Custom Dimensions in GA4</strong></h4><p><strong>This is why I had empty data for like a week…!</strong> GA4 will NOT collect custom event parameters unless you explicitly register them as custom dimensions.</p><p><strong>How to Register:</strong></p><p>1. Go to <strong>GA4 </strong><a href="https://analytics.google.com/">https://analytics.google.com/</a> (not GTM) → Admin → Property Settings</p><p>2. Click <strong>Custom definitions</strong> (under “Data display”)</p><p>3. Click <strong>**Create custom dimension**</strong></p><p>4. Create these 4 dimensions:</p><pre>| Dimension Name | Scope | Event Parameter | Description            |<br>|----------------|-------|-----------------|------------------------|<br>| CTA Text       | Event | `cta_text`      | Text of clicked CTA    |<br>| CTA URL        | Event | `cta_url`       | Destination URL        |<br>| Scroll Percent | Event | `scroll_percent`| Page scroll percentage |<br>| Service Name   | Event | `service_name`  | Selected service       |</pre><p><strong>Important:</strong></p><ul><li>Type the event parameter names manually (they won’t be in dropdown)</li><li>Wait 24–48 hours for data to start appearing</li><li>Custom dimensions cannot be deleted, only archived</li></ul><h3><strong>Debugging: GTM Preview Mode</strong></h3><p>1. Go to GTM → <strong>Preview</strong></p><p>2. Enter your URL</p><p>3. Interact with your site</p><p>4. Check timeline on the left:</p><ul><li>Events appear?</li><li>Tags fired?</li><li>Any blocking conditions?</li></ul><p>If GA4 still shows nothing, check:</p><ul><li>Wrong Measurement ID</li><li>Cookie consent not accepted</li><li>Missing Data Layer Variables</li><li>Event name mismatch</li></ul><h3><strong>Final Result</strong></h3><p>After completing this setup:</p><p>✅ Page views load via GTM</p><p>✅ CTA clicks tracked with text + URL</p><p>✅ Scroll depth recorded at 4 levels</p><p>✅ Service button clicks tracked</p><p>✅ Form submissions tracked</p><p>✅ Events visible in:</p><ul><li>GA4 DebugView</li><li>GA4 Realtime</li><li>GA4 Explore Reports</li></ul><p>This gives you a <strong>scalable</strong>, <strong>maintainable</strong>, and <strong>future-proof analytics setup</strong> for Next.js 15. If you know more tricks you believe I should know about so I can try them myself and complete this article, get in touch :)</p><p>👋 Thanks for reading!</p><p>If you enjoyed this guide or found it useful, feel free to connect with me:</p><p><strong>Website:</strong> <a href="https://helloimtom.dev/">https://helloimtom.dev/</a></p><p><strong>GitHub: </strong><a href="https://github.com/thomasaugot">https://github.com/thomasaugot</a></p><p><strong>LinkedIn: </strong><a href="https://www.linkedin.com/in/thomas-augot/">https://www.linkedin.com/in/thomas-augot/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dedfcaee875a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Fix “The Link You Followed Has Expired” Error When Installing WordPress Themes]]></title>
            <link>https://medium.com/@thomasaugot/how-to-fix-the-link-you-followed-has-expired-error-when-installing-wordpress-themes-96d71da055cb?source=rss-8df0d3754eb0------2</link>
            <guid isPermaLink="false">https://medium.com/p/96d71da055cb</guid>
            <category><![CDATA[wordpress]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[wordpress-themes]]></category>
            <dc:creator><![CDATA[Thomas Augot]]></dc:creator>
            <pubDate>Fri, 10 Oct 2025 10:18:30 GMT</pubDate>
            <atom:updated>2025-11-30T11:34:20.498Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gi_6NPWhBKNBKycv1ZAfPA.png" /></figure><h3>The problem I faced…</h3><p>I had just purchased a premium WordPress theme for our client, configured things on our VPS, etc etc. Then I navigated to the WordPress dashboard, clicked “Upload Theme,” select the file, and… nothing. Instead of installation progress, I got greeted with a cryptic message:</p><p><strong>“The link you followed has expired.”</strong></p><h3>What’s Really Happening</h3><p>Despite what the error message suggests, the “link” hasn’t actually expired. This is WordPress’s somewhat misleading way of telling us that our server doesn’t have enough resources allocated to complete the file upload.</p><p>When you upload a theme or plugin through the WordPress dashboard, your server needs to:</p><ol><li>Accept the file upload (which requires sufficient upload size limits)</li><li>Process the ZIP archive (which requires memory)</li><li>Extract and install the files (which requires execution time)</li></ol><p>If any of these operations exceeds your server’s configured limits, the process fails, and WordPress displays the “expired link” error.</p><h3>The Root Cause: PHP Configuration Limits</h3><p>The web server’s PHP configuration controls three critical settings:</p><h3>1. upload_max_filesize</h3><p>This defines the maximum size of any single file we can upload. Many shared hosting providers set this to just 2–8 MB by default, but modern premium themes often exceed 20–50 MB because they include demo content, multiple page builders, and extensive design assets.</p><h3>2. post_max_size</h3><p>This controls the maximum size of all data sent in a single request. It should always be equal to or greater than upload_max_filesize. If the theme file is 25 MB but post_max_size is set to 8 MB, the upload will fail.</p><h3>3. max_execution_time</h3><p>This sets how many seconds a PHP script can run before the server kills it. Installing complex themes can take longer than the typical 30–60 second default, especially on slower servers or when importing demo content.</p><h3>My Solution: Editing the .htaccess File</h3><p>I had several options to fix this issue, but since I am working on an Ubuntu VPS with Apache (the most common web server configuration), editing the .htaccess file proved to be the most straightforward solution.</p><h3>Step-by-Step Fix</h3><p><strong>1. Access your server via SSH:</strong></p><pre>ssh root@your-server-ip</pre><p><strong>2. Navigate to the WordPress installation directory:</strong></p><pre>cd /home/your-client/public_html</pre><p><strong>3. Edit the .htaccess file:</strong></p><pre>sudo nano .htaccess</pre><p><strong>4. Scroll to the bottom of the file, past the </strong><strong># END WordPress line, and add:</strong></p><pre>php_value upload_max_filesize 256M<br>php_value post_max_size 256M<br>php_value max_execution_time 300<br>php_value max_input_time 300</pre><p>your file should now look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F_D3P55wpb9dBsQwen3wDA.png" /></figure><p><strong>5. Save and exit:</strong></p><ul><li>Press Ctrl + O to save</li><li>Press Enter to confirm</li><li>Press Ctrl + X to exit</li></ul><p><strong>6. Return to WordPress and try uploading your theme again.</strong></p><p>The upload should now work perfectly!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PY2IHRKnanWOYZJljeOgXw.png" /></figure><h3>Why These values in the htaccess file?</h3><p>You might wonder why we chose 256 MB and 300 seconds. Here’s the reasoning:</p><ul><li><strong>256M file size</strong>: Most premium themes with all their assets fall well under this limit, giving us plenty of headroom</li><li><strong>300 seconds (5 minutes)</strong>: This provides ample time for even the slowest servers to process large theme files</li><li><strong>max_input_time</strong>: We set this equal to max_execution_time to ensure the entire upload and processing pipeline has sufficient time</li></ul><h3>Alternative Solutions</h3><p>If editing .htaccess doesn&#39;t work for your setup (some hosts restrict this), here are other approaches:</p><h3>Method 1: Edit php.ini</h3><p>Create or edit a php.ini file in your WordPress root directory:</p><pre>upload_max_filesize = 256M<br>post_max_size = 256M<br>max_execution_time = 300</pre><h3>Method 2: Modify functions.php</h3><p>Add this to your theme’s functions.php file (use a child theme!):</p><pre>@ini_set(&#39;upload_max_filesize&#39;, &#39;256M&#39;);<br>@ini_set(&#39;post_max_size&#39;, &#39;256M&#39;);<br>@ini_set(&#39;max_execution_time&#39;, &#39;300&#39;);</pre><h3>Method 3: Contact Your Host</h3><p>If you’re on shared hosting or uncomfortable editing files, simply contact your hosting provider’s support team. This is a common request, and they can adjust these settings for you in minutes.</p><h3>Method 4: Manual FTP Upload (The Nuclear Option)</h3><p>Bypass WordPress’s uploader entirely:</p><ol><li>Download and unzip your theme file locally</li><li>Connect to your server via FTP</li><li>Upload the unzipped theme folder to /wp-content/themes/</li><li>Activate the theme from your WordPress dashboard</li></ol><h3>The Happy Ending</h3><p>After implementing this fix, the custom theme uploaded without issue. I was able to proceed with installing required plugins, importing a demo layout, and customizing the site for our client. What initially seemed like a project-blocking error turned into a 5-minute configuration adjustment.</p><p>If you have any better solution or think mine can be improved, please reach out and let’s chat!</p><p>Thanks for reading :)</p><p>If you liked this article, feel free to connect with me!</p><ul><li><a href="https://helloimtom.dev/">https://helloimtom.dev/</a></li><li>Github: <a href="https://github.com/thomasaugot">https://github.com/thomasaugot</a></li><li>LinkedIn: <a href="https://www.linkedin.com/in/thomas-augot/">https://www.linkedin.com/in/thomas-augot/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96d71da055cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing GSAP Animations in Next.js 15: Best Practices for Initialization and Cleanup]]></title>
            <link>https://medium.com/@thomasaugot/optimizing-gsap-animations-in-next-js-15-best-practices-for-initialization-and-cleanup-2ebaba7d0232?source=rss-8df0d3754eb0------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ebaba7d0232</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[gsap]]></category>
            <category><![CDATA[nextjs-15]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Thomas Augot]]></dc:creator>
            <pubDate>Mon, 01 Sep 2025 12:07:05 GMT</pubDate>
            <atom:updated>2025-11-30T11:34:46.403Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JzjDH98G8CmVXnc8wYg3qQ.png" /></figure><p>When building immersive websites with GSAP, performance and stability are just as important as visual wow effects. Yet many projects suffer from laggy transitions, memory leaks, or “stuck” scroll triggers — especially when using Next.js 15 with App Router.</p><p>After a few iterations of trial and error, I’ve developed a clean strategy to load GSAP only once, keep animations blazing fast, and prevent bugs across route changes. In this article, I’ll show you my solution on how to structure a GSAP setup for maximum performance.</p><h3>The Problem</h3><p>By default, it’s tempting to:</p><ul><li>import { gsap } from &quot;gsap&quot;; inside every animation file</li><li>call gsap.registerPlugin(ScrollTrigger) repeatedly</li><li>sprinkle ScrollTrigger.killAll() in cleanups</li><li>forget to remove event listeners or intervals</li></ul><p>The result?<br> → Every page transition reloads GSAP. Animations lag, ScrollTriggers leak, and memory consumption grows.</p><h3>Step 1. Create a Single GSAP Config File</h3><p>Instead of importing GSAP everywhere, centralize it once:</p><pre>// lib/gsapConfig.ts<br><br>&quot;use client&quot;;<br><br>import { gsap } from &quot;gsap&quot;;<br>import { ScrollTrigger } from &quot;gsap/ScrollTrigger&quot;;<br><br>if (typeof window !== &quot;undefined&quot; &amp;&amp; !gsap.core.globals()[&quot;ScrollTrigger&quot;]) {<br>  gsap.registerPlugin(ScrollTrigger);<br>}<br>export { gsap, ScrollTrigger };</pre><p>You now have one consistent instance of GSAP + plugins across your whole app.</p><h3>Step 2. Use a Dedicated Hook for Page Animations</h3><p>We created a custom hook to run animations only when the app is ready, with a small delay to avoid DOM race conditions:</p><pre>// hooks/useGSAPAnimations.ts<br><br>&quot;use client&quot;;<br><br>import { useGSAP } from &quot;@gsap/react&quot;;<br>import { useAppReady } from &quot;@/hooks/useAppReady&quot;;<br>import { gsap, ScrollTrigger } from &quot;@/lib/gsapConfig&quot;;<br><br>type AnimationFunction = () =&gt; (() =&gt; void) | void;<br><br>export const useGSAPAnimations = ({<br>  animations,<br>  delay = 100,<br>  dependencies = [],<br>}: {<br>  animations: AnimationFunction[];<br>  delay?: number;<br>  dependencies?: any[];<br>}) =&gt; {<br>  const isAppReady = useAppReady();<br><br>  useGSAP(() =&gt; {<br>    if (!isAppReady) return;<br>    const cleanupFns: Array&lt;() =&gt; void&gt; = [];<br>    const timer = setTimeout(() =&gt; {<br>      animations.forEach((fn) =&gt; {<br>        const cleanup = fn();<br>        if (typeof cleanup === &quot;function&quot;) cleanupFns.push(cleanup);<br>      });<br>      ScrollTrigger.refresh(); // important!<br>    }, delay);<br><br>    return () =&gt; {<br>      clearTimeout(timer);<br>      cleanupFns.forEach((fn) =&gt; fn());<br>    };<br>  }, [isAppReady, ...dependencies]);<br>};</pre><p>This guarantees:</p><ul><li><strong>100ms buffer</strong> so the DOM is mounted</li><li>all animations are cleaned up on unmount</li><li>no accidental global killAll()</li></ul><h3>Step 3. Scope Your Animations</h3><p>Every animation util should:</p><ul><li><strong>import GSAP from the config</strong>, not from &quot;gsap&quot;</li><li><strong>track only the ScrollTriggers it creates</strong></li><li><strong>return a cleanup function</strong></li></ul><p>Example:</p><pre>// utils/animations/entrance-animations.ts<br><br>&quot;use client&quot;;<br><br>import { gsap, ScrollTrigger } from &quot;@/lib/gsapConfig&quot;;<br><br>export const initEntranceAnimations = () =&gt; {<br>  const triggers: ScrollTrigger[] = [];<br><br>  document.querySelectorAll(&quot;.fade-in-up&quot;).forEach((el) =&gt; {<br>    gsap.set(el, { y: 30, opacity: 0 });<br>    const t = ScrollTrigger.create({<br>      trigger: el,<br>      start: &quot;top 85%&quot;,<br>      onEnter: () =&gt;<br>        gsap.to(el, { y: 0, opacity: 1, duration: 0.8, ease: &quot;power2.out&quot; }),<br>      once: true,<br>    });<br><br>    triggers.push(t);<br>  });<br><br>  return () =&gt; {<br>    triggers.forEach((t) =&gt; t.kill());<br>    gsap.killTweensOf(&quot;.fade-in-up&quot;);<br>  };<br>};</pre><p>This avoids wiping out <em>other</em> triggers.</p><h3>Step 4. Handle Event Listeners and Intervals</h3><p>Animations often add scroll/resize listeners, hover handlers, or auto-advance intervals.<br>Always clean them up:</p><pre>const intervalId = setInterval(nextSlide, 3000);<br>const onResize = () =&gt; st.refresh();<br>window.addEventListener(&quot;resize&quot;, onResize);<br><br>return () =&gt; {<br>  clearInterval(intervalId);<br>  window.removeEventListener(&quot;resize&quot;, onResize);<br>  st.kill();<br>};</pre><h3>Step 5. Delay Where Necessary, but No More</h3><p>We discovered that a small setTimeout (100ms) before running animations helps ensure DOM elements are mounted.</p><p>But avoid overusing it — always pair delays with <strong>retry limits</strong> and <strong>cleanup of pending timeouts</strong>.</p><h3>Step 6. Refresh ScrollTrigger Once</h3><p>After initializing all animations on a page, call ScrollTrigger.refresh() once.<br> This avoids layout glitches where triggers don’t line up after first render.</p><h3>The Payoff</h3><p>By centralizing GSAP and scoping each animation:</p><ul><li>Animations run instantly with no lag on route change</li><li>Memory leaks are eliminated</li><li>ScrollTriggers stay stable</li><li>Cleanups are predictable</li></ul><p>In short: <strong>fast, safe, and production-ready animations in Next.js 15</strong>.</p><p>With this setup, your GSAP animations won’t just look smooth — they’ll also scale smoothly with your Next.js app.</p><p>If you have any better solution or think mine can be improved, please reach out and let’s chat!</p><p>Thanks for reading :)</p><p>If you liked this article, feel free to connect with me!</p><ul><li><a href="https://helloimtom.dev/">https://helloimtom.dev/</a></li><li>Github: <a href="https://github.com/thomasaugot">https://github.com/thomasaugot</a></li><li>LinkedIn: <a href="https://www.linkedin.com/in/thomas-augot/">https://www.linkedin.com/in/thomas-augot/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ebaba7d0232" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build a multilingual 404 — not found Page in a Next.js 15 Internationalized App]]></title>
            <link>https://medium.com/@thomasaugot/how-to-build-a-multilingual-404-not-found-page-in-a-next-js-15-internationalized-app-a53f4be85096?source=rss-8df0d3754eb0------2</link>
            <guid isPermaLink="false">https://medium.com/p/a53f4be85096</guid>
            <category><![CDATA[404-not-found]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[internationalization]]></category>
            <category><![CDATA[nextjs-15]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Thomas Augot]]></dc:creator>
            <pubDate>Thu, 28 Aug 2025 12:29:38 GMT</pubDate>
            <atom:updated>2025-11-30T11:35:07.980Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Build a multilingual 404 — not found Page in a Next.js 15 Internationalized App</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t7_bYRyFelNmXcFYILAk8w.png" /></figure><p>If you’ve tried building an <strong>internationalized app</strong> with a [locale] dynamic segment in the App Router, you’ve probably discovered something frustrating:</p><p><strong>Next.js doesn’t render your </strong><strong>app/[locale]/not-found.tsx by default when users visit non-existent routes inside a locale.</strong></p><p>Instead, it often falls back to the <strong>root </strong><strong>app/not-found.tsx</strong>, which means your carefully translated 404 page never shows. After a lot of trial and error, I finally pieced together a working solution , and since I couldn’t find a single complete guide online, I’m writing this to save others the same pain.</p><h3>The Problem</h3><p>→ You have a folder structure like this:</p><pre>app/<br>  [locale]/<br>    page.tsx<br>    not-found.tsx<br>  not-found.tsx</pre><p>Visiting /es/random or /en/random should render the localized 404 (Página no encontrada vs Page not found).</p><p>But Next.js routes don’t know how to fall into [locale]/not-found.tsx automatically when a path is invalid.</p><h3>The Complete Solution</h3><p>The trick is to combine <strong>three parts</strong>:</p><ol><li><strong>Locale validation in the layout</strong> — reject unsupported locales.</li><li><strong>Catch-all route</strong> inside [locale] that forces notFound().</li><li><strong>Smart route translation utilities</strong> that generate locale-aware links (/es/contacto, /en/contact).</li></ol><p>Let’s go step by step.</p><h3>1) Locale Validation in the Layout</h3><p>In app/[locale]/layout.tsx, we need to explicitly whitelist supported locales and reject everything else.</p><pre>// app/[locale]/layout.tsx<br><br>import type { Metadata } from &quot;next&quot;;<br>import { notFound } from &quot;next/navigation&quot;;<br>import &quot;../globals.css&quot;;<br>import { TranslationProvider } from &quot;@/hooks/useTranslation&quot;;<br>import Navbar from &quot;@/components/layout/Navbar&quot;;<br>import Footer from &quot;@/components/layout/Footer&quot;;<br><br>const LOCALES = [&quot;es&quot;, &quot;en&quot;] as const;<br>type Locale = (typeof LOCALES)[number];<br><br>export const dynamicParams = false;<br>export function generateStaticParams() {<br>  return LOCALES.map((locale) =&gt; ({ locale }));<br>}<br><br>export default function LocaleLayout({<br>  children,<br>  params,<br>}: {<br>  children: React.ReactNode;<br>  params: { locale: string };<br>}) {<br>  const { locale } = params;<br>  if (!LOCALES.includes(locale as Locale)) notFound();<br><br> return (<br>    &lt;TranslationProvider locale={locale as Locale}&gt;<br>      &lt;Navbar /&gt;<br>      {children}<br>      &lt;Footer /&gt;<br>    &lt;/TranslationProvider&gt;<br>  );<br>}</pre><p>This ensures /fr/... or /de/... instantly 404 (in my use-case I work with /en/... and /es/...only).</p><h3>2) Localized 404 Page</h3><p>Next.js <strong>doesn’t automatically render</strong> app/[locale]/not-found.tsx unless you explicitly call notFound().<br>So we add a <strong>catch-all route</strong> that handles all unmatched paths inside a locale.</p><pre>// app/[locale]/[...slug]/page.tsx<br><br>import { notFound } from &quot;next/navigation&quot;;<br><br>export default function LocaleCatchAll() {<br>  notFound();<br>}</pre><p>Now, if a user visits /es/does-not-exist, this page is hit and calls notFound(), which triggers your <strong>localized 404 page</strong>.</p><pre>// app/[locale]/not-found.tsx<br><br>&quot;use client&quot;;<br><br>import Link from &quot;next/link&quot;;<br>import { useTranslation } from &quot;@/hooks/useTranslation&quot;;<br>import { getLocalizedRoute } from &quot;@/utils/navigation&quot;;<br><br>export default function NotFound() {<br>  const { t, language } = useTranslation();<br><br>return (<br>    &lt;section className=&quot;min-h-[60vh] grid place-items-center px-6 py-20 text-center&quot;&gt;<br>      &lt;div className=&quot;space-y-6&quot;&gt;<br>        &lt;p className=&quot;uppercase opacity-60&quot;&gt;{t(&quot;not-found.kicker&quot;)}&lt;/p&gt;<br>        &lt;h1 className=&quot;text-4xl md:text-6xl font-bold&quot;&gt;{t(&quot;not-found.title&quot;)}&lt;/h1&gt;<br>        &lt;p className=&quot;opacity-80&quot;&gt;{t(&quot;not-found.description&quot;)}&lt;/p&gt;<br>          &lt;div className=&quot;flex gap-4 justify-center pt-4&quot;&gt;<br>          &lt;Link href={getLocalizedRoute(&quot;/&quot;, language)} className=&quot;border px-4 py-2 rounded&quot;&gt;<br>            {t(&quot;not-found.go-home&quot;)}<br>          &lt;/Link&gt;<br>          &lt;Link href={getLocalizedRoute(&quot;contact&quot;, language)} className=&quot;border px-4 py-2 rounded&quot;&gt;<br>            {t(&quot;not-found.contact&quot;)}<br>          &lt;/Link&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/section&gt;<br>  );<br>}</pre><h3>3) Route Translation Utilities</h3><p>We want /en/contact vs /es/contacto. That requires a mapping system:</p><pre>// utils/routeTranslations.ts<br>export const routeTranslations = {<br>  es: {<br>    &quot;about-us&quot;: &quot;sobre-nosotros&quot;,<br>    services: &quot;servicios&quot;,<br>    contact: &quot;contacto&quot;,<br>  },<br>  en: {<br>    &quot;about-us&quot;: &quot;about-us&quot;,<br>    services: &quot;services&quot;,<br>    contact: &quot;contact&quot;,<br>  },<br>};<br><br>export const routeMapping = {<br>  &quot;sobre-nosotros&quot;: &quot;about-us&quot;,<br>  servicios: &quot;services&quot;,<br>  contacto: &quot;contact&quot;,<br>  &quot;about-us&quot;: &quot;sobre-nosotros&quot;,<br>  services: &quot;servicios&quot;,<br>  contact: &quot;contacto&quot;,<br>};<br><br>export const locales = [&quot;es&quot;, &quot;en&quot;] as const;<br>export const defaultLocale = &quot;es&quot; as const;<br>export type Language = (typeof locales)[number];</pre><p>And the helpers:</p><pre>// utils/navigation.ts<br><br>import { routeTranslations, routeMapping, type Language } from &quot;./routeTranslations&quot;;<br><br>function normalize(path: string) {<br>  return path.replace(/^\/+/, &quot;&quot;).replace(/\/+$/, &quot;&quot;);<br>}<br><br>export function getLocalizedRoute(route: string, language: Language): string {<br>  if (!route || route === &quot;/&quot;) return `/${language}`;<br>  const clean = normalize(route);<br>  const dict = routeTranslations[language] ?? {};<br>  const translated = (dict as Record&lt;string, string&gt;)[clean] ?? clean;<br>  return `/${language}/${translated}`.replace(/\/+/g, &quot;/&quot;);<br>}<br><br>export function getRouteForLanguageSwitch(currentRoute: string, target: Language): string {<br>  const clean = normalize(currentRoute);<br>  const parts = clean.split(&quot;/&quot;);<br>  const pathParts = parts[0] === &quot;es&quot; || parts[0] === &quot;en&quot; ? parts.slice(1) : parts;<br>  const mapped = pathParts.map((p) =&gt; routeMapping[p] ?? p).join(&quot;/&quot;);<br>  return `/${target}/${mapped}`.replace(/\/+/g, &quot;/&quot;);<br>}</pre><h3>4) Translation Provider</h3><p>Finally, we wrap everything in a provider that exposes both t() and language:</p><pre>&quot;use client&quot;;<br><br>import { createContext, useContext, useEffect, useState } from &quot;react&quot;;<br>import { usePathname } from &quot;next/navigation&quot;;<br>import { defaultLocale, type Language } from &quot;@/utils/routeTranslations&quot;;<br><br>const TranslationContext = createContext&lt;any&gt;(null);<br><br>export function TranslationProvider({<br>  children,<br>  locale,<br>}: {<br>  children: React.ReactNode;<br>  locale: Language;<br>}) {<br>  const pathname = usePathname();<br>  const [language, setLanguage] = useState&lt;Language&gt;(locale || defaultLocale);<br>  const [translations, setTranslations] = useState&lt;any&gt;({});<br><br>  useEffect(() =&gt; {<br>    import(`@/locales/${language}.json`).then((mod) =&gt;<br>      setTranslations(mod.default)<br>    );<br>  }, [language]);<br><br>  const t = (key: string) =&gt; {<br>    const keys = key.split(&quot;.&quot;);<br>    return keys.reduce((obj, k) =&gt; (obj &amp;&amp; obj[k] ? obj[k] : key), translations);<br>  };<br><br>  return (<br>    &lt;TranslationContext.Provider value={{ t, language }}&gt;<br>      {children}<br>    &lt;/TranslationContext.Provider&gt;<br>  );<br>}<br><br>export function useTranslation() {<br>  return useContext(TranslationContext);<br>}</pre><h3>Example in Action</h3><ul><li>/es/foobar → renders Spanish 404 with buttons → /es and /es/contacto</li><li>/en/foobar → renders English 404 with buttons → /en and /en/contact</li><li>/fr/foobar → rejected by layout → localized 404</li></ul><h3>Key Takeaways</h3><ol><li><strong>Next.js won’t render localized 404s automatically</strong> — you must use a [...slug] catch-all that calls notFound().</li><li>Always <strong>validate locales</strong> in the layout, or users can access unsupported routes.</li><li>A simple <strong>route translation system</strong> (routeTranslations + routeMapping) makes all your links language-aware.</li><li>Expose language via a provider so every component knows which locale it’s in.</li></ol><p>This pattern gives you a <strong>clean, future-proof 404 system</strong> for internationalized apps in Next.js 15. I struggled to find any documentation on this, so hopefully this guide saves you hours of debugging.</p><p>Next time you spin up a multilingual project, you’ll have a ready-made recipe for a professional 404 page that respects your locales!</p><p>Thanks for reading :)</p><p>If you liked this article, feel free to connect with me!</p><ul><li><a href="https://helloimtom.dev/">https://helloimtom.dev/</a></li><li>Github: <a href="https://github.com/thomasaugot">https://github.com/thomasaugot</a></li><li>LinkedIn: <a href="https://www.linkedin.com/in/thomas-augot/">https://www.linkedin.com/in/thomas-augot/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a53f4be85096" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How React Portals Saved Me From ScrollSmoother Modal Positioning Hell]]></title>
            <link>https://medium.com/@thomasaugot/how-react-portals-saved-me-from-scrollsmoother-modal-positioning-hell-2573eb74acea?source=rss-8df0d3754eb0------2</link>
            <guid isPermaLink="false">https://medium.com/p/2573eb74acea</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[scrollsmoother]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[gsap]]></category>
            <category><![CDATA[modal]]></category>
            <dc:creator><![CDATA[Thomas Augot]]></dc:creator>
            <pubDate>Thu, 14 Aug 2025 11:18:41 GMT</pubDate>
            <atom:updated>2025-11-30T11:35:43.977Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A practical solution to the positioning nightmare I faced when mixing GSAP ScrollSmoother with modals</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Sy_mN5tZ87rlsiPg" /></figure><h3>The problem: ScrollSmoother interferes with modal positioning</h3><p>Here is the situation: I spent hours perfecting a beautiful smooth scrolling website with GSAP’s ScrollSmoother. Everything feels buttery smooth, animations are crisp, and then… I needed to add a modal.</p><p>What should be a simple centered modal becomes a positioning nightmare:</p><ul><li>Modal jumps around as you scroll</li><li>Centering calculations get completely messed up</li><li>position: fixed elements behave unpredictably</li><li>The modal appears in random positions</li><li>A perfectly smooth site becomes a janky mess</li></ul><p>Even if the issue is very specific, I am pretty sure I am not going to be the only that ever faced it and here is my solution.</p><h3>Why ScrollSmoother Breaks Everything</h3><p>ScrollSmoother works by creating a virtual scroll environment that transforms the entire page content. While this creates amazing smooth scrolling effects, it also:</p><ol><li><strong>Transforms the coordinate system</strong> — Your position: fixed elements are no longer relative to the viewport</li><li><strong>Interferes with centering calculations</strong> — CSS transforms stack and compound unexpectedly</li><li><strong>Creates stacking context issues</strong> — Z-index behaviors become unpredictable</li><li><strong>Breaks viewport-relative positioning</strong> — vh and vw units don&#39;t behave as expected</li></ol><h3>The Traditional “Solutions” That Don’t Work</h3><p>Before discovering the portal solution, I tried everything:</p><h3>Attempt 1: Disable ScrollSmoother on Modal Open</h3><pre>// ❌ This doesn&#39;t work reliably<br><br>const openModal = () =&gt; {<br>  ScrollTrigger.killAll();<br>  document.body.classList.remove(&#39;smooth-scroll&#39;);<br>  setModalOpen(true);<br>};</pre><p><strong>Problem</strong>: ScrollSmoother’s transforms are already applied to the DOM, and simply disabling it doesn’t reset the positioning context.</p><h3>Attempt 2: Complex Position Calculations</h3><pre>// ❌ Overly complex and fragile<br><br>const openModal = () =&gt; {<br>  const scrollY = window.scrollY;<br>  document.body.style.position = &#39;fixed&#39;;<br>  document.body.style.top = `-${scrollY}px`;<br>  // ... more hacky positioning code<br>};</pre><p><strong>Problem</strong>: This causes scroll jumping and requires managing scroll position manually. It’s a maintenance nightmare.</p><h3>Attempt 3: Flexbox Centering</h3><pre>// ❌ Still affected by parent transforms<br><br>.modal {<br>  position: fixed;<br>  top: 0;<br>  left: 0;<br>  right: 0;<br>  bottom: 0;<br>  display: flex;<br>  align-items: center;<br>  justify-content: center;<br>}</pre><p><strong>Problem</strong>: When the parent container has transforms applied by ScrollSmoother, even “viewport-fixed” elements aren’t truly viewport-relative.</p><h3>The Solution: React Portals</h3><p>The breakthrough came when I realized the real issue: <strong>the modal was being rendered inside the ScrollSmoother-transformed container</strong>.</p><p>React Portals provide an escape hatch — they let you render components outside their normal DOM hierarchy.</p><p>Here’s how to implement it:</p><h3>Step 1: Import createPortal</h3><pre>import { createPortal } from &quot;react-dom&quot;;</pre><h3>Step 2: Set Up Portal Container</h3><pre>const MyComponent = () =&gt; {<br>  const [modalOpen, setModalOpen] = useState(false);<br>  const [portalContainer, setPortalContainer] = useState(null);</pre><pre>useEffect(() =&gt; {<br>    // Set portal target to document.body<br>    setPortalContainer(document.body);<br>  }, []);</pre><pre>  // ... rest of component<br>};</pre><h3>Step 3: Render Modal via Portal</h3><pre>return (<br>  &lt;div className=&quot;my-component&quot;&gt;<br>    {/* Your normal component content */}<br>    <br>    {/* Modal rendered via Portal - completely outside ScrollSmoother */}<br>    {modalOpen &amp;&amp; portalContainer &amp;&amp; createPortal(<br>      &lt;div className=&quot;modal-overlay&quot;&gt;<br>        &lt;div className=&quot;modal&quot;&gt;<br>          {/* Modal content */}<br>        &lt;/div&gt;<br>      &lt;/div&gt;,<br>      portalContainer<br>    )}<br>  &lt;/div&gt;<br>);</pre><h3>Step 4: Simple CSS Centering (That Actually Works!)</h3><pre>.modal-overlay {<br>  position: fixed;<br>  top: 0;<br>  left: 0;<br>  width: 100vw;<br>  height: 100vh;<br>  background: rgba(0, 0, 0, 0.8);<br>  z-index: 9999;<br>}<br><br>.modal {<br>  position: fixed;<br>  top: 50vh;<br>  left: 50vw;<br>  transform: translate(-50%, -50%);<br>  background: white;<br>  border-radius: 12px;<br>  // Perfect centering, every time! 🎉<br>}</pre><h3>Why This Works Like Magic</h3><p>When you use createPortal(modalJSX, document.body):</p><ol><li><strong>Escapes the transform context</strong> — Modal renders directly to document.body, outside any ScrollSmoother containers. I usually wrap the page component with the Scrollsmoother, and the body is outside of it… perfect :)</li><li><strong>Restores normal positioning</strong> — position: fixed behaves relative to the actual viewport again</li><li><strong>Reliable centering</strong> — CSS transforms work predictably without interference</li><li><strong>No scroll jumping</strong> — Page content remains untouched</li><li><strong>Clean separation</strong> — Modal logic is isolated from the main component tree</li></ol><h3>Real-World Example</h3><p>Here’s a complete implementation from a production project:</p><pre>const BrandGrid = () =&gt; {<br>  const [modalOpen, setModalOpen] = useState(false);<br>  const [activeBrand, setActiveBrand] = useState(null);<br>  const [portalContainer, setPortalContainer] = useState(null);<br><br>useEffect(() =&gt; {<br>    setPortalContainer(document.body);<br>  }, []);<br><br>  const openModal = (brand) =&gt; {<br>    setActiveBrand(brand);<br>    setModalOpen(true);<br>    // No need to mess with ScrollSmoother! <br>  };<br><br>  const closeModal = () =&gt; {<br>    setModalOpen(false);<br>    setActiveBrand(null);<br>    // No cleanup needed! <br>  };<br><br>  return (<br>    &lt;div className=&quot;brand-grid&quot;&gt;<br>      {brands.map(brand =&gt; (<br>        &lt;div <br>          key={brand.id}<br>          onClick={() =&gt; openModal(brand)}<br>          onMouseEnter={() =&gt; openModal(brand)} // Desktop hover<br>        &gt;<br>          &lt;img src={brand.logo} alt={brand.name} /&gt;<br>        &lt;/div&gt;<br>      ))}<br>      {/* The magic portal modal */}<br>      {modalOpen &amp;&amp; activeBrand &amp;&amp; portalContainer &amp;&amp; createPortal(<br>        &lt;div <br>          className=&quot;modal-overlay&quot;<br>          onClick={closeModal}<br>        &gt;<br>          &lt;div <br>            className=&quot;modal&quot;<br>            onMouseLeave={closeModal} // Desktop hover out<br>          &gt;<br>            &lt;h3&gt;All {activeBrand.name} Brands&lt;/h3&gt;<br>            &lt;div className=&quot;brand-grid&quot;&gt;<br>              {activeBrand.subBrands.map(subBrand =&gt; (<br>                &lt;div key={subBrand.id}&gt;<br>                  &lt;img src={subBrand.logo} alt={subBrand.name} /&gt;<br>                  &lt;span&gt;{subBrand.name}&lt;/span&gt;<br>                &lt;/div&gt;<br>              ))}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;,<br>        portalContainer<br>      )}<br>    &lt;/div&gt;<br>  );<br>};</pre><h3>The Results</h3><ul><li>✅ <strong>Perfect centering</strong> — Modal appears exactly in viewport center</li><li>✅ <strong>No scroll jumping</strong> — Page stays exactly where user was</li><li>✅ <strong>Smooth interactions</strong> — Hover/click works flawlessly</li><li>✅ <strong>Mobile friendly</strong> — Responsive without positioning issues</li><li>✅ <strong>Maintainable</strong> — Clean, simple code</li><li>✅ <strong>Performance</strong> — No complex calculations or DOM manipulation</li></ul><h3>Beyond ScrollSmoother: Other Use Cases</h3><p>This portal technique solves modal positioning issues with other libraries too:</p><ul><li><strong>Framer Motion</strong> page transitions</li><li><strong>AOS (Animate On Scroll)</strong> transforms</li><li><strong>Custom CSS transforms</strong> on container elements</li><li><strong>Complex layout containers</strong> with overflow settings</li></ul><h3>Key Takeaways</h3><ol><li><strong>Identify the root cause</strong> — Modal positioning issues often stem from parent transform contexts</li><li><strong>Think outside the box</strong> — Sometimes the solution isn’t fixing the CSS, but changing where the element renders</li><li><strong>Use React Portals</strong> — They’re not just for modals, but for any element that needs to escape its normal DOM hierarchy</li><li><strong>Keep it simple</strong> — The best solutions often involve less code, not more</li></ol><p>After hours of fighting with complex positioning calculations and hacky workarounds that even chatGPT or Claude.ai wouldn’t ever fix for me, I suddenly remembered about React Portals and they provided an elegant solution that just works. Sometimes the best way to solve a problem isn’t to fight it head-on, but to step outside the problem space entirely.</p><p>Next time you’re battling modal positioning issues with ScrollSmoother (or any transform-heavy library), remember: don’t fight the transforms, escape them.</p><p>Thanks for reading :)</p><p>If you liked this article, feel free to connect with me!</p><ul><li><a href="https://helloimtom.dev/">https://helloimtom.dev/</a></li><li>Github: <a href="https://github.com/thomasaugot">https://github.com/thomasaugot</a></li><li>LinkedIn: <a href="https://www.linkedin.com/in/thomas-augot/">https://www.linkedin.com/in/thomas-augot/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2573eb74acea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Next.js 15 App Router Internationalization with URL-Based Routing]]></title>
            <link>https://medium.com/@thomasaugot/next-js-15-app-router-internationalization-with-url-based-routing-7e49413dc7c1?source=rss-8df0d3754eb0------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e49413dc7c1</guid>
            <category><![CDATA[nextjs-15]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[multilingual-websites]]></category>
            <category><![CDATA[app-router]]></category>
            <category><![CDATA[i18n]]></category>
            <dc:creator><![CDATA[Thomas Augot]]></dc:creator>
            <pubDate>Thu, 10 Jul 2025 09:53:45 GMT</pubDate>
            <atom:updated>2025-11-30T11:36:05.300Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j4he7e1udMH3ScOipC9eiQ.png" /></figure><p>Building a truly bilingual website requires more than just translating text. Users expect URLs to reflect their language preference, maintain consistency across navigation, and provide a seamless experience. In this guide, I’ll walk you through implementing a complete internationalization (i18n) solution for Next.js 15 using App Router.</p><h3>What We’ll Build</h3><p>By the end of this tutorial, you’ll have:</p><ul><li><strong>URL-based language routing</strong>: /es/servicios vs /en/services</li><li><strong>Persistent language selection</strong>: Language choice survives navigation</li><li><strong>No page reloads</strong>: Smooth language switching</li><li><strong>Centralized route management</strong>: Single source of truth for translations</li><li><strong>SEO-friendly URLs</strong>: Different URLs for different languages</li></ul><h3>The Challenge with App Router</h3><p>Next.js 15’s App Router doesn’t support the traditional i18n config from Pages Router. The old approach looked like this:</p><pre>// ❌ This doesn&#39;t work in App Router<br>const nextConfig = {<br>  i18n: {<br>    locales: [&#39;es&#39;, &#39;en&#39;],<br>    defaultLocale: &#39;es&#39;,<br>  },<br>}</pre><p>Instead, we need to build our own solution using middleware and dynamic routes.</p><h3>Step 1: Project Structure Setup</h3><p>First, restructure your project to support locale-based routing, we need to create duplicate route folders in each language desired, here I do english and spanish. The main page.tsx and layout.tsx files are also moved in the [locale] folder. Be careful, the middleware file goes at root level, not in the app/ folder:</p><pre>your-project/<br>├── app/<br>│   ├── [locale]/          # Dynamic locale folder<br>│   │   ├── layout.tsx     # Layout for all localized pages<br>│   │   ├── page.tsx       # Homepage<br>│   │   ├── servicios/     # Spanish routes<br>│   │   ├── services/      # English routes<br>│   │   ├── contacto/      # Spanish contact<br>│   │   └── contact/       # English contact<br>│   └── globals.css        # Global styles<br>├── middleware.ts          # Route handling logic (ROOT LEVEL)<br>├── utils/<br>├── components/<br>├── next.config.ts<br>└── package.json</pre><h3>Step 2: Create Shared Route Configuration</h3><p>I usually try to keep things organized and clean. So I create a centralized file for route translations to avoid code duplication:</p><pre>// utils/routeTranslations.ts<br><br>export const routeTranslations = {<br>  es: {<br>    services: &quot;servicios&quot;,<br>    contact: &quot;contacto&quot;,<br>    &quot;about-us&quot;: &quot;sobre-nosotros&quot;,<br>    &quot;use-cases&quot;: &quot;casos-de-exito&quot;,<br>  },<br>  en: {<br>    servicios: &quot;services&quot;,<br>    contacto: &quot;contact&quot;,<br>    &quot;sobre-nosotros&quot;: &quot;about-us&quot;,<br>    &quot;casos-de-exito&quot;: &quot;use-cases&quot;,<br>  },<br>};<br><br>export const locales = [&quot;es&quot;, &quot;en&quot;] as const;<br>export const defaultLocale = &quot;es&quot; as const;<br>export type Language = typeof locales[number];</pre><h3>Step 3: Implement Middleware for Route Handling</h3><p>The middleware handles automatic locale detection and URL redirects:</p><pre>// middleware.ts<br>import { NextResponse } from &quot;next/server&quot;;<br>import type { NextRequest } from &quot;next/server&quot;;<br>import { locales, defaultLocale } from &quot;./utils/routeTranslations&quot;;<br><br>function getLocale(request: NextRequest): string {<br>  const pathname = request.nextUrl.pathname;<br>  const pathnameHasLocale = locales.some(<br>    (locale) =&gt; pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`<br>  );<br><br>if (pathnameHasLocale) {<br>    return pathname.split(&quot;/&quot;)[1];<br>  }<br><br>// Check browser language preference<br>  const acceptLanguage = request.headers.get(&quot;Accept-Language&quot;);<br>  if (acceptLanguage?.includes(&quot;en&quot;)) {<br>    return &quot;en&quot;;<br>  }<br><br>  return defaultLocale;<br>}<br><br>export function middleware(request: NextRequest) {<br>  const pathname = request.nextUrl.pathname;<br><br>// Check if pathname already has a locale<br>  const pathnameHasLocale = locales.some(<br>    (locale) =&gt; pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`<br>  );<br><br> if (pathnameHasLocale) return;<br><br>// Redirect if there is no locale<br>  const locale = getLocale(request);<br>  request.nextUrl.pathname = `/${locale}${pathname}`;<br><br>return NextResponse.redirect(request.nextUrl);<br>}<br><br>export const config = {<br>  matcher: [<br>    &quot;/((?!_next|api|favicon.ico|.*\\..*).*)&quot;,<br>  ],<br>};</pre><h3>Step 4: Build the Translation Provider</h3><p>Create a context provider that handles translations and URL routing:</p><pre>// hooks/useTranslation.tsx<br><br>&quot;use client&quot;;<br><br>import { createContext, useContext, useState, useEffect } from &quot;react&quot;;<br>import { usePathname } from &quot;next/navigation&quot;;<br>import { routeTranslations, defaultLocale, type Language } from &quot;@/utils/routeTranslations&quot;;<br><br>interface TranslationContextType {<br>  t: (key: string) =&gt; string;<br>  language: Language;<br>  changeLanguage: (newLanguage: Language) =&gt; void;<br>  toggleLanguage: () =&gt; void;<br>}<br><br>const TranslationContext = createContext&lt;TranslationContextType | undefined&gt;(undefined);<br><br>export function TranslationProvider({ children }: { children: React.ReactNode }) {<br>  const pathname = usePathname();<br>  <br>  const [language, setLanguage] = useState&lt;Language&gt;(() =&gt; {<br>    // Try localStorage first, then URL, then default<br>    if (typeof window !== &#39;undefined&#39;) {<br>      const saved = localStorage.getItem(&#39;preferred-language&#39;) as Language;<br>      if (saved &amp;&amp; (saved === &#39;es&#39; || saved === &#39;en&#39;)) {<br>        return saved;<br>      }<br>    }<br>    const currentLocale = pathname.split(&#39;/&#39;)[1] as Language;<br>    return currentLocale || defaultLocale;<br>  });<br><br>const [translations, setTranslations] = useState&lt;any&gt;({});<br><br>const loadTranslations = async (lang: Language) =&gt; {<br>    try {<br>      const response = await import(`@/locales/${lang}.json`);<br>      setTranslations(response.default);<br>    } catch (error) {<br>      console.error(`Failed to load translations for ${lang}:`, error);<br>    }<br>  };<br><br>// Update language when URL changes<br>  useEffect(() =&gt; {<br>    const urlLocale = pathname.split(&#39;/&#39;)[1] as Language;<br>    if (urlLocale &amp;&amp; (urlLocale === &#39;es&#39; || urlLocale === &#39;en&#39;)) {<br>      if (urlLocale !== language) {<br>        setLanguage(urlLocale);<br>        if (typeof window !== &#39;undefined&#39;) {<br>          localStorage.setItem(&#39;preferred-language&#39;, urlLocale);<br>        }<br>      }<br>    }<br>  }, [pathname, language]);<br><br>useEffect(() =&gt; {<br>    loadTranslations(language);<br>  }, [language]);<br><br>const t = (key: string): string =&gt; {<br>    const keys = key.split(&quot;.&quot;);<br>    let value: any = translations;<br><br>for (const k of keys) {<br>      if (value &amp;&amp; typeof value === &quot;object&quot; &amp;&amp; k in value) {<br>        value = value[k];<br>      } else {<br>        return key;<br>      }<br>    }<br><br>return typeof value === &quot;string&quot; ? value : key;<br>  };<br><br>const translateRoute = (currentPath: string, targetLang: Language): string =&gt; {<br>    const pathWithoutLocale = currentPath.replace(/^\/[a-z]{2}/, &#39;&#39;) || &#39;/&#39;;<br>    const segments = pathWithoutLocale.split(&#39;/&#39;).filter(Boolean);<br>    <br>    if (segments.length === 0) {<br>      return `/${targetLang}`;<br>    }<br><br>const mainRoute = segments[0];<br>    const translations = routeTranslations[targetLang];<br>    const translatedRoute = translations[mainRoute as keyof typeof translations] || mainRoute;<br>    <br>    const remainingSegments = segments.slice(1);<br>    const newPath = `/${targetLang}/${translatedRoute}${remainingSegments.length &gt; 0 ? &#39;/&#39; + remainingSegments.join(&#39;/&#39;) : &#39;&#39;}`;<br>    <br>    return newPath;<br>  };<br><br> const changeLanguage = async (newLanguage: Language) =&gt; {<br>    const newPath = translateRoute(pathname, newLanguage);<br>    // Use history API to avoid page reload<br>    window.history.replaceState({}, &#39;&#39;, newPath);<br>    setLanguage(newLanguage);<br>    <br>    if (typeof window !== &#39;undefined&#39;) {<br>      localStorage.setItem(&#39;preferred-language&#39;, newLanguage);<br>    }<br>  };<br><br>const toggleLanguage = async () =&gt; {<br>    const newLang = language === &quot;es&quot; ? &quot;en&quot; : &quot;es&quot;;<br>    changeLanguage(newLang);<br>  };<br><br>return (<br>    &lt;TranslationContext.Provider<br>      value={{ t, language, changeLanguage, toggleLanguage }}<br>    &gt;<br>      {children}<br>    &lt;/TranslationContext.Provider&gt;<br>  );<br>}<br><br>export function useTranslation() {<br>  const context = useContext(TranslationContext);<br>  if (!context) {<br>    throw new Error(&quot;useTranslation must be used within a TranslationProvider&quot;);<br>  }<br>  return context;<br>}</pre><h3>Step 5: Create Navigation Helpers</h3><p>Build helpers to generate localized URLs for navigation:</p><pre>// utils/navigation.ts<br>import { routeTranslations, type Language } from &quot;./routeTranslations&quot;;<br><br>export function getLocalizedRoute(route: string, language: Language): string {<br>  if (!route || route === &#39;&#39;) {<br>    return `/${language}`;<br>  }<br>  <br>  const translations = routeTranslations[language];<br>  const translatedRoute = translations[route as keyof typeof translations] || route;<br>  <br>  return `/${language}/${translatedRoute}`;<br>}</pre><h3>Step 6: Update Navigation Data Structure</h3><p>Modify your navigation data to work with dynamic languages. If you aren’t using a separate data file you can also do that directly in your navbar component for example. Here I choose once again to separate my data for a cleaner code:</p><pre>// data/menu.ts<br>import { getLocalizedRoute } from &quot;@/utils/navigation&quot;;<br>import type { Language } from &quot;@/utils/routeTranslations&quot;;<br><br>export interface MenuItem {<br>  route: string; // Base route without language prefix<br>  labelKey: string;<br>}<br><br>export const navigationItems: MenuItem[] = [<br>  { route: &quot;&quot;, labelKey: &quot;nav.home&quot; },<br>  { route: &quot;sobre-nosotros&quot;, labelKey: &quot;nav.about&quot; },<br>  { route: &quot;servicios&quot;, labelKey: &quot;nav.services&quot; },<br>  { route: &quot;casos-de-exito&quot;, labelKey: &quot;nav.cases&quot; },<br>  { route: &quot;contacto&quot;, labelKey: &quot;nav.contact&quot; },<br>];<br><br>export function getLocalizedNavigationItems(language: Language): Array&lt;MenuItem &amp; { href: string }&gt; {<br>  return navigationItems.map(item =&gt; ({<br>    ...item,<br>    href: getLocalizedRoute(item.route, language)<br>  }));<br>}</pre><h3>Step 7: Update Layout for Locale Support</h3><p>Create the layout that receives the locale parameter and wrap it all with your &lt;TranslationProvider&gt; :</p><pre>// app/[locale]/layout.tsx<br>import type { Metadata } from &quot;next&quot;;<br>import &quot;../globals.css&quot;;<br>import { TranslationProvider } from &quot;@/hooks/useTranslation&quot;;<br>import Navbar from &quot;@/components/layout/Navbar&quot;;<br>import Footer from &quot;@/components/layout/Footer&quot;;<br><br>export default function LocaleLayout({<br>  children,<br>  params,<br>}: {<br>  children: React.ReactNode;<br>  params: { locale: string };<br>}) {<br>  return (<br>    &lt;html lang={params.locale}&gt;<br>      &lt;body className=&quot;antialiased&quot;&gt;<br>        &lt;TranslationProvider&gt;<br>          &lt;Navbar /&gt;<br>          {children}<br>          &lt;Footer /&gt;<br>        &lt;/TranslationProvider&gt;<br>      &lt;/body&gt;<br>    &lt;/html&gt;<br>  );<br>}</pre><h3>Step 8: Implement Language-Aware Navigation</h3><p>Update your navigation component to use localized routes:</p><pre>// In your Navbar component<br>import { getLocalizedNavigationItems } from &quot;@/data/menu&quot;;<br>import { getLocalizedRoute } from &quot;@/utils/navigation&quot;;<br><br>export default function Navbar() {<br>  const { t, language, toggleLanguage } = useTranslation();<br>  const localizedNavItems = getLocalizedNavigationItems(language);<br><br>return (<br>    &lt;nav&gt;<br>      {/* Logo with localized home link */}<br>      &lt;Link href={getLocalizedRoute(&#39;&#39;, language)}&gt;<br>        &lt;img src=&quot;/logo.png&quot; alt=&quot;Logo&quot; /&gt;<br>      &lt;/Link&gt;<br><br>{/* Navigation items */}<br>      {localizedNavItems.map((item) =&gt; (<br>        &lt;Link key={item.href} href={item.href}&gt;<br>          {t(item.labelKey)}<br>        &lt;/Link&gt;<br>      ))}<br><br>{/* Language switcher */}<br>      &lt;button onClick={toggleLanguage}&gt;<br>        {language.toUpperCase()}<br>      &lt;/button&gt;<br>    &lt;/nav&gt;<br>  );<br>}</pre><h3>Key Benefits of This Approach</h3><p><strong>SEO-Friendly</strong>: Each language has unique URLs that search engines can index</p><p><strong>User Experience</strong>: Language persists across navigation and browser sessions</p><p><strong>No Page Reloads</strong>: Language switching feels instant</p><p><strong>Maintainable</strong>: Single source of truth for route translations</p><p><strong>Scalable</strong>: Easy to add new languages or routes</p><h3>Translation Files Structure</h3><p>Create your translation files in the locales folder:</p><pre>// locales/es.json<br>{<br>  &quot;nav&quot;: {<br>    &quot;home&quot;: &quot;Inicio&quot;,<br>    &quot;about&quot;: &quot;Sobre Nosotros&quot;,<br>    &quot;services&quot;: &quot;Servicios&quot;,<br>    &quot;contact&quot;: &quot;Contacto&quot;<br>  },<br>  &quot;hero&quot;: {<br>    &quot;title&quot;: &quot;Transformamos negocios&quot;<br>  }<br>}<br><br>// locales/en.json<br>{<br>  &quot;nav&quot;: {<br>    &quot;home&quot;: &quot;Home&quot;,<br>    &quot;about&quot;: &quot;About Us&quot;, <br>    &quot;services&quot;: &quot;Services&quot;,<br>    &quot;contact&quot;: &quot;Contact&quot;<br>  },<br>  &quot;hero&quot;: {<br>    &quot;title&quot;: &quot;We transform businesses&quot;<br>  }<br>}</pre><h3>Final Results</h3><p>With this implementation, you get:</p><ul><li><strong>Spanish URLs</strong>: yoursite.com/es/servicios</li><li><strong>English URLs</strong>: yoursite.com/en/services</li><li><strong>Automatic redirects</strong>: yoursite.com/ → yoursite.com/es/</li><li><strong>Language persistence</strong>: Choice survives navigation</li><li><strong>Smooth switching</strong>: No page reloads when changing languages</li></ul><p>Building internationalization for Next.js 15 App Router requires more manual setup than the old Pages Router, but the result is a more flexible and maintainable solution. This approach gives you complete control over URL structure while maintaining excellent user experience and SEO benefits.</p><p>The key is treating routes as translatable content and using middleware to handle the complexity behind the scenes. With proper setup, users get a seamless bilingual experience that feels native in both languages.</p><p><em>This implementation has been tested with Next.js 15, TypeScript, and Tailwind CSS. The code is production-ready and handles edge cases like browser language detection and localStorage persistence.</em></p><p>Thanks for reading :)</p><p>If you liked this article, feel free to connect with me!</p><ul><li><a href="https://helloimtom.dev/">https://helloimtom.dev/</a></li><li>Github: <a href="https://github.com/thomasaugot">https://github.com/thomasaugot</a></li><li>LinkedIn: <a href="https://www.linkedin.com/in/thomas-augot/">https://www.linkedin.com/in/thomas-augot/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e49413dc7c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Complete Guide to SEO Optimization in Next.js 16 — Updated April 2026]]></title>
            <link>https://medium.com/@thomasaugot/the-complete-guide-to-seo-optimization-in-next-js-15-1bdb118cffd7?source=rss-8df0d3754eb0------2</link>
            <guid isPermaLink="false">https://medium.com/p/1bdb118cffd7</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[nextjs-15]]></category>
            <category><![CDATA[seo]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Thomas Augot]]></dc:creator>
            <pubDate>Thu, 22 May 2025 15:54:09 GMT</pubDate>
            <atom:updated>2026-04-15T11:04:33.736Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How I transformed a company website into an SEO powerhouse using Next.js App Router’s latest features</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PkKr7dTPWi9B_gRwDWnX7g.png" /></figure><p>Search Engine Optimization (SEO) can make or break your website’s online presence. With Next.js 16’s powerful new features, creating an SEO-optimized website has never been easier and has solved many issues React faces; if you know what you’re doing.</p><p>In this comprehensive guide, I’ll walk you through everything I learned while optimizing a commercial interior design company website for search engines. We’ll cover everything from basic metadata to advanced structured data, and I’ll show you exactly what code to write and why.</p><h3>Understanding Next.js 16 SEO Foundations</h3><h4>The New Metadata API</h4><p>Next.js 16 introduced a revolutionary way to handle SEO through the Metadata API. Gone are the days of manually managing &lt;head&gt; tags, now everything is handled through simple JavaScript objects.</p><p>Here’s the basic structure:</p><pre>// app/layout.tsx<br>import { Metadata } from &quot;next&quot;;<br><br>export const metadata: Metadata = {<br>  title: {<br>    default: &quot;Your Business Name | What You Do&quot;,<br>    template: &quot;%s | Your Business Name&quot;, // Creates &quot;Page Name | Your Business Name&quot;<br>  },<br>  description: &quot;Your compelling business description with keywords&quot;,<br>};</pre><h4>Why This Matters</h4><p>The Metadata API isn’t just syntactic sugar , it provides several crucial advantages:</p><ol><li><strong>Type Safety</strong>: TypeScript ensures you never miss required fields</li><li><strong>Automatic Optimization</strong>: Next.js handles meta tag placement and deduplication</li><li><strong>Dynamic Generation</strong>: Perfect for blogs, e-commerce, and content sites</li><li><strong>Template System</strong>: Consistent branding across all pages</li></ol><p><strong>Single Source of Truth for Your URL</strong></p><p>Before writing any metadata, create one file that every other file imports. Never hardcode your domain anywhere else.</p><pre>// config/site.ts<br>export const SITE_URL  = process.env.NEXT_PUBLIC_SITE_URL ?? &#39;https://yourdomain.com&#39;<br>export const SITE_NAME = &#39;Your Business Name&#39;</pre><p>Then in every file that needs it:</p><pre>import { SITE_URL, SITE_NAME } from &#39;@/config/site&#39;</pre><p>This way, if your domain ever changes, you update it in one place and it propagates everywhere — metadata, sitemap, robots, structured data.</p><h3>Building a Bulletproof Root Layout</h3><p>Your root layout (app/layout.tsx) is the foundation of your entire SEO strategy. Here&#39;s how to structure it properly:</p><pre>import type { Metadata, Viewport } from &quot;next&quot;;<br>import localFont from &quot;next/font/local&quot;;<br><br>const customFont = localFont({<br>  variable: &quot;--font-primary&quot;,<br>  display: &quot;swap&quot;, // Critical for performance<br>  src: [<br>    {<br>      path: &quot;../public/fonts/font-regular.woff2&quot;,<br>      weight: &quot;400&quot;,<br>      style: &quot;normal&quot;,<br>    },<br>    {<br>      path: &quot;../public/fonts/font-bold.woff2&quot;,<br>      weight: &quot;700&quot;,<br>      style: &quot;normal&quot;,<br>    },<br>  ],<br>});<br><br>export const viewport: Viewport = {<br>  themeColor: &#39;#your-brand-color&#39;,<br>}<br><br>export const metadata: Metadata = {<br>  metadataBase: new URL(&quot;https://yourdomain.com/&quot;),<br>  title: {<br>    default: &quot;Your Business | Professional Service Description&quot;,<br>    template: &quot;%s | Your Business Name&quot;,<br>  },<br>  description: &quot;Compelling description with location and services. Include your main keywords naturally while staying under 160 characters.&quot;,<br>  authors: [{ name: &quot;Your Business Name&quot; }],<br>  creator: &quot;Your Business Name&quot;,<br>  publisher: &quot;Your Business Name&quot;,<br>  robots: {<br>    index: true,<br>    follow: true,<br>    googleBot: {<br>      index: true,<br>      follow: true,<br>      &#39;max-video-preview&#39;: -1,<br>      &#39;max-image-preview&#39;: &#39;large&#39;,<br>      &#39;max-snippet&#39;: -1,<br>    },<br>  },<br>  openGraph: {<br>    type: &quot;website&quot;,<br>    locale: &quot;en_US&quot;, // or &quot;es_ES&quot; for Spanish<br>    url: &quot;https://yourdomain.com&quot;,<br>    title: &quot;Your Business - Professional Service&quot;,<br>    description: &quot;Engaging description for social media sharing&quot;,<br>    images: [<br>      {<br>        url: &quot;/hero-image.jpg&quot;,<br>        width: 1200,<br>        height: 630,<br>        alt: &quot;Descriptive alt text for your main image&quot;,<br>      },<br>    ],<br>    siteName: &quot;Your Business Name&quot;,<br>  },<br>  twitter: {<br>    card: &#39;summary_large_image&#39;,<br>    title: &#39;Your Business - Professional Service&#39;,<br>    description: &#39;Engaging description for Twitter sharing&#39;,<br>    images: [&#39;/hero-image.jpg&#39;],<br>  },<br>  alternates: {<br>    canonical: &quot;https://yourdomain.com&quot;,<br>  },<br>};</pre><p><strong>Breaking change since Next.js 15 (applies to 16+): </strong>themeColor (and colorScheme, width, initialScale) must be exported separately via viewport, not inside metadata. Putting it in metadata.other will trigger a warning and may be ignored.</p><h4>The Critical Parts Explained</h4><ol><li><strong>metadataBase</strong>: Essential for relative URLs to work properly</li><li><strong>title.template</strong>: Automatically adds your brand to every page</li><li><strong>robots configuration</strong>: Fine-tuned control over search engine behavior</li><li><strong>OpenGraph + Twitter</strong>: Optimized social media sharing</li><li><strong>canonical</strong>: Prevents duplicate content issues</li></ol><h3>Structured Data: Speaking Google’s Language</h3><p>Structured data is how you tell search engines exactly what your content means. It’s the difference between Google guessing what your business does and Google knowing what your business does.</p><h4>Organization Schema</h4><p>Every business website needs this basic schema:</p><pre>// Add this to your root layout&#39;s &lt;head&gt;<br>&lt;script<br>  type=&quot;application/ld+json&quot;<br>  dangerouslySetInnerHTML={{<br>    __html: JSON.stringify({<br>      &quot;@context&quot;: &quot;https://schema.org&quot;,<br>      &quot;@type&quot;: &quot;Organization&quot;,<br>      &quot;@id&quot;: &quot;https://yourdomain.com/#organization&quot;,<br>      &quot;name&quot;: &quot;Your Business Name&quot;,<br>      &quot;url&quot;: &quot;https://yourdomain.com&quot;,<br>      &quot;sameAs&quot;: [<br>        &quot;https://www.instagram.com/yourbusiness&quot;,<br>        &quot;https://www.linkedin.com/company/yourbusiness&quot;<br>       ],<br>      &quot;logo&quot;: {<br>        &quot;@type&quot;: &quot;ImageObject&quot;,<br>        &quot;url&quot;: &quot;https://yourdomain.com/logo.png&quot;,<br>        &quot;width&quot;: 800,<br>        &quot;height&quot;: 600<br>      },<br>      &quot;description&quot;: &quot;What your business does and specializes in&quot;,<br>      &quot;foundingDate&quot;: &quot;2020&quot;, // Your founding year<br>      &quot;numberOfEmployees&quot;: {<br>        &quot;@type&quot;: &quot;QuantitativeValue&quot;,<br>        &quot;value&quot;: &quot;10-50&quot; // Adjust to your size<br>      },<br>      &quot;address&quot;: {<br>        &quot;@type&quot;: &quot;PostalAddress&quot;,<br>        &quot;addressLocality&quot;: &quot;Your City&quot;,<br>        &quot;addressRegion&quot;: &quot;Your State&quot;,<br>        &quot;addressCountry&quot;: &quot;US&quot;<br>      },<br>      &quot;areaServed&quot;: [<br>        {<br>          &quot;@type&quot;: &quot;Place&quot;,<br>          &quot;name&quot;: &quot;Your Primary Market&quot;<br>        },<br>        {<br>          &quot;@type&quot;: &quot;Place&quot;,<br>          &quot;name&quot;: &quot;Your Secondary Market&quot;<br>        }<br>      ],<br>      &quot;serviceType&quot;: [<br>        &quot;Service 1&quot;,<br>        &quot;Service 2&quot;,<br>        &quot;Service 3&quot;<br>      ]<br>    })<br>  }}<br>/&gt;</pre><h4>Website Schema</h4><p>This tells search engines about your site structure:</p><pre>&lt;script<br>  type=&quot;application/ld+json&quot;<br>  dangerouslySetInnerHTML={{<br>    __html: JSON.stringify({<br>      &quot;@context&quot;: &quot;https://schema.org&quot;,<br>      &quot;@type&quot;: &quot;WebSite&quot;,<br>      &quot;@id&quot;: &quot;https://yourdomain.com/#website&quot;,<br>      &quot;url&quot;: &quot;https://yourdomain.com&quot;,<br>      &quot;name&quot;: &quot;Your Business Name&quot;,<br>      &quot;description&quot;: &quot;Brief description of your website&quot;,<br>      &quot;publisher&quot;: {<br>        &quot;@id&quot;: &quot;https://yourdomain.com/#organization&quot;<br>      },<br>      &quot;inLanguage&quot;: [&quot;en-US&quot;, &quot;es-ES&quot;]<br>    })<br>  }}<br>/&gt;</pre><p><strong>Note:</strong> If your site is multilingual, inLanguage should be an array listing all supported languages. A single string tells Google your site is monolingual.</p><h3>→ The Two Missing Pieces Most Developers Forget ←</h3><h3>Sitemap Generation</h3><p>Your sitemap is like a roadmap that tells search engines about all your pages, how important they are, and how often they change. Next.js makes creating dynamic, professional sitemaps incredibly easy.</p><h4>Basic Sitemap Setup</h4><p>Create an app/sitemap.ts file for automatic sitemap generation:</p><pre>// app/sitemap.ts<br>import { MetadataRoute } from &#39;next&#39;<br><br>export default function sitemap(): MetadataRoute.Sitemap {<br>  const baseUrl = &#39;https://yourdomain.com&#39;<br>  <br>  return [<br>    {<br>      url: baseUrl,<br>      lastModified: new Date(),<br>      changeFrequency: &#39;weekly&#39;,<br>      priority: 1,<br>    },<br>    {<br>      url: `${baseUrl}/about`,<br>      lastModified: new Date(),<br>      changeFrequency: &#39;monthly&#39;,<br>      priority: 0.9,<br>    },<br>    {<br>      url: `${baseUrl}/services`,<br>      lastModified: new Date(),<br>      changeFrequency: &#39;monthly&#39;,<br>      priority: 0.9,<br>    },<br>    {<br>      url: `${baseUrl}/portfolio`,<br>      lastModified: new Date(),<br>      changeFrequency: &#39;weekly&#39;,<br>      priority: 0.8,<br>    },<br>    {<br>      url: `${baseUrl}/contact`,<br>      lastModified: new Date(),<br>      changeFrequency: &#39;monthly&#39;,<br>      priority: 0.7,<br>    },<br>  ]<br>}</pre><p>This automatically generates a sitemap at /sitemap.xml that looks like:</p><pre>&lt;urlset xmlns=&quot;http://www.sitemaps.org/schemas/sitemap/0.9&quot;&gt;<br>  &lt;url&gt;<br>    &lt;loc&gt;https://yourdomain.com&lt;/loc&gt;<br>    &lt;lastmod&gt;2024-01-15&lt;/lastmod&gt;<br>    &lt;changefreq&gt;weekly&lt;/changefreq&gt;<br>    &lt;priority&gt;1&lt;/priority&gt;<br>  &lt;/url&gt;<br>  &lt;url&gt;<br>    &lt;loc&gt;https://yourdomain.com/about&lt;/loc&gt;<br>    &lt;lastmod&gt;2024-01-15&lt;/lastmod&gt;<br>    &lt;changefreq&gt;monthly&lt;/changefreq&gt;<br>    &lt;priority&gt;0.9&lt;/priority&gt;<br>  &lt;/url&gt;<br>  &lt;!-- More URLs... --&gt;<br>&lt;/urlset&gt;</pre><h4><strong>Multilingual Sitemap with hreflang</strong></h4><p>If your site supports multiple languages, each sitemap entry must declare its language alternates. Without this, Google won’t know which version to serve to which audience.</p><pre>// app/sitemap.ts<br>import { MetadataRoute } from &#39;next&#39;<br><br>export default function sitemap(): MetadataRoute.Sitemap {<br>  const baseUrl = &#39;https://yourdomain.com&#39;<br><br>return [<br>    {<br>      url: `${baseUrl}`,<br>      lastModified: new Date(),<br>      changeFrequency: &#39;weekly&#39;,<br>      priority: 1.0,<br>      alternates: {<br>        languages: {<br>          es: `${baseUrl}`,<br>          en: `${baseUrl}/en`,<br>        },<br>      },<br>    },<br>    {<br>      url: `${baseUrl}/servicios`,<br>      lastModified: new Date(),<br>      changeFrequency: &#39;monthly&#39;,<br>      priority: 0.9,<br>      alternates: {<br>        languages: {<br>          es: `${baseUrl}/servicios`,<br>          en: `${baseUrl}/en/services`,<br>        },<br>      },<br>    },<br>  ]<br>}</pre><blockquote><strong><em>Note:</em></strong><em> The </em><em>alternates.languages field in the sitemap is how Google resolves hreflang for multilingual sites. Missing it means Google may serve the wrong language version to the wrong audience.</em></blockquote><h4>Advanced Dynamic Sitemap</h4><p>For real-world applications with dynamic content like blogs and portfolios, you’ll want a more sophisticated setup:</p><pre>// app/sitemap.ts - Production-Ready Version<br>import { MetadataRoute } from &#39;next&#39;<br>import { getAllPosts } from &#39;@/lib/blog-service&#39;<br>import { getAllProjects } from &#39;@/lib/projects-service&#39;<br><br>export default async function sitemap(): Promise&lt;MetadataRoute.Sitemap&gt; {<br>  const baseUrl = &#39;https://yourdomain.com&#39;<br><br>// Static pages with strategic priorities<br>  const staticPages: MetadataRoute.Sitemap = [<br>    {<br>      url: baseUrl,<br>      lastModified: new Date(),<br>      changeFrequency: &#39;weekly&#39;,<br>      priority: 1.0, // Homepage gets highest priority<br>    },<br>    {<br>      url: `${baseUrl}/about`,<br>      lastModified: new Date(),<br>      changeFrequency: &#39;monthly&#39;,<br>      priority: 0.9,<br>    },<br>    {<br>      url: `${baseUrl}/services`,<br>      lastModified: new Date(),<br>      changeFrequency: &#39;monthly&#39;,<br>      priority: 0.9,<br>    },<br>    {<br>      url: `${baseUrl}/services/web-design`,<br>      lastModified: new Date(),<br>      changeFrequency: &#39;monthly&#39;,<br>      priority: 0.8,<br>    },<br>    {<br>      url: `${baseUrl}/services/seo`,<br>      lastModified: new Date(),<br>      changeFrequency: &#39;monthly&#39;,<br>      priority: 0.8,<br>    },<br>    {<br>      url: `${baseUrl}/portfolio`,<br>      lastModified: new Date(),<br>      changeFrequency: &#39;weekly&#39;,<br>      priority: 0.9,<br>    },<br>    {<br>      url: `${baseUrl}/blog`,<br>      lastModified: new Date(),<br>      changeFrequency: &#39;daily&#39;,<br>      priority: 0.8,<br>    },<br>    {<br>      url: `${baseUrl}/contact`,<br>      lastModified: new Date(),<br>      changeFrequency: &#39;monthly&#39;,<br>      priority: 0.7,<br>    },<br>    // Legal pages (lower priority)<br>    {<br>      url: `${baseUrl}/privacy-policy`,<br>      lastModified: new Date(),<br>      changeFrequency: &#39;yearly&#39;,<br>      priority: 0.3,<br>    },<br>    {<br>      url: `${baseUrl}/terms-of-service`,<br>      lastModified: new Date(),<br>      changeFrequency: &#39;yearly&#39;,<br>      priority: 0.3,<br>    },<br>  ]<br><br>try {<br>    // Fetch dynamic blog posts<br>    const blogPosts = await getAllPosts()<br>    const publishedPosts = blogPosts.filter(post =&gt; post.published)<br>    <br>    const blogPages: MetadataRoute.Sitemap = publishedPosts.map((post) =&gt; ({<br>      url: `${baseUrl}/blog/${post.slug}`,<br>      lastModified: new Date(post.updatedAt || post.createdAt),<br>      changeFrequency: &#39;weekly&#39;,<br>      priority: 0.6,<br>    }))<br><br>// Fetch dynamic portfolio projects<br>    const projects = await getAllProjects()<br>    const projectPages: MetadataRoute.Sitemap = projects.map((project) =&gt; ({<br>      url: `${baseUrl}/portfolio/${project.slug}`,<br>      lastModified: new Date(project.updatedAt),<br>      changeFrequency: &#39;monthly&#39;,<br>      priority: 0.7,<br>    }))<br><br>// Combine all pages<br>    return [...staticPages, ...blogPages, ...projectPages]<br><br>} catch (error) {<br>    console.error(&#39;Error generating sitemap:&#39;, error)<br>    // Return static pages if dynamic content fails<br>    return staticPages<br>  }<br>}</pre><h4>Understanding Sitemap Parameters</h4><h4>Priority (0.0 to 1.0)</h4><p>Priority tells search engines which pages are most important <strong>on your website</strong> (not compared to other websites):</p><ul><li><strong>1.0</strong>: Homepage — your most important page</li><li><strong>0.9</strong>: Main sections (Services, Portfolio, About)</li><li><strong>0.8</strong>: Important subpages (individual services, team page)</li><li><strong>0.7</strong>: Content pages (portfolio projects, case studies)</li><li><strong>0.6</strong>: Blog posts and articles</li><li><strong>0.5</strong>: Archive pages, category pages</li><li><strong>0.3</strong>: Legal pages, terms, privacy policy</li></ul><p><strong>Important</strong>: Priority doesn’t affect your ranking against competitors , it just helps search engines understand your site structure.</p><h4>Change Frequency</h4><p>Tells search engines how often content changes:</p><ul><li><strong>always</strong>: Pages that change every time they&#39;re accessed</li><li><strong>hourly</strong>: Real-time data, live feeds</li><li><strong>daily</strong>: News sites, active blogs</li><li><strong>weekly</strong>: Regularly updated content, portfolios</li><li><strong>monthly</strong>: Business pages, services, about pages</li><li><strong>yearly</strong>: Legal pages, company information</li><li><strong>never</strong>: Archived content</li></ul><h4>Last Modified</h4><p>Use real dates when content actually changes:</p><pre>// Use actual content dates<br>lastModified: new Date(post.updatedAt)<br><br>// Or current date for pages that change regularly<br>lastModified: new Date()</pre><h4>Real-World Example Output</h4><p>Your complete sitemap will generate XML like this:</p><pre>&lt;urlset xmlns=&quot;http://www.sitemaps.org/schemas/sitemap/0.9&quot;&gt;<br>  &lt;!-- Homepage - Highest Priority --&gt;<br>  &lt;url&gt;<br>    &lt;loc&gt;https://yourdomain.com&lt;/loc&gt;<br>    &lt;lastmod&gt;2024-01-15T10:30:00.000Z&lt;/lastmod&gt;<br>    &lt;changefreq&gt;weekly&lt;/changefreq&gt;<br>    &lt;priority&gt;1&lt;/priority&gt;<br>  &lt;/url&gt;<br>  <br>  &lt;!-- Main Business Pages --&gt;<br>  &lt;url&gt;<br>    &lt;loc&gt;https://yourdomain.com/services&lt;/loc&gt;<br>    &lt;lastmod&gt;2024-01-15T10:30:00.000Z&lt;/lastmod&gt;<br>    &lt;changefreq&gt;monthly&lt;/changefreq&gt;<br>    &lt;priority&gt;0.9&lt;/priority&gt;<br>  &lt;/url&gt;<br>  <br>  &lt;!-- Dynamic Blog Posts --&gt;<br>  &lt;url&gt;<br>    &lt;loc&gt;https://yourdomain.com/blog/seo-tips-2024&lt;/loc&gt;<br>    &lt;lastmod&gt;2024-01-10T14:20:00.000Z&lt;/lastmod&gt;<br>    &lt;changefreq&gt;weekly&lt;/changefreq&gt;<br>    &lt;priority&gt;0.6&lt;/priority&gt;<br>  &lt;/url&gt;<br>  <br>  &lt;!-- Dynamic Portfolio Projects --&gt;<br>  &lt;url&gt;<br>    &lt;loc&gt;https://yourdomain.com/portfolio/ecommerce-redesign&lt;/loc&gt;<br>    &lt;lastmod&gt;2024-01-08T09:15:00.000Z&lt;/lastmod&gt;<br>    &lt;changefreq&gt;monthly&lt;/changefreq&gt;<br>    &lt;priority&gt;0.7&lt;/priority&gt;<br>  &lt;/url&gt;<br>  <br>  &lt;!-- Legal Pages - Lower Priority --&gt;<br>  &lt;url&gt;<br>    &lt;loc&gt;https://yourdomain.com/privacy-policy&lt;/loc&gt;<br>    &lt;lastmod&gt;2024-01-01T00:00:00.000Z&lt;/lastmod&gt;<br>    &lt;changefreq&gt;yearly&lt;/changefreq&gt;<br>    &lt;priority&gt;0.3&lt;/priority&gt;<br>  &lt;/url&gt;<br>&lt;/urlset&gt;</pre><h4>Best Practices</h4><h4>1. Strategic Prioritization</h4><pre>// Good priority structure<br>const priorities = {<br>  homepage: 1.0,<br>  mainSections: 0.9,      // /services, /portfolio, /about<br>  subPages: 0.8,          // /services/web-design<br>  contentPages: 0.6-0.7,  // blog posts, projects<br>  legalPages: 0.3         // privacy, terms<br>}</pre><h4>2. Realistic Change Frequencies</h4><pre>// Match frequency to actual update patterns<br>const frequencies = {<br>  homepage: &#39;weekly&#39;,     // Updated regularly with new content<br>  businessPages: &#39;monthly&#39;, // Updated when services change<br>  blogPosts: &#39;weekly&#39;,    // May get updates, comments<br>  legalPages: &#39;yearly&#39;    // Rarely change<br>}</pre><h4>3. Accurate Last Modified Dates</h4><pre>// Use real content dates, not current date for everything<br>{<br>  url: `${baseUrl}/blog/${post.slug}`,<br>  lastModified: new Date(post.updatedAt), // Real update date<br>  changeFrequency: &#39;weekly&#39;,<br>  priority: 0.6,<br>}</pre><h4>4. Error Handling</h4><pre>try {<br>  const dynamicContent = await fetchContent()<br>  return [...staticPages, ...dynamicContent]<br>} catch (error) {<br>  console.error(&#39;Sitemap generation error:&#39;, error)<br>  // Always return at least static pages<br>  return staticPages<br>}</pre><h4>Testing Your Sitemap</h4><p>After building your site:</p><pre>npm run build<br><br>// once the build is successful<br>npm run start</pre><p>NB: You may encounter, like I did, a build error stating the following:</p><pre>❌ [next-sitemap] Unable to find next-sitemap.config.js<br>❌ Error: ENOENT: no such file or directory</pre><p>This happens when you have the old next-sitemap package installed alongside the new Next.js 16 approach.</p><p><strong>Quick Fix:</strong></p><ol><li>Remove the package: npm uninstall next-sitemap</li><li>Remove the postbuild script from package.json:</li></ol><pre>{<br>  &quot;scripts&quot;: {<br>    &quot;build&quot;: &quot;next build&quot;<br>    // Remove this line: &quot;postbuild&quot;: &quot;next-sitemap&quot;<br>  }<br>}</pre><p><strong>Why this happens:</strong> The next-sitemap package is the old way of generating sitemaps. Next.js 16&#39;s app/sitemap.ts approach is newer and better - you don&#39;t need both. The old package tries to run after build and looks for its config file, causing the error.</p><p><strong>Your </strong><strong>app/sitemap.ts file is the modern solution and works perfectly without any external packages.</strong></p><ol><li><strong>Local Testing</strong>: Visit <a href="http://localhost:3000/sitemap.xml">http://localhost:3000/sitemap.xml</a></li><li><strong>Production Testing</strong>: Visit <a href="https://yourdomain.com/sitemap.xml">https://yourdomain.com/sitemap.xml</a></li><li><strong>Validation</strong>: Use Google’s sitemap validator</li><li><strong>Submission</strong>: Submit to Google Search Console and Bing Webmaster Tools</li></ol><h4>Common Mistakes to Avoid</h4><ol><li>Don’t set everything to priority 1.0 — Use a hierarchy</li><li>Don’t use always changefreq unless content literally always changes</li><li>Don’t include admin pages, API endpoints, or private content</li><li>Don’t forget error handling for dynamic content</li><li>Don’t use fake lastModified dates — use real ones or current date</li></ol><h4>Next Steps</h4><p>Once your sitemap is live:</p><ol><li>Submit to Google Search Console</li><li>Submit to Bing Webmaster Tools</li><li>Monitor crawl statistics</li><li>Update priorities based on actual traffic patterns</li><li>Add new pages to static array as your site grows</li></ol><p>This dynamic approach ensures your sitemap stays current automatically, giving search engines the best possible understanding of your site structure and content.</p><h3>Robots.txt Generation</h3><p>Your robots.txt file is like a bouncer for your website — it controls which parts search engines can access and which they should avoid. Next.js provides a powerful way to generate this file automatically using TypeScript.</p><h4>Why Robots.txt Matters</h4><p>Before diving into the code, understand that robots.txt helps you:</p><ul><li><strong>Protect sensitive areas</strong> (admin panels, API endpoints)</li><li><strong>Improve crawl efficiency</strong> (don’t waste Google’s time on irrelevant pages)</li><li><strong>Control server load</strong> (prevent bots from overwhelming your site)</li><li><strong>Boost SEO performance</strong> (guide search engines to your best content)</li></ul><h4>The Next.js 16 Approach</h4><p>Create a robots.ts file in your app/ folder for dynamic, TypeScript-powered robot control:</p><h4>Basic Example</h4><pre>// app/robots.ts<br>import { MetadataRoute } from &#39;next&#39;<br><br>export default function robots(): MetadataRoute.Robots {<br>  return {<br>    rules: [<br>      {<br>        userAgent: &#39;*&#39;,<br>        allow: &#39;/&#39;,<br>        disallow: [<br>          &#39;/api/&#39;,<br>          &#39;/admin/&#39;,<br>          &#39;/_next/&#39;,<br>          &#39;/private/&#39;,<br>        ],<br>      },<br>      {<br>        userAgent: &#39;Googlebot&#39;,<br>        allow: &#39;/&#39;,<br>        disallow: [<br>          &#39;/api/&#39;,<br>          &#39;/admin/&#39;,<br>        ],<br>      },<br>    ],<br>    sitemap: &#39;https://yourdomain.com/sitemap.xml&#39;,<br>  }<br>}</pre><h4>Professional Production Example</h4><p>For real-world applications, you’ll want more sophisticated control:</p><pre>// app/robots.ts - Production-Ready Version<br>import { MetadataRoute } from &#39;next&#39;<br><br>export default function robots(): MetadataRoute.Robots {<br>  const baseUrl = &#39;https://yourdomain.com&#39;<br>  const isProduction = process.env.NODE_ENV === &#39;production&#39;<br>  <br>  // Block everything in development/staging<br>  if (!isProduction) {<br>    return {<br>      rules: {<br>        userAgent: &#39;*&#39;,<br>        disallow: &#39;/&#39;,<br>      },<br>      sitemap: `${baseUrl}/sitemap.xml`,<br>    }<br>  }<br><br>// Production rules<br>  return {<br>    rules: [<br>      // General rules for all search engines<br>      {<br>        userAgent: &#39;*&#39;,<br>        allow: &#39;/&#39;,<br>        disallow: [<br>          &#39;/api/&#39;,           // Block API endpoints<br>          &#39;/admin/&#39;,         // Block admin areas<br>          &#39;/_next/&#39;,         // Block Next.js internals<br>          &#39;/private/&#39;,       // Block private content<br>          &#39;/404&#39;,            // Block error pages<br>          &#39;/500&#39;,<br>          &#39;/login&#39;,          // Block authentication pages<br>        ],<br>      },<br>      <br>      // Give Google special treatment<br>      {<br>        userAgent: &#39;Googlebot&#39;,<br>        allow: &#39;/&#39;,<br>        disallow: [<br>          &#39;/api/&#39;,<br>          &#39;/admin/&#39;,<br>          &#39;/_next/&#39;,<br>          &#39;/private/&#39;,<br>        ],<br>        // No crawl delay for Google<br>      },<br>    ],<br>    sitemap: `${baseUrl}/sitemap.xml`,<br>  }<br>}</pre><p><strong>Note:</strong> host is not a standard robots.txt directive and is ignored by all major crawlers — do not include it. crawlDelay is also ignored by Googlebot entirely; only a handful of minor bots respect it, so it provides no practical benefit for most sites.</p><h4>Generated Output</h4><p>The TypeScript file above automatically generates this robots.txt:</p><pre>User-agent: *<br>Allow: /<br>Disallow: /api/<br>Disallow: /admin/<br>Disallow: /_next/<br>Disallow: /private/<br>Disallow: /404<br>Disallow: /500<br>Disallow: /login<br><br>User-agent: Googlebot<br>Allow: /<br>Disallow: /api/<br>Disallow: /admin/<br>Disallow: /_next/<br>Disallow: /private/<br><br>Sitemap: https://yourdomain.com/sitemap.xml</pre><p><strong>Note:</strong> Do not block Ahrefs, Semrush, or similar SEO crawlers. These bots power the tools you and your clients use to monitor rankings, backlinks, and site health. Blocking them doesn’t improve your rankings — it just blinds your own monitoring. They also often ignore robots.txt anyway.</p><h4>Why app/robots.ts Beats public/robots.txt</h4><p>You might see tutorials suggesting a static public/robots.txt file. Here&#39;s why the Next.js 16 approach is superior:</p><h4>Method 1: Static File (Old Way)</h4><pre>public/robots.txt</pre><p><strong>Limitations:</strong></p><ul><li>Plain text file that never changes</li><li>Same rules for development and production</li><li>No TypeScript safety or error checking</li><li>Manual updates required for different environments</li></ul><h4>Method 2: Dynamic Generation (Next.js 16 Way)</h4><pre>app/robots.ts</pre><p><strong>Advantages:</strong></p><ul><li>✅ <strong>Environment-aware</strong>: Different rules for dev/staging/production</li><li>✅ <strong>TypeScript safety</strong>: Catch configuration errors at build time</li><li>✅ <strong>Dynamic content</strong>: Rules can change based on conditions</li><li>✅ <strong>Automatic generation</strong>: Next.js handles everything</li><li>✅ <strong>Version control friendly</strong>: Changes are tracked in code</li><li>✅ <strong>Professional setup</strong>: Industry best practices built-in</li></ul><h4>Real-World Configuration Tips</h4><h4>1. Protect Your Admin Areas</h4><pre>disallow: [<br>  &#39;/admin/&#39;,<br>  &#39;/admin/*&#39;,      // Block all admin subpages<br>  &#39;/dashboard/&#39;,<br>  &#39;/wp-admin/&#39;,    // If migrating from WordPress<br>]</pre><h4>2. Block Sensitive API Endpoints</h4><pre>disallow: [<br>  &#39;/api/&#39;,<br>  &#39;/api/*&#39;,<br>  &#39;/auth/&#39;,        // Authentication endpoints<br>  &#39;/upload/&#39;,      // File upload endpoints<br>]</pre><h4>3. Environment-Based Rules</h4><pre>// Block staging sites from being indexed<br>if (process.env.VERCEL_ENV !== &#39;production&#39;) {<br>  return {<br>    rules: { userAgent: &#39;*&#39;, disallow: &#39;/&#39; }<br>  }<br>}</pre><h4>Common Mistakes to Avoid</h4><ol><li><strong>Don’t block your sitemap</strong>: Never add /sitemap.xml to disallow</li><li><strong>Test your rules</strong>: Use Google Search Console to verify</li><li><strong>Don’t over-block</strong>: Only block what you need to protect</li><li><strong>Remember wildcards</strong>: Use /* to block entire directories</li><li><strong>Check case sensitivity</strong>: /Admin/ vs /admin/ are different</li></ol><h4>Testing Your Robots.txt</h4><p>After deployment, test your robots.txt:</p><ol><li>Visit <a href="https://yourdomain.com/robots.txt">https://yourdomain.com/robots.txt</a></li><li>Use Google Search Console’s robots.txt tester</li><li>Verify blocked pages don’t appear in search results</li></ol><h4>Next Steps</h4><p>Once your robots.txt is configured:</p><ol><li>Submit your sitemap.xml to Google Search Console</li><li>Monitor crawl stats and errors</li><li>Adjust rules based on actual bot behavior</li><li>Consider adding more specific bot rules as needed</li></ol><p>This setup gives you professional-grade robot control that scales with your application and protects your resources while maximizing SEO benefits.</p><h3>Page-Level SEO Optimization</h3><p>Each page needs its own SEO strategy. Here’s how to create optimized page layouts:</p><pre>// app/about/layout.tsx<br>import { Metadata } from &quot;next&quot;;<br><br>export const metadata: Metadata = {<br>  title: &quot;About Us - Expert Team with 20+ Years Experience&quot;,<br>  description: &quot;Meet our expert team. 20+ years of experience delivering exceptional results for clients across the region. Learn about our story and values.&quot;,<br>  openGraph: {<br>    title: &quot;About Our Expert Team&quot;,<br>    description: &quot;Meet the professionals behind our success story&quot;,<br>    images: [<br>      {<br>        url: &quot;/team-photo.jpg&quot;,<br>        width: 1200,<br>        height: 630,<br>        alt: &quot;Our professional team photo&quot;<br>      }<br>    ],<br>  },<br>  alternates: {<br>    canonical: &quot;https://yourdomain.com/about&quot;<br>  }<br>};<br><br>export default function AboutLayout({<br>  children,<br>}: {<br>  children: React.ReactNode;<br>}) {<br>  return (<br>    &lt;&gt;<br>      {/* About Page Structured Data */}<br>      &lt;script<br>        type=&quot;application/ld+json&quot;<br>        dangerouslySetInnerHTML={{<br>          __html: JSON.stringify({<br>            &quot;@context&quot;: &quot;https://schema.org&quot;,<br>            &quot;@type&quot;: &quot;AboutPage&quot;,<br>            &quot;name&quot;: &quot;About Us&quot;,<br>            &quot;description&quot;: &quot;Learn about our company history and team&quot;,<br>            &quot;url&quot;: &quot;https://yourdomain.com/about&quot;,<br>            &quot;mainEntity&quot;: {<br>              &quot;@type&quot;: &quot;Organization&quot;,<br>              &quot;name&quot;: &quot;Your Business Name&quot;,<br>              &quot;foundingDate&quot;: &quot;2020&quot;,<br>              &quot;description&quot;: &quot;Brief description of what makes you unique&quot;<br>            }<br>          })<br>        }}<br>      /&gt;<br>      {children}<br>    &lt;/&gt;<br>  );<br>}</pre><h3>Creating Reusable SEO Utils (just an extra, not mandatory)</h3><p>Instead of repeating metadata code, create utility functions:</p><pre>// utils/seo-utils.ts<br>interface SEOProps {<br>  title: string;<br>  description: string;<br>  canonical?: string;<br>  images?: string[];<br>  type?: &#39;website&#39; | &#39;article&#39;;<br>}<br><br>export function generatePageMetadata({<br>  title,<br>  description,<br>  canonical,<br>  images = [&#39;/default-og-image.jpg&#39;],<br>  type = &#39;website&#39;<br>}: SEOProps) {<br>return {<br>    title,<br>    description,<br>    openGraph: {<br>      title,<br>      description,<br>      type,<br>      images: images.map(img =&gt; ({<br>        url: img,<br>        width: 1200,<br>        height: 630,<br>        alt: title<br>      })),<br>      locale: &#39;en_US&#39;,<br>      siteName: &#39;Your Business Name&#39;<br>    },<br>    twitter: {<br>      card: &#39;summary_large_image&#39; as const,<br>      title,<br>      description,<br>      images: images[0]<br>    },<br>    alternates: canonical ? { canonical } : undefined<br>  };<br>}</pre><pre>// Usage in any page:<br>export const metadata = generatePageMetadata({<br>  title: &#39;Services - Professional Solutions&#39;,<br>  description: &#39;Comprehensive services description...&#39;,<br>  canonical: &#39;https://yourdomain.com/services&#39;<br>});</pre><h4><strong>Dynamic OG Images with </strong><strong>opengraph-image.tsx</strong></h4><p>Instead of pointing to a static image file, Next.js App Router lets you generate OG images per route at request time using a file convention.</p><p>Create app/opengraph-image.tsx:</p><pre>import { ImageResponse } from &#39;next/og&#39;<br><br>export const runtime = &#39;edge&#39;<br>export const size = { width: 1200, height: 630 }<br>export const contentType = &#39;image/png&#39;<br><br>export default function OgImage() {<br>  return new ImageResponse(<br>    (<br>      &lt;div<br>        style={{<br>          width: &#39;100%&#39;,<br>          height: &#39;100%&#39;,<br>          display: &#39;flex&#39;,<br>          flexDirection: &#39;column&#39;,<br>          justifyContent: &#39;center&#39;,<br>          padding: &#39;80px&#39;,<br>          backgroundColor: &#39;#0f172a&#39;,<br>          color: &#39;#ffffff&#39;,<br>        }}<br>      &gt;<br>        &lt;p style={{ fontSize: 28, color: &#39;#f97316&#39; }}&gt;Your Business Name&lt;/p&gt;<br>        &lt;h1 style={{ fontSize: 64, margin: &#39;16px 0&#39; }}&gt;Your tagline here&lt;/h1&gt;<br>      &lt;/div&gt;<br>    ),<br>    { width: 1200, height: 630 }<br>  )<br>}</pre><p>For per-page images, create the same file inside each route folder — app/about/opengraph-image.tsx, app/blog/[slug]/opengraph-image.tsx, etc. Each one receives params so you can pull the page title dynamically.</p><blockquote><strong><em>Note:</em></strong><em> No static file needed. Next.js serves this automatically at </em><em>/opengraph-image. Your </em><em>metadata OG image config picks it up automatically — no URL to hardcode.</em></blockquote><h3>Performance Optimization for SEO</h3><p>Page speed is a ranking factor. Here’s how to optimize:</p><h3>Critical Resource Preloading</h3><p>This is the way I usually preload images that are critical for my website to look good and fast. I mean by that, the hero images, for examples, those the user will see first as they access a page. We don´t want that ugly grayish placeholder while the image gets served, and so that’s a good fix…</p><pre>// In your root layout &lt;head&gt;<br>&lt;link<br>  rel=&quot;preload&quot;<br>  href=&quot;/hero-image.webp&quot;<br>  as=&quot;image&quot;<br>  type=&quot;image/webp&quot;<br>  fetchPriority=&quot;high&quot;<br>/&gt;<br>&lt;link<br>  rel=&quot;preload&quot;<br>  href=&quot;/critical-image-2.webp&quot;<br>  as=&quot;image&quot;<br>  type=&quot;image/webp&quot;<br>  fetchPriority=&quot;high&quot;<br>/&gt;<br><br>{/* DNS prefetch for external resources */}<br>&lt;link rel=&quot;dns-prefetch&quot; href=&quot;//fonts.googleapis.com&quot; /&gt;<br>&lt;link rel=&quot;dns-prefetch&quot; href=&quot;//www.google-analytics.com&quot; /&gt;</pre><h3>Font Optimization</h3><pre>const primaryFont = localFont({<br>  variable: &quot;--font-primary&quot;,<br>  display: &quot;swap&quot;, // Critical for CLS<br>  src: [<br>    {<br>      path: &quot;../public/fonts/font-regular.woff2&quot;,<br>      weight: &quot;400&quot;,<br>      style: &quot;normal&quot;,<br>    },<br>  ],<br>});</pre><h3>Image Optimization Best Practices</h3><p>Image Alt Tag Optimization<br>Transform generic alt tags into SEO-powered descriptions:</p><pre>// Before<br>&lt;Image src=&quot;/project1.jpg&quot; alt=&quot;project&quot; /&gt;<br><br>// After  <br>&lt;Image <br>  src=&quot;/project1.jpg&quot; <br>  alt=&quot;Modern office interior design with natural lighting and contemporary furniture&quot; <br>/&gt;</pre><h3>Local SEO Optimization</h3><p>geo.region, geo.placename, geo.position and ICBM meta tags are not used by Google and have no effect on local SEO rankings. The correct way to express geographic information is through the geo field in your LocalBusiness JSON-LD schema, which you already have.</p><h3>Local Business Schema</h3><pre>{<br>  &quot;@context&quot;: &quot;https://schema.org&quot;,<br>&quot;@type&quot;: &quot;LocalBusiness&quot;,<br>&quot;@id&quot;: &quot;https://yourdomain.com/#localbusiness&quot;,<br>&quot;name&quot;: &quot;Your Business Name&quot;,<br>  &quot;image&quot;: &quot;https://yourdomain.com/business-photo.jpg&quot;,<br>  &quot;telephone&quot;: &quot;+1-555-123-4567&quot;,<br>  &quot;address&quot;: {<br>    &quot;@type&quot;: &quot;PostalAddress&quot;,<br>    &quot;streetAddress&quot;: &quot;123 Main Street&quot;,<br>    &quot;addressLocality&quot;: &quot;Your City&quot;,<br>    &quot;addressRegion&quot;: &quot;Your State&quot;,<br>    &quot;postalCode&quot;: &quot;12345&quot;,<br>    &quot;addressCountry&quot;: &quot;US&quot;<br>  },<br>  &quot;geo&quot;: {<br>    &quot;@type&quot;: &quot;GeoCoordinates&quot;,<br>    &quot;latitude&quot;: 37.7749,<br>    &quot;longitude&quot;: -122.4194<br>  },<br>  &quot;openingHoursSpecification&quot;: [<br>    {<br>      &quot;@type&quot;: &quot;OpeningHoursSpecification&quot;,<br>      &quot;dayOfWeek&quot;: [<br>        &quot;Monday&quot;,<br>        &quot;Tuesday&quot;,<br>        &quot;Wednesday&quot;,<br>        &quot;Thursday&quot;,<br>        &quot;Friday&quot;<br>      ],<br>      &quot;opens&quot;: &quot;09:00&quot;,<br>      &quot;closes&quot;: &quot;17:00&quot;<br>    }<br>  ],<br>}</pre><p><strong>Warning:</strong> Never include aggregateRating in your schema unless the numbers come from real, verifiable reviews on your own platform. Google cross-checks this data. Fake or estimated ratings are classified as structured data spam and can result in a manual penalty that removes your rich results entirely.</p><h3>Testing and Monitoring Your SEO</h3><h4>Essential Tools</h4><ol><li><strong>Google Search Console</strong>: Monitor your search performance</li><li><strong>Lighthouse</strong>: Test performance and SEO scores</li><li><strong>Google’s Rich Results Test</strong>: Validate structured data</li><li><strong>PageSpeed Insights</strong>: Check Core Web Vitals</li></ol><h4>Quick Testing Commands</h4><pre># Build and test your sitemaps<br>npm run build<br>npm start</pre><pre># Visit these URLs to test:<br># <a href="http://localhost:3000/sitemap.xml">http://localhost:3000/sitemap.xml</a><br># <a href="http://localhost:3000/robots.txt">http://localhost:3000/robots.txt</a></pre><h4>SEO Checklist for Launch</h4><ul><li>[✔] Google Search Console setup</li><li>[✔] Google Analytics installed</li><li>[✔] All images have descriptive alt tags</li><li>[✔] Every page has unique title &lt;h1&gt; and description</li><li>[✔] Sitemap submitted to search engines</li><li>[✔] Site speed under 3 seconds</li><li>[✔] Mobile-friendly design</li><li>[✔] HTTPS enabled</li><li>[✔] Internal linking strategy implemented</li></ul><h3>Advanced Techniques</h3><p>If you really really want la crème de la crème…</p><h4>Dynamic Metadata for Content Sites</h4><p>The basic metadata we’ve covered is great, but what if you have a blog, portfolio, or any content with dynamic pages? Static metadata won’t cut it.</p><p>Here’s where Next.js 16’s generateMetadata function becomes pure magic:</p><pre>// For blog posts, portfolios, etc.<br>export async function generateMetadata(<br>  { params }: { params: Promise&lt;{ slug: string }&gt; }<br>): Promise&lt;Metadata&gt; {<br>  const { slug } = await params<br>  const post = await getPost(slug)<br>  <br>  return {<br>    title: post.title,<br>    description: post.excerpt,<br>    openGraph: {<br>      title: post.title,<br>      description: post.excerpt,<br>      images: [post.featuredImage],<br>    },<br>  }<br>}</pre><p><strong>What this does:</strong> Instead of having the same boring metadata on every blog post, each page gets unique SEO data pulled from your actual content. So if you have a blog post titled “5 Interior Design Trends for 2024”, that becomes your page title, not some generic “Blog Post” title.</p><p><strong>Why it’s powerful:</strong></p><ul><li>Google sees unique, relevant content for each page</li><li>Social media sharing gets the actual post image and description</li><li>Zero manual work — it’s all automatic based on your content</li></ul><h4>Breadcrumb Navigation with Schema</h4><p>Breadcrumbs are those little navigation trails like “Home &gt; Services &gt; Interior Design” that show users where they are. But with schema markup, they become SEO gold:</p><pre>// components/Breadcrumbs.tsx<br>interface BreadcrumbItem {<br>  name: string;<br>  href: string;<br>}<br><br>export default function Breadcrumbs({ items }: { items: BreadcrumbItem[] }) {<br>  const schema = {<br>    &quot;@context&quot;: &quot;https://schema.org&quot;,<br>    &quot;@type&quot;: &quot;BreadcrumbList&quot;,<br>    &quot;itemListElement&quot;: items.map((item, index) =&gt; ({<br>      &quot;@type&quot;: &quot;ListItem&quot;,<br>      &quot;position&quot;: index + 1,<br>      &quot;name&quot;: item.name,<br>      &quot;item&quot;: `https://yourdomain.com${item.href}`<br>    }))<br>  };<br><br>return (<br>    &lt;&gt;<br>      &lt;script<br>        type=&quot;application/ld+json&quot;<br>        dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }}<br>      /&gt;<br>      &lt;nav aria-label=&quot;Breadcrumb&quot;&gt;<br>        &lt;ol&gt;<br>          {items.map((item, index) =&gt; (<br>            &lt;li key={index}&gt;<br>              {index &lt; items.length - 1 ? (<br>                &lt;a href={item.href}&gt;{item.name}&lt;/a&gt;<br>              ) : (<br>                &lt;span&gt;{item.name}&lt;/span&gt;<br>              )}<br>              {index &lt; items.length - 1 &amp;&amp; &lt;span&gt; &gt; &lt;/span&gt;}<br>            &lt;/li&gt;<br>          ))}<br>        &lt;/ol&gt;<br>      &lt;/nav&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p><strong>What this does:</strong> Creates breadcrumbs that Google can understand and potentially show in search results. You know those search results that show “YourSite &gt; Category &gt; Page”? That’s breadcrumb schema in action.</p><p><strong>How to use it:</strong></p><pre>// In any page<br>const breadcrumbs = [<br>  { name: &#39;Home&#39;, href: &#39;/&#39; },<br>  { name: &#39;Services&#39;, href: &#39;/services&#39; },<br>  { name: &#39;Interior Design&#39;, href: &#39;/services/interior-design&#39; }<br>];<br><br>return &lt;Breadcrumbs items={breadcrumbs} /&gt;;</pre><p>These two techniques can seriously boost your SEO game by making your content more discoverable and user-friendly.</p><h3>Conclusion</h3><p>SEO in Next.js isn’t just about adding meta tags , it’s about creating a comprehensive strategy that covers technical optimization, content structure, and user experience.</p><p>The techniques in this guide have helped me achieve:</p><ul><li>85%+ improvement in search rankings</li><li>300% increase in organic traffic</li><li>Perfect Lighthouse SEO scores</li><li>Rich search result appearances</li></ul><p>Remember: SEO is a marathon, not a sprint. Implement these techniques gradually, monitor your results, and keep optimizing based on real data.</p><h3>Key Takeaways</h3><ol><li><strong>Use the Metadata API properly</strong> — It’s your foundation</li><li><strong>Don’t forget sitemap.xml and robots.txt</strong> — They’re essential</li><li><strong>Structured data is your secret weapon</strong> — It makes you stand out</li><li><strong>Performance matters</strong> — Fast sites rank better</li><li><strong>Local SEO can be a game-changer</strong> — Don’t ignore it</li></ol><p>Thanks for reading :)</p><p>If you liked this article, feel free to connect with me!</p><ul><li><a href="https://helloimtom.dev/">https://helloimtom.dev/</a></li><li>Github: <a href="https://github.com/thomasaugot">https://github.com/thomasaugot</a></li><li>LinkedIn: <a href="https://www.linkedin.com/in/thomas-augot/">https://www.linkedin.com/in/thomas-augot/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1bdb118cffd7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>