<?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"><channel><title><![CDATA[Towneers Devlog]]></title><description><![CDATA[Towneers Devlog]]></description><link>https://towneers.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Sat, 28 Nov 2026 00:59:02 GMT</lastBuildDate><atom:link href="https://towneers.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[SEO y búsqueda con IA para un juego de navegador en Node.js puro: hreflang, JSON-LD, llms.txt e IndexNow sin framework]]></title><description><![CDATA[Nota: el juego también está disponible en español. Divulgación: desarrollo Towneers, un simulador de vida multijugador gratuito en el navegador. Esto es un…]]></description><link>https://towneers.hashnode.dev/seo-y-b-squeda-con-ia-para-un-juego-de-navegador-en-node-js-puro-hreflang-json-ld-llms-txt-e-indexnow-sin-framework</link><guid isPermaLink="true">https://towneers.hashnode.dev/seo-y-b-squeda-con-ia-para-un-juego-de-navegador-en-node-js-puro-hreflang-json-ld-llms-txt-e-indexnow-sin-framework</guid><category><![CDATA[SEO]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[spanish]]></category><category><![CDATA[Game Development]]></category><dc:creator><![CDATA[Towneers]]></dc:creator><pubDate>Fri, 27 Nov 2026 14:09:16 GMT</pubDate><content:encoded><![CDATA[<p><em>Nota: el juego también está disponible en español.</em></p>
<p><em>Divulgación: desarrollo Towneers, un simulador de vida multijugador gratuito en el navegador. Esto es un análisis de cómo se sirven su sitio y su blog. Todo lo que sigue procede del código real, simplificado para facilitar la lectura.</em></p>
<p>Un juego de navegador tiene un problema de SEO incómodo. El producto es un canvas y un WebSocket, que un rastreador ve como una página vacía. Las palabras que pueden posicionar, y que un asistente de IA puede citar, viven en otro sitio: una página de inicio, una guía del juego y un blog.</p>
<p>Decidimos no acoplar un CMS ni un generador de sitios estáticos. El servidor ya funciona con Node.js puro y la única dependencia en tiempo de ejecución es <code>ws</code>. Así que el blog es un único módulo del servidor que renderiza HTML a partir de archivos markdown. También sirve los extras legibles por máquinas: feeds, mapas del sitio, <code>llms.txt</code> y una copia en markdown de cada entrada. Este artículo recorre las decisiones y los compromisos.</p>
<h2>La forma del sistema</h2>
<p>Las entradas son archivos: <code>content/blog/&lt;slug&gt;/&lt;lang&gt;.md</code>, en cinco idiomas (en, es, de, uk, ru). Un módulo, <code>server/blog.js</code>, los lee, renderiza el HTML bajo demanda y guarda el resultado en caché en memoria. El mismo motor sirve también las páginas de guía <code>/game/...</code>, de modo que solo hay un lugar que sabe cómo emitir <code>&lt;head&gt;</code>.</p>
<p>El comentario de cabecera del módulo enumera lo que promete: texto renderizado en el servidor sin scripts, una caché en memoria por dirección e idioma, ETag y Last-Modified, gzip/brotli, canonical, hreflang con x-default, Open Graph, JSON-LD, RSS/Atom por idioma, un mapa del sitio del blog, <code>/llms.txt</code>, <code>/llms-full.txt</code> y una versión en markdown de cada entrada en <code>/blog/&lt;slug&gt;.md</code>.</p>
<p>¿Por qué renderizado en el servidor y no una carcasa SPA? Un rastreador, un bot de vista previa de enlaces y un recuperador de LLM comparten un rasgo: la mayoría no ejecuta tu JavaScript, o no lo ejecuta de forma fiable. HTML plano generado por una función es la respuesta más portable. Las páginas del blog no incluyen ningún código de framework.</p>
<h2>Entradas como archivos, con un frontmatter diminuto</h2>
<p>Una entrada empieza con unas pocas líneas de frontmatter. El analizador de <code>shared/blog.js</code> tiene unas veinte líneas y maneja solo lo que necesitamos: cadenas, listas <code>[a, b]</code> y booleanos.</p>
<pre><code class="language-js">export function parseFront(src) {
  const text = String(src ?? '').replace(/^﻿/, '').replace(/\r\n?/g, '\n');
  const m = /^---\n([\s\S]*?)\n---\n?/.exec(text);
  if (!m) return { meta: {}, body: text };
  const meta = {};
  for (const line of m[1].split('\n')) {
    const mm = /^([A-Za-z_][\w-]*)\s*:\s*(.*)$/.exec(line);
    if (!mm) continue;
    let v = mm[2].trim();
    if (/^\[.*\]$/.test(v)) v = v.slice(1, -1).split(',').map((x) =&gt; unq(x.trim())).filter(Boolean);
    else if (v === 'true' || v === 'false') v = v === 'true';
    else v = unq(v);
    meta[mm[1]] = v;
  }
  return { meta, body: text.slice(m[0].length) };
}
</code></pre>
<p>Los campos son <code>title</code>, <code>description</code>, <code>summary</code>, <code>date</code>, <code>tags</code>, <code>cover</code> y <code>coverAlt</code>. Una entrada real, recortada:</p>
<pre><code class="language-yaml">---
title: "Farming in Towneers: from your first seeds to a three-star harvest"
description: "A deep farming guide: plot prices, tools, all 9 crops, 5 seed tiers..."
date: 2026-11-27
tags: [guides, money]
cover: /landing/img/blog/farming-cover.webp
coverAlt: "A farm plot in North Farms at sunset..."
---
</code></pre>
<p>La decisión aquí fue mantener el contenido en el repositorio, junto al código, y no en una base de datos. Las entradas se revisan y se versionan como código. En el servidor de producción, las ediciones hechas en el panel de administración se escriben en un directorio de datos que se superpone a los archivos del repositorio. Una clase de almacén vuelve a escanear los directorios cuando cambia la firma de los archivos, como mucho una vez cada dos segundos, y incrementa un contador de versión. Ese contador es lo que invalida la caché más adelante.</p>
<h2>Bloques personalizados: FAQ, «pruébalo» y consejos</h2>
<p>Markdown por sí solo no puede expresar unas preguntas frecuentes que deban convertirse en marcado <code>FAQPage</code>, ni un botón que enlace directamente al juego. El renderizador añade una pequeña sintaxis de bloques sobre markdown: <code>:::faq</code>, <code>:::try</code>, <code>:::tip</code>, además de <code>:::news</code> y <code>:::items</code>.</p>
<pre><code class="language-md">:::try farms | ▶ Show me North Farms
...
:::

:::faq
### How much does a farm plot cost?
🪙2,700–5,400 right now. It depends on the size, and you can own up to 4 plots.
:::
</code></pre>
<p>El renderizador recoge cada pregunta y respuesta de un bloque <code>:::faq</code> en una lista mientras renderiza. Esa única lista alimenta dos salidas: las preguntas y respuestas visibles, y el JSON-LD. Los autores escriben la FAQ una sola vez y no pueden hacer que el marcado discrepe de la página. Esta idea de «una fuente, varias representaciones» reaparece en la copia en markdown y en <code>llms.txt</code>.</p>
<p>Una salvedad que conviene decir en voz alta: hace algún tiempo Google restringió los resultados enriquecidos de FAQ a un conjunto reducido de sitios, así que no deberías esperar un fragmento de FAQ en los resultados. Aun así emitimos <code>FAQPage</code> porque los pares pregunta-respuesta estructurados son baratos de producir y tienen justo la forma que les gusta extraer a los motores de respuestas.</p>
<h2>El head: canonical, hreflang, Open Graph</h2>
<p>Una función, <code>page()</code>, construye todo el documento. Esta es la parte del head que importa para el SEO multilingüe, reducida a lo esencial:</p>
<pre><code class="language-js">const xdef = alts.find((a) =&gt; a.lang === 'en');
return `&lt;!doctype html&gt;
&lt;html lang="${lang}" dir="ltr"&gt;
&lt;head&gt;
  &lt;title&gt;${esc(title)}&lt;/title&gt;
  &lt;meta name="description" content="${esc(desc)}" /&gt;
  &lt;meta name="robots" content="${robots}" /&gt;
  &lt;link rel="canonical" href="${abs(canonical)}" /&gt;
  ${alts.map((a) =&gt; `&lt;link rel="alternate" hreflang="${a.lang}" href="${abs(a.href)}" /&gt;`).join('\n  ')}
  ${xdef ? `&lt;link rel="alternate" hreflang="x-default" href="${abs(xdef.href)}" /&gt;` : ''}
  &lt;meta property="og:type" content="${ogType}" /&gt;
  &lt;meta property="og:locale" content="${ogLocale(lang)}" /&gt;
</code></pre>
<p>Hay tres decisiones incorporadas aquí.</p>
<p><strong>hreflang lista solo los idiomas que existen.</strong> Una entrada tiene <code>alts</code> para los idiomas en los que hay un archivo, no para los cinco. Muchos sitios generan alternativas para cada configuración regional y apuntan la mitad de ellas a páginas que no existen o que muestran inglés sin avisar. Nosotros no.</p>
<p><strong>x-default es el inglés.</strong> El inglés vive en la dirección sin prefijo (<code>/blog/...</code>), los demás idiomas en <code>/blog/es/...</code>, <code>/blog/de/...</code> y así sucesivamente. Una petición a <code>/blog/en/...</code> se redirige con un 301 a la forma sin prefijo, de modo que haya exactamente una URL por página.</p>
<p><strong>Las páginas sin traducir llevan noindex.</strong> Si una entrada no tiene archivo en español, la dirección en español sigue funcionando, porque no queremos un callejón sin salida para el lector. Muestra el texto en inglés con una nota de «por ahora solo en inglés». Pero el canonical apunta a la URL en inglés y la metaetiqueta robots pasa a <code>noindex, follow</code>:</p>
<pre><code class="language-js">const fallback = v.lang !== lang;
const canonical = fallback ? postPath('en', slug) : path;
// ...
robots: fallback || preview ? 'noindex, follow'
                            : 'index, follow, max-image-preview:large, max-snippet:-1',
</code></pre>
<p>No hay traducción automática. Una traducción real es un archivo aparte y, hasta que exista, la página no compite consigo misma en el índice. Fíjate en <code>max-snippet:-1</code> y <code>max-image-preview:large</code> en las páginas reales: queremos fragmentos largos, tanto para la búsqueda como para las respuestas de IA.</p>
<p>Open Graph incluye el ancho y el alto de la imagen, <code>og:locale</code> y <code>og:locale:alternate</code> para los demás idiomas, y <code>article:published_time</code>, <code>article:modified_time</code> y <code>article:tag</code> en las entradas. La imagen de portada es un archivo de 1200×630. Los bots de vista previa de enlaces (Telegram, Slack, WhatsApp y el resto) importan más para un juego social que cualquier buscador, y leen exactamente estas etiquetas.</p>
<h2>JSON-LD: un grafo por tipo de página</h2>
<p>Cada entrada lleva un <code>BlogPosting</code> más un <code>BreadcrumbList</code>, y un <code>FAQPage</code> cuando la entrada tiene preguntas. Este es el bloque <code>BlogPosting</code>, abreviado:</p>
<pre><code class="language-js">const postLd = {
  '@context': 'https://schema.org', '@type': 'BlogPosting', '@id': `${url}#post`,
  headline: v.title.slice(0, 110), description: v.description, url, inLanguage: v.lang,
  mainEntityOfPage: { '@type': 'WebPage', '@id': url },
  datePublished: `${v.date}T12:00:00Z`, dateModified: `${v.updated}T12:00:00Z`,
  author: { '@type': 'Organization', name: v.author || bt(v.lang, 'team'), url: `${origin}/` },
  publisher: { '@type': 'Organization', '@id': `${origin}/#org`, name: SITE, url: `${origin}/` },
  about: { '@type': 'VideoGame', name: SITE, url: `${origin}/` },
  wordCount: v.words, timeRequired: `PT${v.minutes}M`,
};
</code></pre>
<p>Notas sobre las decisiones:</p>
<ul>
<li><strong><code>@id</code> estables.</strong> <code>#post</code>, <code>#faq</code>, <code>#org</code>, <code>#game</code>. La organización y el juego se referencian por id desde muchas páginas, de modo que un consumidor puede fusionarlos en una sola entidad.</li>
<li><strong>El juego es un <code>VideoGame</code>.</strong> El índice del blog lo describe con <code>genre</code>, <code>gamePlatform</code>, <code>playMode: 'MultiPlayer'</code> y una <code>Offer</code> gratuita (precio 0). Cada entrada dice que trata <code>about</code> de ese juego, lo que vincula el contenido con el producto.</li>
<li><strong><code>HowTo</code> en las páginas de guía.</strong> Las páginas <code>/game/...</code> salen del mismo motor. Una página puede optar por ello con <code>howto: true</code> en su frontmatter, y la primera lista numerada se convierte en elementos <code>HowToStep</code>. El nombre del paso es el arranque en negrita de cada elemento de la lista, así que el texto visible y el marcado salen de una sola lista.</li>
<li><strong><code>wordCount</code> y <code>timeRequired</code></strong> se calculan, no se escriben a mano.</li>
</ul>
<p>El documento de escenario que describe esta función dice que una prueba comprueba que el JSON-LD se interpreta y que los campos están presentes. Esa es la única protección que considero imprescindible: los datos estructurados fallan en silencio, y una comilla suelta sin escapar puede inutilizar todo el bloque sin ningún error visible.</p>
<h2>Números que no pueden desviarse: marcadores <code>{{f:key}}</code></h2>
<p>Las guías del juego están llenas de números: cuántos cultivos hay, cuánto cuesta una parcela, la comisión del mercado, la tarifa del taxi. En un juego vivo, la economía se ajusta desde un panel de administración. Un número tecleado a mano en un artículo está mal a la semana siguiente.</p>
<p>Así que las páginas de guía usan marcadores, y <code>server/sitefacts.js</code> calcula los valores a partir de los mismos registros que usa el juego (objetos, recetas, catálogo, la tabla de ajuste). Una página dice:</p>
<pre><code class="language-md">Premises: rent from 🪙{{f:unit_rent_min}} a day (up to {{f:rent_biz_max}} rented at once)
or buy for 🪙{{f:unit_buy_min}}–{{f:unit_buy_max}}.
</code></pre>
<p>y el servidor lo rellena en el momento de renderizar:</p>
<pre><code class="language-js">const fillFacts = (md, lang) =&gt; md.replace(/\{\{f:([a-z0-9_]+)\}\}/g, (m, k) =&gt; {
  const v = facts()[k];
  return v == null ? '—' : typeof v === 'number' ? fmtNum(v, lang) : String(v);
});
</code></pre>
<p>Los números se formatean en el idioma del lector. Si el mundo no tiene datos para una clave, la página imprime un guion en lugar de un número incorrecto. Los datos forman parte de la versión de la caché (<code>pages.ver | factsSig | store.ver</code>), de modo que cambiar un valor de la economía en el panel de administración cambia la página renderizada, el ETag y <code>Last-Modified</code>, sin necesidad de un despliegue.</p>
<p>Ese mismo texto es el que exponen <code>llms.txt</code> y <code>llms-full.txt</code>, así que un modelo que lea nuestro sitio obtiene los números actuales y no una copia obsoleta.</p>
<p>Compromiso: las entradas del blog son distintas. Son instantáneas fechadas, y ahí permito números tecleados, porque «precios el día de la redacción» es el enfoque honesto para un artículo fechado. Los marcadores son para las páginas de guía perennes.</p>
<h2>Feeds y mapas del sitio</h2>
<p>Por idioma, servimos RSS 2.0 en <code>/blog/feed.xml</code> (y <code>/blog/es/feed.xml</code>, etc.) y Atom en <code>/blog/atom.xml</code>. El head de cada página enlaza al feed de su propio idioma.</p>
<p>Hay dos mapas del sitio, <code>/sitemap-blog.xml</code> y <code>/sitemap-game.xml</code>. Cada entrada de URL lista sus alternativas hreflang, en el formato de mapa del sitio, con el elemento <code>xhtml:link</code>:</p>
<pre><code class="language-js">${u.alts.map((a) =&gt;
  `&lt;xhtml:link rel="alternate" hreflang="${a.lang}" href="${xml(origin + a.href)}" /&gt;`
).join('\n')}
${en ? `&lt;xhtml:link rel="alternate" hreflang="x-default" href="${xml(origin + en.href)}" /&gt;` : ''}
</code></pre>
<p>Poner hreflang tanto en el head de la página como en el mapa del sitio es redundante a propósito. El mapa del sitio es más fácil de auditar con un script, y el head es lo que ve un rastreador cuando aterriza en una única URL. Si alguna vez discrepan, quieres descubrirlo en una prueba, no en Search Console.</p>
<h2>Velocidad y caché en unas pocas decenas de líneas</h2>
<p>La caché es un <code>Map</code> con clave por tipo, idioma, ruta y origen. Cada entrada guarda el cuerpo renderizado, una versión, un ETag y <code>Last-Modified</code>. Si la versión del almacén no ha cambiado, se devuelven los mismos bytes. El límite es de 600 entradas, y se descarta primero la más antigua.</p>
<pre><code class="language-js">function cached(key, make, verOf = () =&gt; { store.scan(); return store.ver; }) {
  const ver = verOf();
  const hit = cache.get(key);
  if (hit &amp;&amp; hit.ver === ver) return hit;
  const r = make();
  const body = Buffer.from(typeof r === 'string' ? r : r.html);
  const e = { ver, body, etag: etagOf(body),
              lastMod: new Date(Math.floor(lm / 1000) * 1000).toUTCString() };
  cache.set(key, e);
  if (cache.size &gt; 600) cache.delete(cache.keys().next().value);
  return e;
}
</code></pre>
<p>El ETag es un SHA-1 truncado del cuerpo. Es un hash del contenido, así que contenido idéntico da un ETag idéntico entre reinicios. <code>send()</code> responde <code>If-None-Match</code> con un 304 y elige brotli o gzip según <code>Accept-Encoding</code>, comprimiendo de forma perezosa y solo una vez por entrada (los cuerpos de menos de 1 KB se envían tal cual):</p>
<pre><code class="language-js">if (e.body.length &gt; 1024 &amp;&amp; /\bbr\b/.test(ae)) {
  e.br ||= brotliCompressSync(e.body, { params: { [Z.BROTLI_PARAM_QUALITY]: 6 } });
  body = e.br; head['Content-Encoding'] = 'br';
} else if (e.body.length &gt; 1024 &amp;&amp; /\bgzip\b/.test(ae)) {
  e.gz ||= gzipSync(e.body, { level: 7 }); body = e.gz; head['Content-Encoding'] = 'gzip';
}
</code></pre>
<p>Brotli con calidad 6 es un compromiso: mucho mejor que gzip con HTML y lo bastante barato como para hacerlo una vez por página en caché. La calidad 11 sería mala idea en la ruta de una petición. Las respuestas llevan <code>Cache-Control: public, max-age=..., stale-while-revalidate=86400</code> y una cabecera <code>Vary</code> que depende de si la dirección negocia el idioma.</p>
<p>El límite honesto: es una caché en memoria de un solo proceso. Es adecuada para un VPS y unos cientos de páginas. No sobreviviría a escalarla a muchas instancias sin una capa compartida o una CDN delante. Para este sitio es un buen compromiso.</p>
<h2>Detección de idioma sin perjudicar a los rastreadores</h2>
<p>La dirección en inglés sin prefijo tiene doble personalidad. Para una persona debería redirigir a su idioma. Para un rastreador debe devolver siempre la misma página en inglés, o el índice se vuelve inestable.</p>
<p>La regla de <code>visitorLang()</code> se ejecuta en este orden: el parámetro de consulta <code>?lang=</code>, luego la cookie que fija el juego o la página de inicio (<code>tw_lang</code>), luego una comprobación de bots y solo después <code>Accept-Language</code>. La comprobación de bots es una expresión regular sobre el User-Agent que cubre rastreadores de buscadores, recuperadores de vistas previas de enlaces y agentes de IA:</p>
<pre><code class="language-js">const BOT = /bot\b|bot\/|crawl|spider|slurp|facebookexternalhit|whatsapp|telegram|slack|discord
  |linkedin|preview|google|bing|yandex|applebot|gptbot|claude|anthropic|perplexity|ccbot
  |bytespider|amazonbot|duckassist|cohere|mistral|headless/i;

if (BOT.test(String(req.headers['user-agent'] || ''))) return DEFAULT_LANG;
</code></pre>
<p>(La lista real es algo más larga y aquí la he acortado.) Un bot recibe inglés sin redirección. Una redirección para una persona es un 302 con <code>Vary: Accept-Language, Cookie</code> y <code>no-store</code>, de modo que ninguna caché fije nunca a una persona en el idioma equivocado. La redirección solo ocurre si la página existe en ese idioma; si no, el visitante se queda en la página en inglés.</p>
<p>¿Es frágil comparar user agents con expresiones regulares? Sí. Cualquier bot nuevo que no esté en la lista se tratará como una persona. Pero la mayoría de los rastreadores no envían ninguna cabecera <code>Accept-Language</code>, así que de todos modos caen en inglés. La expresión regular protege sobre todo el caso de un bot de vista previa que sí envía una.</p>
<p>La página de inicio en <code>/</code> usa la misma idea con un esquema de URL distinto: <code>/?lang=es</code> para cada idioma, hreflang para cada diccionario y <code>x-default</code> apuntando al origen sin más. El servidor traduce el texto fuente en ruso de la página con los mismos diccionarios que usa el juego y guarda en caché el HTML terminado por idioma. Las URL para compartir llevan el <code>?lang=</code> de quien compartió, así que un bot de vista previa, que no envía <code>Accept-Language</code>, renderiza la tarjeta en el idioma de quien la compartió.</p>
<h2>404 que son realmente 404</h2>
<p>Una página de no encontrado devuelve el estado 404 con <code>Cache-Control: no-cache</code>, <code>noindex, follow</code> y sin alternativas hreflang. Es una página real, con las tres últimas entradas y un enlace al blog y a la página de inicio, para que una persona que se haya equivocado al escribir una URL tenga adónde ir. El modo de fallo que evitamos es el soft 404, una página amable servida con estado 200 que un buscador indexará como duplicado.</p>
<p>Las barras finales se redirigen con un 301 a la ruta limpia. Los nombres de etiquetas se validan con una expresión regular antes de cualquier búsqueda, y un slug tiene que pasar <code>validSlug</code>. Estas comprobaciones mantienen finito y aburrido el número de URL rastreables.</p>
<h2>Markdown para máquinas: <code>/blog/&lt;slug&gt;.md</code>, <code>llms.txt</code>, <code>llms-full.txt</code></h2>
<p>Cada entrada existe en tres representaciones: HTML para las personas, JSON-LD para los buscadores y markdown para los modelos de lenguaje. El markdown está disponible en la dirección de la entrada más <code>.md</code>, y el head HTML lo anuncia:</p>
<pre><code class="language-html">&lt;link rel="alternate" type="text/markdown" href="https://towneers.world/blog/farming-guide.md" /&gt;
</code></pre>
<p>La copia en markdown no es el archivo fuente sin más. Una función <code>plainMarkdown()</code> la produce a partir de la entrada analizada: los bloques personalizados se aplanan, los iconos de objetos se sustituyen por los nombres de los objetos, se rellenan los datos y los bloques «pruébalo» se convierten en enlaces normales con la URL del enlace directo. No hay scripts, ni navegación, ni maquetación.</p>
<p><code>/llms.txt</code> sigue el formato de llmstxt.org. Describe el juego, enlaza las páginas y entradas clave como URL <code>.md</code>, y lista los feeds, los mapas del sitio y los archivos de texto completo por idioma. <code>/llms-full.txt</code> contiene el texto completo de cada página de guía y entrada en inglés, y <code>/llms-full-es.txt</code>, <code>-de.txt</code>, <code>-uk.txt</code>, <code>-ru.txt</code> hacen lo mismo por idioma.</p>
<p>No afirmaré que <code>llms.txt</code> mejore el posicionamiento. No hay pruebas públicas de que los grandes buscadores lo usen como señal de posicionamiento, y lo que se dice en línea es sobre todo especulación. Mi motivo para mantenerlo es más modesto: es una función en caché sobre datos que ya tenemos, y algunos agentes y herramientas para desarrolladores sí lo recuperan. Los endpoints <code>.md</code> cuestan casi nada y dan a cualquier recuperador una copia limpia que citar.</p>
<h2>robots.txt: la decisión sobre los rastreadores de IA</h2>
<p>El archivo es estático (<code>client/robots.txt</code>) y la decisión está escrita en un comentario al principio: los rastreadores de IA y los asistentes de búsqueda con IA son bienvenidos en el sitio y en el blog. La lista nombra GPTBot, OAI-SearchBot, ChatGPT-User, ClaudeBot, Claude-User, Claude-SearchBot, PerplexityBot, Perplexity-User, Google-Extended, Applebot-Extended, CCBot, Meta-ExternalAgent, Bytespider, Amazonbot, DuckAssistBot, cohere-ai y MistralAI-User. Todos reciben las mismas reglas que los demás:</p>
<pre><code>User-agent: *
Allow: /
Allow: /blog/
Allow: /game/
Allow: /llms.txt
Allow: /llms-full.txt
Disallow: /admin/
Disallow: /api/
Disallow: /pay/
Disallow: /play

Sitemap: https://towneers.world/sitemap-blog.xml
Sitemap: https://towneers.world/sitemap-game.xml
</code></pre>
<p>Dos cosas merecen una nota. Primero, repetir las reglas para cada agente con nombre es necesario en la práctica: un rastreador que encuentra un grupo con su propio nombre ignora el grupo <code>*</code>, así que un grupo explícito con solo líneas <code>Allow</code> ocultaría las líneas <code>Disallow</code>. Las repetimos. Segundo, <code>/play</code>, el juego en sí, está prohibido para todos. No hay nada que indexar en un canvas, y los rastreadores no deberían crear sesiones.</p>
<p>Es una decisión de negocio y no técnica. Para un juego gratuito que vive del boca a boca, que te recomiende un asistente es distribución, así que optamos por participar. Si tu contenido es tu producto, puedes decidir lo contrario. Lo importante es hacer explícita la decisión y escribir el razonamiento en el archivo, de modo que revertirla más adelante signifique borrar unas pocas líneas.</p>
<h2>IndexNow: avisar a los buscadores en lugar de esperar</h2>
<p>Los mapas del sitio se consultan periódicamente, así que una entrada nueva puede tardar días en ser detectada. IndexNow es un protocolo de notificación activa que admiten Bing, Yandex, Seznam y otros, y el índice de Bing es una de las fuentes de varios productos de búsqueda con IA. <code>server/indexnow.js</code> tiene 75 líneas y ninguna dependencia.</p>
<p>Solo en producción, genera una vez una clave de 32 caracteres hexadecimales y la guarda en el directorio de datos. La sirve como <code>/&lt;key&gt;.txt</code>, que es como el protocolo verifica que eres el dueño del host. Después, con un temporizador, lee nuestros propios mapas del sitio (las mismas funciones que los sirven) y compara cada <code>lastmod</code> con un pequeño archivo JSON de lo que ya se envió:</p>
<pre><code class="language-js">export function changedUrls(entries, sent) {
  return entries.filter((e) =&gt; e.loc.startsWith(ORIGIN + '/') &amp;&amp; sent[e.loc] !== e.lastmod);
}
// ...
const r = await fetchFn(API, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json; charset=utf-8' },
  body: JSON.stringify({ host: HOST, key, keyLocation: `${ORIGIN}/${key}.txt`,
                         urlList: list.map((e) =&gt; e.loc) }),
  signal: AbortSignal.timeout(15000),
});
if (r.status !== 200 &amp;&amp; r.status !== 202) return 0;   // reintento en el siguiente ciclo
</code></pre>
<p>Se ejecuta por primera vez dos minutos después del arranque y luego cada 30 minutos, y envía como máximo 10 000 URL por llamada. Solo <code>200</code> y <code>202</code> cuentan como éxito, y solo entonces las URL se registran como enviadas, de modo que una llamada fallida se reintenta en el siguiente ciclo. El mapa del sitio es la única fuente de verdad sobre lo que cambió: sin ganchos en el panel de administración ni en el script de despliegue, sin una lista aparte que mantener. Un interruptor de entorno <code>INDEXNOW=off</code> lo desactiva. Los temporizadores llevan <code>unref()</code> para que nunca mantengan vivo el proceso.</p>
<p>Google no admite IndexNow, así que para Google los mapas del sitio siguen siendo la vía de entrada.</p>
<h2>Del artículo al juego: enlaces directos</h2>
<p>Un blog que no puede enviar a un lector al producto es solo un blog. El bloque <code>:::try</code> renderiza una llamada a la acción que abre el juego en un lugar concreto, <code>/play?go=&lt;place&gt;</code>, de una lista blanca fija (<code>funfair</code>, <code>fame</code>, <code>square</code>, <code>market</code>, <code>carshop</code>, <code>realty</code>, <code>cottages</code>, <code>farms</code>, <code>beach</code>, <code>park</code>, <code>football</code>). El cliente lee el parámetro y le muestra al jugador el camino hasta ese lugar. Un valor desconocido recurre a un enlace simple <code>start=new</code>.</p>
<p>El servidor añade parámetros UTM, con el slug de la entrada como campaña:</p>
<pre><code class="language-js">const playUrl = (campaign) =&gt; (go) =&gt;
  `/play?${GO_PLACES.includes(go) ? `go=${go}&amp;` : 'start=new&amp;'}` +
  `utm_source=blog&amp;utm_medium=blog&amp;utm_campaign=${encodeURIComponent(campaign)}`;
</code></pre>
<p>Así cada entrada es medible como canal, y la copia en markdown contiene el mismo enlace. Como <code>/play</code> está prohibido en robots.txt, estos enlaces son para personas, no para que los sigan los rastreadores.</p>
<h2>Qué haría de otra manera</h2>
<ul>
<li><strong>Probar el head, no solo el cuerpo.</strong> Nuestro documento de escenario dice que una prueba verifica que el JSON-LD se interpreta y que los campos existen. Añadiría una comprobación de que cada destino hreflang devuelve 200 y enlaza de vuelta, porque los enlaces de retorno rotos hacen que hreflang se ignore.</li>
<li><strong>No fiarse de que aparezca un resultado enriquecido.</strong> Los datos estructurados dan elegibilidad, no una promesa.</li>
<li><strong>Mantener la caché honesta.</strong> Un contador de versión es más simple que invalidar por clave, pero tira todo cuando cambia una sola entrada. A nuestro tamaño cuesta milisegundos. Con diez mil páginas no sería así.</li>
<li><strong>Medir directamente los referidos de IA.</strong> Las etiquetas UTM solo funcionan cuando el asistente las conserva. Los registros del servidor por user agent son la otra mitad del panorama.</li>
</ul>
<h2>Lista de comprobación</h2>
<ol>
<li>Renderiza el texto en el servidor. No hace falta JS en el cliente para leer una página.</li>
<li>Una URL canónica por página. Redirige con 301 los duplicados del estilo <code>/en/</code> y las barras finales.</li>
<li>hreflang solo para los idiomas que realmente existen, más <code>x-default</code>. Ponlo en el head y en el mapa del sitio.</li>
<li>Páginas de respaldo sin traducir: muestra algo útil, canonical al original, <code>noindex, follow</code>.</li>
<li>Estado 404 real, <code>noindex</code>, sin alternativas.</li>
<li>Open Graph con el tamaño de la imagen, <code>og:locale</code> y sus alternativas; una portada de 1200×630.</li>
<li>JSON-LD con <code>@id</code> estables: <code>BlogPosting</code>, <code>BreadcrumbList</code>, <code>FAQPage</code>, <code>HowTo</code> y un <code>VideoGame</code> para el producto.</li>
<li>Genera el marcado de la FAQ a partir de la misma lista que renderiza la FAQ visible.</li>
<li>Pon los números cambiantes detrás de marcadores calculados a partir de datos en vivo.</li>
<li>ETag a partir de un hash del contenido, <code>Last-Modified</code>, <code>Cache-Control</code> con <code>stale-while-revalidate</code>, brotli con gzip como alternativa.</li>
<li>Nunca redirijas a los bots por idioma. Comprueba el User-Agent antes que <code>Accept-Language</code>.</li>
<li>RSS y Atom por idioma, enlazados desde el head.</li>
<li>Mapas del sitio con alternativas hreflang; lístalos en robots.txt.</li>
<li>Una copia en markdown de cada página, enlazada con <code>rel="alternate" type="text/markdown"</code>, y un <code>llms.txt</code> sobre ellas.</li>
<li>Decide tu política para los rastreadores de IA a propósito, repite las reglas disallow en cada grupo con nombre y escribe el razonamiento en el archivo.</li>
<li>Notifica los cambios con IndexNow desde tu propio mapa del sitio y registra lo que se envió.</li>
<li>Enlaza desde el contenido al producto con enlaces directos y etiquetas UTM en cada enlace.</li>
</ol>
<p>Nada de esto necesita un framework. Necesita un módulo que trate cada página como datos y la renderice de varias maneras.</p>
<p>Si quieres ver qué sirve todo esto, el juego es gratuito y funciona en cualquier navegador. <a href="https://towneers.world/r/hashnode?utm_campaign=seo-es&amp;utm_content=article">towneers.world</a></p>
]]></content:encoded></item><item><title><![CDATA[SEO and AI search for a browser game in plain Node.js: hreflang, JSON-LD, llms.txt and IndexNow without a framework]]></title><description><![CDATA[Disclosure: I build Towneers, a free multiplayer life sim in the browser. This is a write-up of how its site and blog are served. Everything below comes…]]></description><link>https://towneers.hashnode.dev/seo-and-ai-search-for-a-browser-game-in-plain-node-js-hreflang-json-ld-llms-txt-and-indexnow-without-a-framework</link><guid isPermaLink="true">https://towneers.hashnode.dev/seo-and-ai-search-for-a-browser-game-in-plain-node-js-hreflang-json-ld-llms-txt-and-indexnow-without-a-framework</guid><category><![CDATA[SEO]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[Game Development]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Towneers]]></dc:creator><pubDate>Fri, 27 Nov 2026 12:18:46 GMT</pubDate><content:encoded><![CDATA[<p><em>Disclosure: I build Towneers, a free multiplayer life sim in the browser. This is a write-up of how its site and blog are served. Everything below comes from the real code, simplified for reading.</em></p>
<p>A browser game has an awkward SEO problem. The product is a canvas and a WebSocket, which a crawler sees as an empty page. The words that can rank, and that an AI assistant can quote, live somewhere else: a landing page, a game guide and a blog.</p>
<p>We decided not to bolt on a CMS or a static-site generator. The server already runs on plain Node.js, and the only runtime dependency is <code>ws</code>. So the blog is a single server module that renders HTML from markdown files. It also serves the machine-readable extras: feeds, sitemaps, <code>llms.txt</code> and a markdown copy of every post. This article walks through the decisions and the trade-offs.</p>
<h2>The shape of the system</h2>
<p>Posts are files: <code>content/blog/&lt;slug&gt;/&lt;lang&gt;.md</code>, five languages (en, es, de, uk, ru). One module, <code>server/blog.js</code>, reads them, renders HTML on demand and caches the result in memory. The same engine also serves the <code>/game/...</code> guide pages, so there is only one place that knows how to emit <code>&lt;head&gt;</code>.</p>
<p>The header comment of the module lists what it promises: server-rendered text without scripts, a per-address and per-language in-memory cache, ETag and Last-Modified, gzip/brotli, canonical, hreflang with x-default, Open Graph, JSON-LD, RSS/Atom per language, a blog sitemap, <code>/llms.txt</code>, <code>/llms-full.txt</code> and a markdown version of each post at <code>/blog/&lt;slug&gt;.md</code>.</p>
<p>Why server rendering and not an SPA shell? A crawler, a link-preview bot and an LLM fetcher all share one trait: most of them do not run your JavaScript, or do not run it reliably. Plain HTML from a function is the most portable answer. The blog pages ship no framework code at all.</p>
<h2>Posts as files, with a tiny frontmatter</h2>
<p>A post starts with a few lines of frontmatter. The parser in <code>shared/blog.js</code> is about twenty lines and handles only what we need: strings, <code>[a, b]</code> lists and booleans.</p>
<pre><code class="language-js">export function parseFront(src) {
  const text = String(src ?? '').replace(/^﻿/, '').replace(/\r\n?/g, '\n');
  const m = /^---\n([\s\S]*?)\n---\n?/.exec(text);
  if (!m) return { meta: {}, body: text };
  const meta = {};
  for (const line of m[1].split('\n')) {
    const mm = /^([A-Za-z_][\w-]*)\s*:\s*(.*)$/.exec(line);
    if (!mm) continue;
    let v = mm[2].trim();
    if (/^\[.*\]$/.test(v)) v = v.slice(1, -1).split(',').map((x) =&gt; unq(x.trim())).filter(Boolean);
    else if (v === 'true' || v === 'false') v = v === 'true';
    else v = unq(v);
    meta[mm[1]] = v;
  }
  return { meta, body: text.slice(m[0].length) };
}
</code></pre>
<p>The fields are <code>title</code>, <code>description</code>, <code>summary</code>, <code>date</code>, <code>tags</code>, <code>cover</code> and <code>coverAlt</code>. A real post, trimmed:</p>
<pre><code class="language-yaml">---
title: "Farming in Towneers: from your first seeds to a three-star harvest"
description: "A deep farming guide: plot prices, tools, all 9 crops, 5 seed tiers..."
date: 2026-11-27
tags: [guides, money]
cover: /landing/img/blog/farming-cover.webp
coverAlt: "A farm plot in North Farms at sunset..."
---
</code></pre>
<p>The decision here was to keep content in the repo, next to the code, and not in a database. Posts are reviewed and versioned like code. On the production server, edits made in the admin panel are written to a data directory that sits on top of the repo files. A store class re-scans the directories when the file signature changes, at most once every two seconds, and bumps a version counter. That counter is what invalidates the cache later.</p>
<h2>Custom blocks: FAQ, "try it" and tips</h2>
<p>Markdown alone cannot express a FAQ that should become <code>FAQPage</code> markup, or a button that deep-links into the game. The renderer adds a small block syntax on top of markdown: <code>:::faq</code>, <code>:::try</code>, <code>:::tip</code>, plus <code>:::news</code> and <code>:::items</code>.</p>
<pre><code class="language-md">:::try farms | ▶ Show me North Farms
...
:::

:::faq
### How much does a farm plot cost?
🪙2,700–5,400 right now. It depends on the size, and you can own up to 4 plots.
:::
</code></pre>
<p>The renderer collects every question and answer from a <code>:::faq</code> block into a list while it renders. That one list then feeds two outputs: the visible questions and answers, and the JSON-LD. Authors write the FAQ once and cannot make the markup disagree with the page. This "one source, several renderings" idea shows up again in the markdown copy and in <code>llms.txt</code>.</p>
<p>A caveat worth saying out loud: Google restricted FAQ rich results to a narrow set of sites some time ago, so you should not expect a FAQ snippet in the results. We still emit <code>FAQPage</code> because the structured question-and-answer pairs are cheap to produce and are exactly the shape that answer engines like to lift.</p>
<h2>The head: canonical, hreflang, Open Graph</h2>
<p>One function, <code>page()</code>, builds the whole document. This is the part of the head that matters for multilingual SEO, reduced to the essentials:</p>
<pre><code class="language-js">const xdef = alts.find((a) =&gt; a.lang === 'en');
return `&lt;!doctype html&gt;
&lt;html lang="${lang}" dir="ltr"&gt;
&lt;head&gt;
  &lt;title&gt;${esc(title)}&lt;/title&gt;
  &lt;meta name="description" content="${esc(desc)}" /&gt;
  &lt;meta name="robots" content="${robots}" /&gt;
  &lt;link rel="canonical" href="${abs(canonical)}" /&gt;
  ${alts.map((a) =&gt; `&lt;link rel="alternate" hreflang="${a.lang}" href="${abs(a.href)}" /&gt;`).join('\n  ')}
  ${xdef ? `&lt;link rel="alternate" hreflang="x-default" href="${abs(xdef.href)}" /&gt;` : ''}
  &lt;meta property="og:type" content="${ogType}" /&gt;
  &lt;meta property="og:locale" content="${ogLocale(lang)}" /&gt;
</code></pre>
<p>Three decisions are baked into this.</p>
<p><strong>hreflang lists only languages that exist.</strong> A post has <code>alts</code> for the languages where a file is present, not for all five. Many sites generate alternates for every locale and point half of them at pages that do not exist or silently show English. We do not.</p>
<p><strong>x-default is English.</strong> English lives at the unprefixed address (<code>/blog/...</code>), the other languages at <code>/blog/es/...</code>, <code>/blog/de/...</code> and so on. A request for <code>/blog/en/...</code> is redirected with a 301 to the unprefixed form so there is exactly one URL per page.</p>
<p><strong>Untranslated pages are noindexed.</strong> If a post has no Spanish file, the Spanish address still works, because we do not want a dead end for a reader. It shows the English text with a "only in English for now" note. But the canonical points at the English URL and the robots meta becomes <code>noindex, follow</code>:</p>
<pre><code class="language-js">const fallback = v.lang !== lang;
const canonical = fallback ? postPath('en', slug) : path;
// ...
robots: fallback || preview ? 'noindex, follow'
                            : 'index, follow, max-image-preview:large, max-snippet:-1',
</code></pre>
<p>There is no machine translation. A real translation is a separate file, and until it exists the page does not compete with itself in the index. Note <code>max-snippet:-1</code> and <code>max-image-preview:large</code> on real pages: we want long snippets, both for search and for AI answers.</p>
<p>Open Graph includes image width and height, <code>og:locale</code> and <code>og:locale:alternate</code> for the other languages, and <code>article:published_time</code>, <code>article:modified_time</code> and <code>article:tag</code> on posts. The cover image is a 1200×630 file. Link-preview bots (Telegram, Slack, WhatsApp and the rest) matter more for a social game than any search engine, and they read exactly these tags.</p>
<h2>JSON-LD: one graph per page type</h2>
<p>Every post carries a <code>BlogPosting</code> plus a <code>BreadcrumbList</code>, and a <code>FAQPage</code> when the post has questions. This is the <code>BlogPosting</code> block, shortened:</p>
<pre><code class="language-js">const postLd = {
  '@context': 'https://schema.org', '@type': 'BlogPosting', '@id': `${url}#post`,
  headline: v.title.slice(0, 110), description: v.description, url, inLanguage: v.lang,
  mainEntityOfPage: { '@type': 'WebPage', '@id': url },
  datePublished: `${v.date}T12:00:00Z`, dateModified: `${v.updated}T12:00:00Z`,
  author: { '@type': 'Organization', name: v.author || bt(v.lang, 'team'), url: `${origin}/` },
  publisher: { '@type': 'Organization', '@id': `${origin}/#org`, name: SITE, url: `${origin}/` },
  about: { '@type': 'VideoGame', name: SITE, url: `${origin}/` },
  wordCount: v.words, timeRequired: `PT${v.minutes}M`,
};
</code></pre>
<p>Notes on the choices:</p>
<ul>
<li><strong>Stable <code>@id</code>s.</strong> <code>#post</code>, <code>#faq</code>, <code>#org</code>, <code>#game</code>. The organization and the game are referenced by id from many pages, so a consumer can merge them into one entity.</li>
<li><strong>The game is a <code>VideoGame</code>.</strong> The blog index describes it with <code>genre</code>, <code>gamePlatform</code>, <code>playMode: 'MultiPlayer'</code> and a free <code>Offer</code> (price 0). Every post says it is <code>about</code> that game, which ties the content to the product.</li>
<li><strong><code>HowTo</code> on guide pages.</strong> The <code>/game/...</code> pages come from the same engine. A page can opt in with <code>howto: true</code> in its frontmatter, and the first numbered list becomes <code>HowToStep</code> items. The step name is the bold lead of each list item, so the visible text and the markup come from one list.</li>
<li><strong><code>wordCount</code> and <code>timeRequired</code></strong> are computed, not typed by hand.</li>
</ul>
<p>The scenario document that describes this feature says a test checks that the JSON-LD parses and the fields are present. That is the only guard I would insist on: structured data fails silently, and a stray unescaped quote can make the whole block useless without any visible error.</p>
<h2>Numbers that cannot drift: <code>{{f:key}}</code> placeholders</h2>
<p>Game guides are full of numbers: how many crops, what a plot costs, the market fee, the taxi fare. In a living game, the economy is tuned from an admin panel. A hand-typed number in an article is wrong the week after.</p>
<p>So guide pages use placeholders, and <code>server/sitefacts.js</code> computes the values from the same registries the game uses (items, recipes, catalog, the tuning table). A page says:</p>
<pre><code class="language-md">Premises: rent from 🪙{{f:unit_rent_min}} a day (up to {{f:rent_biz_max}} rented at once)
or buy for 🪙{{f:unit_buy_min}}–{{f:unit_buy_max}}.
</code></pre>
<p>and the server fills it in at render time:</p>
<pre><code class="language-js">const fillFacts = (md, lang) =&gt; md.replace(/\{\{f:([a-z0-9_]+)\}\}/g, (m, k) =&gt; {
  const v = facts()[k];
  return v == null ? '—' : typeof v === 'number' ? fmtNum(v, lang) : String(v);
});
</code></pre>
<p>Numbers are formatted in the reader's language. If the world has no data for a key, the page prints a dash instead of a wrong number. The facts are part of the cache version (<code>pages.ver | factsSig | store.ver</code>), so changing an economy value in the admin changes the rendered page, the ETag and <code>Last-Modified</code>, without a deploy.</p>
<p>The same text is what <code>llms.txt</code> and <code>llms-full.txt</code> expose, so a model that reads our site gets the current numbers and not a stale copy.</p>
<p>Trade-off: blog posts are different. They are dated snapshots, and there I allow typed numbers, because "prices on the day of writing" is the honest framing for a dated article. Placeholders are for the evergreen guide pages.</p>
<h2>Feeds and sitemaps</h2>
<p>Per language, we serve RSS 2.0 at <code>/blog/feed.xml</code> (and <code>/blog/es/feed.xml</code> and so on) and Atom at <code>/blog/atom.xml</code>. Each page's head links to the feed of its own language.</p>
<p>There are two sitemaps, <code>/sitemap-blog.xml</code> and <code>/sitemap-game.xml</code>. Each URL entry lists its hreflang alternates, in the sitemap format, with the <code>xhtml:link</code> element:</p>
<pre><code class="language-js">${u.alts.map((a) =&gt;
  `&lt;xhtml:link rel="alternate" hreflang="${a.lang}" href="${xml(origin + a.href)}" /&gt;`
).join('\n')}
${en ? `&lt;xhtml:link rel="alternate" hreflang="x-default" href="${xml(origin + en.href)}" /&gt;` : ''}
</code></pre>
<p>Putting hreflang in both the page head and the sitemap is redundant by design. The sitemap is easier to audit with a script, and the head is what a crawler sees when it lands on a single URL. If they ever disagree, you want to find that out in a test, not in Search Console.</p>
<h2>Speed and caching in a few dozen lines</h2>
<p>The cache is a <code>Map</code> keyed by kind, language, path and origin. Each entry stores the rendered body, a version, an ETag and <code>Last-Modified</code>. If the store version has not changed, the same bytes come back. The cap is 600 entries, and the oldest one is dropped first.</p>
<pre><code class="language-js">function cached(key, make, verOf = () =&gt; { store.scan(); return store.ver; }) {
  const ver = verOf();
  const hit = cache.get(key);
  if (hit &amp;&amp; hit.ver === ver) return hit;
  const r = make();
  const body = Buffer.from(typeof r === 'string' ? r : r.html);
  const e = { ver, body, etag: etagOf(body),
              lastMod: new Date(Math.floor(lm / 1000) * 1000).toUTCString() };
  cache.set(key, e);
  if (cache.size &gt; 600) cache.delete(cache.keys().next().value);
  return e;
}
</code></pre>
<p>The ETag is a truncated SHA-1 of the body. That is a content hash, so identical content gives an identical ETag across restarts. <code>send()</code> answers <code>If-None-Match</code> with a 304 and picks brotli or gzip from <code>Accept-Encoding</code>, compressing lazily and only once per entry (bodies under 1 KB are sent as-is):</p>
<pre><code class="language-js">if (e.body.length &gt; 1024 &amp;&amp; /\bbr\b/.test(ae)) {
  e.br ||= brotliCompressSync(e.body, { params: { [Z.BROTLI_PARAM_QUALITY]: 6 } });
  body = e.br; head['Content-Encoding'] = 'br';
} else if (e.body.length &gt; 1024 &amp;&amp; /\bgzip\b/.test(ae)) {
  e.gz ||= gzipSync(e.body, { level: 7 }); body = e.gz; head['Content-Encoding'] = 'gzip';
}
</code></pre>
<p>Brotli at quality 6 is a compromise: much better than gzip on HTML, and cheap enough to do once per cached page. Quality 11 would be a bad idea on a request path. Responses carry <code>Cache-Control: public, max-age=..., stale-while-revalidate=86400</code> and a <code>Vary</code> header that depends on whether the address is language-negotiated.</p>
<p>The honest limit: this is a single-process, in-memory cache. It is right for one VPS and a few hundred pages. It would not survive being scaled to many instances without a shared layer or a CDN in front. For this site that is a fine trade.</p>
<h2>Language detection without hurting crawlers</h2>
<p>The unprefixed English address has a split personality. For a human it should redirect to their language. For a crawler it must return the same English page every time, or the index becomes unstable.</p>
<p>The rule in <code>visitorLang()</code> runs in this order: the <code>?lang=</code> query parameter, then the cookie set by the game or the landing page (<code>tw_lang</code>), then a bot check, and only then <code>Accept-Language</code>. The bot check is a regex over the User-Agent that covers search crawlers, link-preview fetchers and AI agents:</p>
<pre><code class="language-js">const BOT = /bot\b|bot\/|crawl|spider|slurp|facebookexternalhit|whatsapp|telegram|slack|discord
  |linkedin|preview|google|bing|yandex|applebot|gptbot|claude|anthropic|perplexity|ccbot
  |bytespider|amazonbot|duckassist|cohere|mistral|headless/i;

if (BOT.test(String(req.headers['user-agent'] || ''))) return DEFAULT_LANG;
</code></pre>
<p>(The real list is somewhat longer and I have shortened it here.) A bot gets English without a redirect. A redirect for a human is a 302 with <code>Vary: Accept-Language, Cookie</code> and <code>no-store</code>, so no cache ever pins a person to the wrong language. The redirect only happens if the page exists in that language, otherwise the visitor stays on the English page.</p>
<p>Is regex-matching user agents fragile? Yes. Any new bot that is not on the list will be treated like a person. But most crawlers send no <code>Accept-Language</code> header at all, so they fall through to English anyway. The regex mostly protects the case of a preview bot that does send one.</p>
<p>The landing page at <code>/</code> uses the same idea with a different URL scheme: <code>/?lang=es</code> for each language, hreflang for every dictionary, and <code>x-default</code> pointing at the bare origin. The server translates the Russian source of the page with the same dictionaries the game uses and caches the finished HTML per language. Link-share URLs carry <code>?lang=</code> of the person who shared, so a preview bot, which sends no <code>Accept-Language</code>, renders the card in the sharer's language.</p>
<h2>404s that are really 404s</h2>
<p>A not-found page returns status 404 with <code>Cache-Control: no-cache</code>, <code>noindex, follow</code>, and no hreflang alternates. It is a real page, with the latest three posts and a link to the blog and the home page, so a human who mistyped a URL has somewhere to go. The failure mode we avoid is the soft 404, a friendly page served with status 200 that a search engine will index as a duplicate.</p>
<p>Trailing slashes are redirected with a 301 to the clean path. Tag names are validated with a regex before any lookup, and a slug has to pass <code>validSlug</code>. These checks keep the number of crawlable URLs finite and boring.</p>
<h2>Markdown for machines: <code>/blog/&lt;slug&gt;.md</code>, <code>llms.txt</code>, <code>llms-full.txt</code></h2>
<p>Each post exists in three renderings: HTML for people, JSON-LD for search engines, and markdown for language models. Markdown is available at the post address plus <code>.md</code>, and the HTML head advertises it:</p>
<pre><code class="language-html">&lt;link rel="alternate" type="text/markdown" href="https://towneers.world/blog/farming-guide.md" /&gt;
</code></pre>
<p>The markdown copy is not the raw source file. A function <code>plainMarkdown()</code> produces it from the parsed post: the custom blocks are flattened, item icons are replaced with item names, the facts are filled in, and "try it" blocks become ordinary links with the deep-link URL. There are no scripts, no navigation and no layout.</p>
<p><code>/llms.txt</code> follows the llmstxt.org layout. It describes the game, links to the key pages and posts as <code>.md</code> URLs, and lists feeds, sitemaps, and the per-language full-text files. <code>/llms-full.txt</code> contains the full text of every English guide page and post, and <code>/llms-full-es.txt</code>, <code>-de.txt</code>, <code>-uk.txt</code>, <code>-ru.txt</code> do the same per language.</p>
<p>I will not claim that <code>llms.txt</code> moves rankings. There is no public evidence that the major engines use it as a ranking signal, and the claims about it online are mostly speculation. My reason to keep it is cheaper: it is one cached function over data we already have, and some agents and developer tools do fetch it. The <code>.md</code> endpoints cost almost nothing and give any fetcher a clean copy to quote.</p>
<h2>robots.txt: the AI crawler decision</h2>
<p>The file is static (<code>client/robots.txt</code>) and the decision is written in a comment at the top: AI crawlers and AI search assistants are welcome on the site and the blog. The list names GPTBot, OAI-SearchBot, ChatGPT-User, ClaudeBot, Claude-User, Claude-SearchBot, PerplexityBot, Perplexity-User, Google-Extended, Applebot-Extended, CCBot, Meta-ExternalAgent, Bytespider, Amazonbot, DuckAssistBot, cohere-ai and MistralAI-User. Every one gets the same rules as everybody else:</p>
<pre><code>User-agent: *
Allow: /
Allow: /blog/
Allow: /game/
Allow: /llms.txt
Allow: /llms-full.txt
Disallow: /admin/
Disallow: /api/
Disallow: /pay/
Disallow: /play

Sitemap: https://towneers.world/sitemap-blog.xml
Sitemap: https://towneers.world/sitemap-game.xml
</code></pre>
<p>Two things deserve a note. First, repeating the rules for each named agent is required in practice: a crawler that finds a group for its own name ignores the <code>*</code> group, so an explicit group with only <code>Allow</code> lines would otherwise hide the <code>Disallow</code> lines. We repeat them. Second, <code>/play</code>, the game itself, is disallowed for everyone. There is nothing to index in a canvas, and crawlers should not create sessions.</p>
<p>This is a business decision and not a technical one. For a free game that lives on word of mouth, being recommended by an assistant is distribution, so we opted in. If your content is your product, you may decide the opposite. The point is to make the decision explicit and write the reasoning in the file, so that reversing it later means deleting a few lines.</p>
<h2>IndexNow: telling search engines instead of waiting</h2>
<p>Sitemaps are polled, so a new post can wait days to be noticed. IndexNow is a push protocol supported by Bing, Yandex, Seznam and others, and Bing's index is one of the feeds behind several AI search products. <code>server/indexnow.js</code> is 75 lines with no dependencies.</p>
<p>On production only, it generates a 32-hex key once and stores it in the data directory. It serves the key as <code>/&lt;key&gt;.txt</code>, which is how the protocol verifies that you own the host. Then, on a timer, it reads our own sitemaps (the same functions that serve them) and compares each <code>lastmod</code> with a small JSON file of what it already sent:</p>
<pre><code class="language-js">export function changedUrls(entries, sent) {
  return entries.filter((e) =&gt; e.loc.startsWith(ORIGIN + '/') &amp;&amp; sent[e.loc] !== e.lastmod);
}
// ...
const r = await fetchFn(API, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json; charset=utf-8' },
  body: JSON.stringify({ host: HOST, key, keyLocation: `${ORIGIN}/${key}.txt`,
                         urlList: list.map((e) =&gt; e.loc) }),
  signal: AbortSignal.timeout(15000),
});
if (r.status !== 200 &amp;&amp; r.status !== 202) return 0;   // retry on the next tick
</code></pre>
<p>It first runs two minutes after start, then every 30 minutes, and sends at most 10,000 URLs per call. Only <code>200</code> and <code>202</code> count as success, and only then are the URLs recorded as sent, so a failed call is retried by the next tick. The sitemap is the single source of truth for what changed: no hooks in the admin or the deploy script, no separate list to maintain. An <code>INDEXNOW=off</code> environment switch disables it. The timers are <code>unref()</code>'d so they never keep the process alive.</p>
<p>Google does not support IndexNow, so for Google the sitemaps remain the way in.</p>
<h2>From article to game: deep links</h2>
<p>A blog that cannot send a reader into the product is just a blog. The <code>:::try</code> block renders a call-to-action that opens the game at a specific place, <code>/play?go=&lt;place&gt;</code>, from a fixed whitelist (<code>funfair</code>, <code>fame</code>, <code>square</code>, <code>market</code>, <code>carshop</code>, <code>realty</code>, <code>cottages</code>, <code>farms</code>, <code>beach</code>, <code>park</code>, <code>football</code>). The client reads the parameter and shows the player the way to that place. An unknown value falls back to a plain <code>start=new</code> link.</p>
<p>The server appends UTM parameters, with the post slug as the campaign:</p>
<pre><code class="language-js">const playUrl = (campaign) =&gt; (go) =&gt;
  `/play?${GO_PLACES.includes(go) ? `go=${go}&amp;` : 'start=new&amp;'}` +
  `utm_source=blog&amp;utm_medium=blog&amp;utm_campaign=${encodeURIComponent(campaign)}`;
</code></pre>
<p>So every post is measurable as a channel, and the markdown copy contains the same link. Since <code>/play</code> is disallowed in robots.txt, these links are for people, not for crawlers to follow.</p>
<h2>What I would do differently</h2>
<ul>
<li><strong>Test the head, not just the body.</strong> Our scenario document says a test verifies that JSON-LD parses and the fields exist. I would add a check that every hreflang target returns 200 and links back, because broken return links make hreflang get ignored.</li>
<li><strong>Do not trust a rich result to appear.</strong> Structured data is eligibility, not a promise.</li>
<li><strong>Keep the cache honest.</strong> A version counter is simpler than invalidation by key, but it throws away everything when one post changes. At our size that costs milliseconds. At ten thousand pages it would not.</li>
<li><strong>Measure AI referrals directly.</strong> UTM tags work only when the assistant keeps them. Server logs by user agent are the other half of the picture.</li>
</ul>
<h2>Checklist</h2>
<ol>
<li>Server-render the text. No client JS is needed to read a page.</li>
<li>One canonical URL per page. Redirect <code>/en/</code>-style duplicates and trailing slashes with 301.</li>
<li>hreflang only for languages that really exist, plus <code>x-default</code>. Put it in the head and in the sitemap.</li>
<li>Untranslated fallback pages: show something useful, canonical to the original, <code>noindex, follow</code>.</li>
<li>Real 404 status, <code>noindex</code>, no alternates.</li>
<li>Open Graph with image size, <code>og:locale</code> and its alternates; a 1200×630 cover.</li>
<li>JSON-LD with stable <code>@id</code>s: <code>BlogPosting</code>, <code>BreadcrumbList</code>, <code>FAQPage</code>, <code>HowTo</code>, and a <code>VideoGame</code> for the product.</li>
<li>Generate FAQ markup from the same list that renders the visible FAQ.</li>
<li>Put changing numbers behind placeholders computed from live data.</li>
<li>ETag from a content hash, <code>Last-Modified</code>, <code>Cache-Control</code> with <code>stale-while-revalidate</code>, brotli with gzip as the fallback.</li>
<li>Never redirect bots by language. Check the User-Agent before <code>Accept-Language</code>.</li>
<li>RSS and Atom per language, linked from the head.</li>
<li>Sitemaps with hreflang alternates; list them in robots.txt.</li>
<li>A markdown copy of each page, linked with <code>rel="alternate" type="text/markdown"</code>, and an <code>llms.txt</code> over it.</li>
<li>Decide your AI crawler policy on purpose, repeat the disallow rules in every named group, and write the reasoning in the file.</li>
<li>Push changes with IndexNow from your own sitemap, and record what was sent.</li>
<li>Deep-link from content into the product with UTM tags on every link.</li>
</ol>
<p>None of this needs a framework. It needs one module that treats every page as data and renders it several ways.</p>
<p>If you want to see what all of this serves, the game is free and runs in any browser. <a href="https://towneers.world/r/hashnode?utm_campaign=seo-node&amp;utm_content=article">towneers.world</a></p>
]]></content:encoded></item></channel></rss>