<?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 Doug Costa on Medium]]></title>
        <description><![CDATA[Stories by Doug Costa on Medium]]></description>
        <link>https://medium.com/@doug.cost?source=rss-9a65542b6634------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*RP9hLLIB020an4Im</url>
            <title>Stories by Doug Costa on Medium</title>
            <link>https://medium.com/@doug.cost?source=rss-9a65542b6634------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 14:07:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@doug.cost/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[Internationalizing an Astro Site with Multiple Languages]]></title>
            <link>https://medium.com/@doug.cost/internationalizing-an-astro-site-with-multiple-languages-f6f9dad94fd7?source=rss-9a65542b6634------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6f9dad94fd7</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[astros]]></category>
            <category><![CDATA[i18n]]></category>
            <category><![CDATA[web]]></category>
            <dc:creator><![CDATA[Doug Costa]]></dc:creator>
            <pubDate>Tue, 29 Sep 2026 00:00:43 GMT</pubDate>
            <atom:updated>2026-09-30T15:28:05.582Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EmQheGFpwpPrmdcia1IPdQ.jpeg" /></figure><h4>How to add support for multiple languages to an Astro site, organizing translations, routes, content and navigation.</h4><h3>Introduction</h3><p>Today, translating a website’s content is very easy. Browsers themselves provide tools that can do this automatically. However, even though this automated process has evolved considerably, it does not always respect the expressions and nuances of each language.</p><p>One way to avoid this kind of situation is to offer the content in multiple languages.</p><p>Another advantage of this approach is that each language version can have its own URL, making it easier for search engines to discover, index, and present the appropriate version of the content.</p><p>For this reason, I added support for four languages to my personal website: <em>Brazilian Portuguese</em> (my native language), <em>English</em>, <em>French</em>, and <em>Spanish</em>. In this article, I will show how I implemented this structure using Astro’s internationalization features.</p><p>Internationalization should cover both interface text and blog content. This means that each article can have translated versions, each with its own URL.</p><p>The idea was to keep a single application while allowing each language to have its own pages, translations, and articles.</p><h3>What We Want to Build</h3><p>Before getting started, it is worth defining how we want the URLs to work.</p><p>Portuguese will be the site’s default language and therefore will not have a URL prefix:</p><pre>https://dougcosta.com/<br>https://dougcosta.com/blog/</pre><p>For the other languages, we will use a prefix:</p><pre>https://dougcosta.com/<br>https://dougcosta.com/blog/</pre><p>The same principle will be used for articles.</p><p>For example, the same article can have the following URLs:</p><pre>/blog/construindo-site-astro-github-pages/<br>/en/blog/building-a-site-with-astro-github-pages/<br>/fr/blog/creer-un-site-avec-astro-et-github-pages/<br>/es/blog/crear-un-sitio-con-astro-y-github-pages/</pre><p>This gives us separate URLs for each language instead of trying to place all translations on the same page.</p><h3>Configuring Internationalization in Astro</h3><p>The first step is to tell Astro which languages will be supported.</p><p>This configuration goes in the file:</p><pre>astro.config.mjs</pre><p>The configuration looks like this:</p><pre>import { defineConfig } from &#39;astro/config&#39;;<br><br>export default defineConfig({<br> site: &#39;https://dougcosta.com&#39;,<br><br> i18n: {<br>  defaultLocale: &#39;pt-BR&#39;,<br>  locales: [&#39;pt-BR&#39;, &#39;en&#39;, &#39;fr&#39;, &#39;es&#39;],<br>  routing: {<br>   prefixDefaultLocale: false,<br>  },<br> },<br>});</pre><p>The defaultLocale property defines the site&#39;s default language.</p><p>In this case:</p><pre>pt-BR</pre><p>The locales array lists all available languages.</p><p>The configuration:</p><pre>prefixDefaultLocale: false</pre><p>is important for the behavior we want. It means that the default language will not have a URL prefix.</p><p>So:</p><pre>/</pre><p>represents Portuguese, while:</p><pre>/en/<br>/fr/<br>/es/</pre><p>represent the other languages.</p><h3>Creating Translation Files</h3><p>In addition to routing, we need to translate the text that is part of the site’s interface.</p><p>To do this, we will create a dedicated structure inside src:</p><pre>src/<br>└── i18n/<br>    ├── en.ts<br>    ├── es.ts<br>    ├── fr.ts<br>    ├── pt-BR.ts<br>    ├── index.ts<br>    └── utils.ts</pre><p>Each language file contains the corresponding translations.</p><p>For example, the pt-BR.ts file contains text such as:</p><pre>export default {<br> nav: {<br>  home: &#39;Início&#39;,<br>  blog: &#39;Blog&#39;,<br>  about: &#39;Sobre&#39;,<br> },<br><br> home: {<br>  readBlog: &#39;Ver blog&#39;,<br>  allPosts: &#39;Ver todos os textos&#39;,<br>  latestPosts: &#39;Últimos textos&#39;,<br> },<br>};</pre><p>The English file has the same structure, but with the text translated:</p><pre>export default {<br> nav: {<br>  home: &#39;Home&#39;,<br>  blog: &#39;Blog&#39;,<br>  about: &#39;About&#39;,<br> },<br><br> home: {<br>  readBlog: &#39;Read blog&#39;,<br>  allPosts: &#39;View all posts&#39;,<br>  latestPosts: &#39;Latest posts&#39;,<br> },<br>};</pre><p>The advantage of this approach is that components can use the same structure regardless of the current language.</p><p>It also keeps translations centralized instead of spreading them throughout the site. In other words, when you change a text in this file, every page and component that uses that translation will display the new value.</p><p>Adding a new language requires updating the Astro configuration and the parts of the project that enumerate the supported locales, as well as creating the corresponding translations and routes.</p><h3>Centralizing Languages</h3><p>After creating the individual files, we need to make the translations available in a centralized way.</p><p>To do this, we will create:</p><pre>src/i18n/index.ts</pre><p>The file imports all catalogs:</p><pre>import ptBR from &#39;./pt-BR&#39;;<br>import en from &#39;./en&#39;;<br>import fr from &#39;./fr&#39;;<br>import es from &#39;./es&#39;;<br><br>const translations = {<br> &#39;pt-BR&#39;: ptBR,<br> en,<br> fr,<br> es,<br>};<br><br>export type Locale = keyof typeof translations;<br>export type Translations = typeof ptBR;<br><br>const typedTranslations: Record&lt;Locale, Translations&gt; = {<br> &#39;pt-BR&#39;: ptBR,<br> en,<br> fr,<br> es,<br>};<br><br>export function getTranslations(locale: Locale): Translations {<br> return typedTranslations[locale];<br>}</pre><p>With this, a component can simply retrieve the translations for the current language:</p><pre>const t = getTranslations(locale);</pre><p>And use:</p><pre>{t.nav.blog}</pre><p>instead of writing it directly:</p><pre>Blog</pre><p>This keeps interface text separate from the component structure.</p><h3>Identifying the Current Language</h3><p>We also need to determine which language corresponds to the URL being accessed.</p><p>We will create some utilities in:</p><pre>src/i18n/utils.ts</pre><p>The first one identifies the language from the first segment of the URL:</p><pre>import type { Locale } from &#39;./index&#39;;<br><br>const supportedLocales: Locale[] = [&#39;pt-BR&#39;, &#39;en&#39;, &#39;fr&#39;, &#39;es&#39;];<br><br>export function getLocaleFromUrl(url: URL): Locale {<br> const [, firstSegment] = url.pathname.split(&#39;/&#39;);<br><br> if (firstSegment &amp;&amp; supportedLocales.includes(firstSegment as Locale)) {<br>  return firstSegment as Locale;<br> }<br><br> return &#39;pt-BR&#39;;<br>}</pre><p>Because Portuguese is the default language and has no URL prefix, when the first segment does not match a supported locale, we assume pt-BR.</p><p>So a URL such as:</p><pre>/en/blog/...</pre><p>returns:</p><pre>en</pre><p>While:</p><pre>/blog/...</pre><p>returns:</p><pre>pt-BR</pre><p>The second is a function for obtaining the corresponding prefix:</p><pre>export function getLocalePrefix(locale: Locale): string {<br> return locale === &#39;pt-BR&#39; ? &#39;&#39; : `/${locale}`;<br>}</pre><p>This allows us to generate URLs without scattering language rules throughout the project.</p><p>For example:</p><pre>getLocalePrefix(&#39;pt-BR&#39;);</pre><p>returns:</p><pre>&#39;&#39;</pre><p>While:</p><pre>getLocalePrefix(&#39;en&#39;);</pre><p>returns:</p><pre>/en</pre><h3>Internationalizing Blog Content</h3><p>The interface is not the only part that needs to be translated.</p><p>The articles themselves also need to indicate which language they represent and which translated content they belong to.</p><p>To do this, let’s open the file:</p><pre>src/content.config.ts</pre><p>And add two fields to the blog collection schema:</p><pre>lang: z.enum([&#39;pt-BR&#39;, &#39;en&#39;, &#39;fr&#39;, &#39;es&#39;]),<br>translationKey: z.string(),</pre><p>It will look like this:</p><pre>...<br><br>const blog = defineCollection({<br> loader: glob({ base: &#39;./src/content/blog&#39;, pattern: &#39;**/*.{md,mdx}&#39; }),<br> schema: ({ image }) =&gt;<br>  z.object({<br>   title: z.string(),<br>   description: z.string(),<br>   lang: z.enum([&#39;pt-BR&#39;, &#39;en&#39;, &#39;fr&#39;, &#39;es&#39;]), // NOVO CAMPO<br>   translationKey: z.string(), // NOVO CAMPO<br>   pubDate: z.coerce.date(),<br>   ...<br>  }),<br>});<br><br>export const collections = { blog };</pre><p>The lang field identifies the language of the article.</p><p>The translationKey works as a shared identifier across all versions of the same content.</p><p>For example, the Astro article uses:</p><pre>lang: pt-BR<br>translationKey: astro-github-pages</pre><p>The English version uses:</p><pre>lang: en<br>translationKey: astro-github-pages</pre><p>The French version:</p><pre>lang: fr<br>translationKey: astro-github-pages</pre><p>And the Spanish version:</p><pre>lang: es<br>translationKey: astro-github-pages</pre><p>This way, we can identify these files as different language versions of the same content.</p><h3>Creating the Translated Files</h3><p>Each translated version has its own content file.</p><p>The original version is located at:</p><pre>src/content/blog/construindo-site-astro-github-pages.md</pre><p>The English version:</p><pre>src/content/blog/building-a-site-with-astro-github-pages.md</pre><p>The French version:</p><pre>src/content/blog/creer-un-site-avec-astro-et-github-pages.md</pre><p>And the Spanish version:</p><pre>src/content/blog/crear-un-sitio-con-astro-y-github-pages.md</pre><p>Although they are different files, they all use the same translationKey.</p><p>This allows Astro to treat each file as an independent post while the application can associate them as translations.</p><h3>Creating Post Utilities</h3><p>With the schema ready, let’s create some functions for working with articles.</p><p>An important implementation rule is that <strong>every post listing must be filtered by the locale of the page being rendered</strong>. It is not enough to create different routes for each language. Since all articles live in the same collection, queries must explicitly select the correct language.</p><p>The first goal is to retrieve only the posts for a given language.</p><p>To do this, we will create the getPostsByLocale function inside the utilities that support the articles in src/utils/posts.ts:</p><pre>export function getPostsByLocale(<br> posts: Post[],<br> locale: Post[&#39;data&#39;][&#39;lang&#39;],<br>) {<br> return posts.filter((post) =&gt; post.data.lang === locale);<br>}</pre><p>This is important because the same project can contain versions of the content in different languages.</p><p>For example, when we are on the English home page, we do not want to show articles in Portuguese.</p><p>We can do:</p><pre>const posts = getPostsByLocale(<br> await getPublishedPosts(),<br> &#39;en&#39;,<br>);</pre><p>And retrieve only the English posts.</p><p>The same rule must be applied to blog listing pages, paginated pages, and any other screen that displays a collection of articles. This way, language separation is not limited to routes and is also respected by the data displayed on each page. We will see later how this mechanism works.</p><p>Still in src/utils/posts.ts, we will create a function to find the translation corresponding to an article:</p><pre>export function getTranslatedPost(<br> posts: Post[],<br> post: Post,<br> locale: Post[&#39;data&#39;][&#39;lang&#39;],<br>) {<br> return posts.find(<br>  (candidate) =&gt;<br>   candidate.data.translationKey === post.data.translationKey &amp;&amp;<br>   candidate.data.lang === locale,<br> );<br>}</pre><p>The logic looks for an article with the same translationKey, checks whether it has the requested language, and returns the translation found.</p><p>This function will be used by the language selector.</p><h3>Creating Routes for Each Language</h3><p>The next step is to create the pages corresponding to each language.</p><p>The project structure looks like this:</p><pre>src/pages/<br>├── index.astro<br>├── blog/<br>│   ├── [...page].astro<br>│   └── [...slug].astro<br>├── en/<br>│   ├── index.astro<br>│   └── blog/<br>│       ├── [...page].astro<br>│       └── [...slug].astro<br>├── fr/<br>│   ├── index.astro<br>│   └── blog/<br>│       ├── [...page].astro<br>│       └── [...slug].astro<br>└── es/<br>    ├── index.astro<br>    └── blog/<br>        ├── [...page].astro<br>        └── [...slug].astro</pre><p>We will create a directory for each language (en, fr, and es) inside src/pages/ and create the pages corresponding to the routes we want to make available in each language. The structure makes it explicit that each language has its own pages.</p><p>The page:</p><pre>src/pages/index.astro</pre><p>represents Portuguese.</p><p>While:</p><pre>src/pages/en/index.astro</pre><p>represents English.</p><p>The same principle is used for French and Spanish.</p><h3>Filtering the Blog by Language</h3><p>On pages that display article lists, such as the home page and blog listing, we use the locale corresponding to each route.</p><p>On the Portuguese home page:</p><pre>const posts = getPostsByLocale(<br> await getPublishedPosts(),<br> &#39;pt-BR&#39;,<br>);</pre><p>On the English home page:</p><pre>const posts = getPostsByLocale(<br> await getPublishedPosts(),<br> &#39;en&#39;,<br>);</pre><p>The same applies to French and Spanish.</p><p>This ensures that each language listing contains only the articles corresponding to that language.</p><p>This filtering must happen <strong>before pagination</strong>. First, we select the posts for the current locale and only then pass that collection to the logic that creates paginated pages. This way, the number of posts per page and the total number of pages are also calculated exclusively based on the current language.</p><p>The rule applies to all listing routes: home, blog, and paginated pages. Each one must retrieve the published posts and then apply getPostsByLocale() with the locale corresponding to its own route.</p><p>It should look something like this:</p><pre>---<br>import Layout from &#39;../layouts/Layout.astro&#39;;<br>import PostCard from &#39;../components/PostCard.astro&#39;;<br>import { BLOG, SITE } from &#39;../consts&#39;;<br>import { getTranslations } from &#39;../i18n&#39;;<br>import { getPostsByLocale, getPublishedPosts } from &#39;../utils/posts&#39;;<br><br>const t = getTranslations(&#39;pt-BR&#39;);<br><br>// Fetch only the articles corresponding to the current language.<br>const posts = getPostsByLocale(<br> await getPublishedPosts(),<br> &#39;pt-BR&#39;,<br>).slice(0, BLOG.postsOnHome);<br>---<br><br>&lt;Layout description={SITE.description}&gt;<br> &lt;section class=&quot;hero wrap&quot;&gt;<br>  &lt;p class=&quot;eyebrow&quot;&gt;{t.home.eyebrow}&lt;/p&gt;<br>  &lt;h1&gt;Doug Costa&lt;/h1&gt;<br>  &lt;p class=&quot;lede&quot;&gt;{SITE.tagline}&lt;/p&gt;<br>  &lt;p class=&quot;intro&quot;&gt;{t.home.intro}&lt;/p&gt;<br>  &lt;a class=&quot;cta&quot; href=&quot;/blog/&quot;&gt;{t.home.readBlog}&lt;/a&gt;<br> &lt;/section&gt;<br> &lt;section class=&quot;latest wrap&quot;&gt;<br>  &lt;div class=&quot;latest__head&quot;&gt;&lt;h2&gt;{t.home.latestPosts}&lt;/h2&gt;&lt;a href=&quot;/blog/&quot;&gt;{t.home.allPosts}&lt;/a&gt;&lt;/div&gt;<br>&lt;!-- List the articles for the current language. --&gt;<br>  {posts.length ? posts.map((post) =&gt; &lt;PostCard post={post} /&gt;) : &lt;p class=&quot;empty&quot;&gt;{t.home.empty}&lt;/p&gt;}<br> &lt;/section&gt;<br>&lt;/Layout&gt;<br>...</pre><p>In addition to improving the browsing experience, this separation prevents content in different languages from being mixed on the same page and keeps pagination consistent with the selected language.</p><h3>Creating the Language Selector</h3><p>With the articles linked through translationKey, we can create the language selector in the header.</p><p>To do this, in src/components/Header.astro, we import the translation utilities we created:</p><pre>---<br>import { getTranslations, type Locale } from &#39;../i18n&#39;;<br>import { getLocaleFromUrl, getLocalePrefix } from &#39;../i18n/utils&#39;;<br>import type { CollectionEntry } from &#39;astro:content&#39;;<br>import { getPublishedPosts, getTranslatedPost } from &#39;../utils/posts&#39;;<br>...</pre><p>We identify the current language:</p><pre>const locale = getLocaleFromUrl(Astro.url);</pre><p>We load the interface translations:</p><pre>const t = getTranslations(locale);</pre><p>We define the available languages:</p><pre>const languages: { locale: Locale; label: string }[] = [<br> { locale: &#39;pt-BR&#39;, label: &#39;PT&#39; },<br> { locale: &#39;en&#39;, label: &#39;EN&#39; },<br> { locale: &#39;fr&#39;, label: &#39;FR&#39; },<br> { locale: &#39;es&#39;, label: &#39;ES&#39; },<br>];</pre><p>We calculate the prefix corresponding to the current language:</p><pre>const basePath = locale === &#39;pt-BR&#39; ? &#39;&#39; : `/${locale}`;</pre><p>We map the site navigation menu items (which allow navigation between the home page, article listing, and about page):</p><pre>const NAV = [<br> { href: `${basePath}/`, label: t.nav.home },<br> { href: `${basePath}/blog/`, label: t.nav.blog },<br> { href: `${basePath}/about/`, label: t.nav.about },<br>];</pre><p>We create a function that generates the path corresponding to the selected language:</p><pre>const languagePath = (targetLocale: Locale) =&gt; {<br> if (!currentPost) {<br>  const prefix = getLocalePrefix(targetLocale);<br>  const currentPath = Astro.url.pathname;<br><br>  const pathWithoutLocale =<br>   locale === &#39;pt-BR&#39;<br>    ? currentPath<br>    : currentPath.replace(new RegExp(`^/${locale}`), &#39;&#39;) || &#39;/&#39;;<br><br>  return `${prefix}${pathWithoutLocale === &#39;/&#39; ? &#39;/&#39; : pathWithoutLocale}`;<br> }<br><br> const translatedPost = getTranslatedPost(<br>  posts,<br>  currentPost,<br>  targetLocale,<br> );<br><br> if (!translatedPost) {<br>  return `${getLocalePrefix(targetLocale)}/blog/`;<br> }<br><br> return `${getLocalePrefix(targetLocale)}/blog/${translatedPost.id}/`;<br>};</pre><p>In this function, when we are inside an article, the selector looks for the corresponding translation:</p><pre>const translatedPost = getTranslatedPost(<br> posts,<br> currentPost,<br> targetLocale,<br>);</pre><p>If the translation exists, we generate the URL for the translated article:</p><pre>return `${getLocalePrefix(targetLocale)}/blog/${translatedPost.id}/`;</pre><p>basePath represents the current language prefix and is used for the fixed menu links. getLocalePrefix() is used when we need to generate a URL for a target language.</p><p>So, if we are reading the Portuguese version and select English, navigation takes us directly to the English version of that same article.</p><p>If a translation does not exist yet, the selector can direct the reader to that language’s blog listing.</p><p>In the header, we use the basePath, which contains the current base path, as the page reference:</p><pre>&lt;a class=&quot;brand&quot; href={`${basePath}/`}&gt;{SITE.title}&lt;/a&gt;</pre><p>And we add a language selector to the header:</p><pre>&lt;div class=&quot;language-switcher&quot; aria-label=&quot;Language&quot;&gt;<br> {languages.map(({ locale: targetLocale, label }) =&gt; (<br>  &lt;a<br>   href={languagePath(targetLocale)}<br>   aria-current={locale === targetLocale ? &#39;page&#39; : undefined}<br>  &gt;<br>   {label}<br>  &lt;/a&gt;<br> ))}<br>&lt;/div&gt;</pre><p>The language selector also needs to work on pages that are not articles.</p><p>In this case, there is no translationKey to use.</p><p>So the application preserves the current path and only changes the language prefix.</p><p>For example:</p><pre>/blog/</pre><p>can be converted into:</p><pre>/en/blog/</pre><p>or:</p><pre>/fr/blog/</pre><p>This keeps navigation consistent throughout the site.</p><h3>Updating the Layout</h3><p>The main layout also needs to know the current language.</p><p>In Layout.astro, we use:</p><pre>const locale = getLocaleFromUrl(Astro.url);<br>const t = getTranslations(locale);</pre><p>The language is also applied to the &lt;html&gt; element:</p><pre>&lt;html lang={locale}&gt;</pre><p>Thus, a Portuguese page will have:</p><pre>&lt;html lang=&quot;pt-BR&quot;&gt;</pre><p>and a page in English:</p><pre>&lt;html lang=&quot;en&quot;&gt;</pre><p>In addition to being semantically correct, this provides the browser and other tools with explicit information about the language of the content.</p><h3>Updating Article Links</h3><p>There is one more important detail when we start working with multiple languages.</p><p>Blog cards are shared components across all pages.</p><p>Therefore, the article link cannot be hardcoded as:</p><pre>&lt;a href={`/blog/${post.id}/`}&gt;</pre><p>On an English page, for example, we need to generate:</p><pre>/en/blog/...</pre><p>To solve this, inside the src/components/PostCard.astro and src/layouts/BlogPost.astro components, we obtain the current language:</p><pre>const locale = getLocaleFromUrl(Astro.url);<br>const localePrefix = getLocalePrefix(locale);</pre><p>For the URL prefix, we use the value stored in localePrefix:</p><pre>&lt;a href={`${localePrefix}/blog/${post.id}/`}&gt;<br> {title}<br>&lt;/a&gt;</pre><p>Because the Portuguese prefix is an empty string, the behavior remains:</p><pre>/blog/...</pre><p>While the other languages receive their respective prefixes:</p><pre>/en/blog/...<br>/fr/blog/...<br>/es/blog/...</pre><p>This way, we can reuse the same component for all versions of the site.</p><h3>Keeping Tag Links in the Correct Language</h3><p>Tags are also part of blog navigation and need to respect the current locale.</p><p>Because tags are reused by articles in all languages, we should not always generate the link from the default route:</p><pre>&lt;a href={`/tags/${tagSlug(tag)}/`}&gt;<br> #{tag}<br>&lt;/a&gt;</pre><p>On an English page, for example, this code would lead to:</p><pre>/tags/astro/</pre><p>when the correct URL is:</p><pre>/en/tags/astro/</pre><p>In src/components/PostCard.astro and src/layouts/BlogPost.astro, we will change the tag links to use the prefix stored in localePrefix. The link becomes:</p><pre>&lt;a href={`${localePrefix}/tags/${tagSlug(tag)}/`}&gt;<br> #{tag}<br>&lt;/a&gt;</pre><p>This way, the components responsible for rendering tags can generate the links correctly in all languages:</p><pre>/tags/astro/<br>/en/tags/astro/<br>/fr/tags/astro/<br>/es/tags/astro/</pre><p>The same concern should be applied to other links generated inside shared components. Whenever a URL depends on the current language, the component should obtain the locale from the current URL and use the corresponding prefix instead of assuming that the default route is always /.</p><h3>Final Result</h3><p>After these changes, we have a structure in which the language is present in all the important parts of the site.</p><p>The home page has a version for each language:</p><pre>/<br>/en/<br>/fr/<br>/es/</pre><p>The blog does too:</p><pre>/blog/<br>/en/blog/<br>/fr/blog/<br>/es/blog/</pre><p>And each article can have its own translated version:</p><pre>/blog/artigo-em-portugues/<br>/en/blog/article-in-english/<br>/fr/blog/article-en-francais/<br>/es/blog/articulo-en-espanol/</pre><p>The relationship between these versions is established through translationKey.</p><p>This allows users to navigate between translations without having to manually search for the corresponding content.</p><h3>Conclusion</h3><p>Internationalizing the site did not mean simply translating the interface text.</p><p>It was necessary to think about the structure as a whole: URLs, content, listings, navigation, and the relationship between translations. Each page must display only the content for its locale, and links generated by shared components must also preserve this context.</p><p>Astro’s i18n configuration established the language-based routing rules, while the project’s page structure and utilities handled the generation and navigation between these routes.</p><p>For blog content, the combination of lang and translationKey created a simple way to identify the language of each article and relate the different versions of the same content.</p><p>In the end, we have a single Astro application capable of publishing the same site in four languages, with dedicated URLs, language-specific listings, localized navigation, and the ability for readers to switch between translations.</p><p>The structure also leaves the project ready to grow. When new articles are published, you only need to create their versions in the desired languages and use the same translationKey to link them.</p><p>If you do not have a website yet and want to build one with Astro, you may also want to read:</p><p>If you use Astro and, like me, want external links on your site to open in a new tab, see how I implemented it in:</p><p>If you want to set up Google Analytics on a website, also see the article:</p><h3>References</h3><p>The implementation presented in this article was based primarily on the official Astro documentation:</p><p><em>Originally published at </em><a href="https://dougcosta.com/en/blog/internationalizing-astro-site-multiple-languages/"><em>https://dougcosta.com</em></a><em> on September 29, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6f9dad94fd7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting Up Google Analytics on a Website]]></title>
            <link>https://medium.com/@doug.cost/setting-up-google-analytics-on-a-website-0a78ec8baedb?source=rss-9a65542b6634------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a78ec8baedb</guid>
            <category><![CDATA[website]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[astros]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[google-analytics]]></category>
            <dc:creator><![CDATA[Doug Costa]]></dc:creator>
            <pubDate>Mon, 21 Sep 2026 00:00:31 GMT</pubDate>
            <atom:updated>2026-09-28T17:54:04.181Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*chbxLN7QfrBNaT87jFfUBQ.jpeg" /></figure><h4>A practical guide to setting up Google Analytics 4 and tracking website traffic.</h4><h3>Introduction</h3><p>The main goal when launching a website or application is to attract visitors and build an engaged audience. Data helps us understand whether that goal is being achieved, so we need a way to collect it.</p><p>Metrics such as the number of visitors, which pages or screens are viewed most often, where visitors come from, and how they navigate through the content help us understand audience interest and contribute to the evolution of the product.</p><p>To track this information, we can use <strong>Google Analytics 4 (GA4)</strong>.</p><p>In this article, we will set up Google Analytics on a website, from creating the account to validating data collection.</p><p>The example in this article uses a website built with Astro and published on GitHub Pages. However, the Google Analytics setup described here can be used with different technologies and platforms. What mainly changes is how the tag is added to the site’s code.</p><h3>Creating and Configuring a Google Analytics Account</h3><h3>Creating the account</h3><p>The first step is to access Google Analytics: <a href="https://analytics.google.com/">Google Analytics</a>.</p><p>Sign in with the Google account that will be used to manage Analytics. If a Google Analytics account does not exist yet, we will need to create one.</p><h3>Creating a property</h3><p>The next step is to create a property. A property represents the set of data we want to analyze in Google Analytics. It is where the data collected by Google Analytics is organized. In this example, this is where we will access the data from our website.</p><p>We can name the property after the website. For example:</p><pre>My New Website</pre><h3>Categorizing the property</h3><p>During this step, Google Analytics asks for some information that may seem more relevant to businesses, such as the industry and company size.</p><p>This step can be confusing when setting up Analytics for a personal website.</p><p>Even if we do not have a company, these questions are still part of the Google Analytics setup process.</p><p>In my case, since this is a personal website focused on technology, I chose the industry category closest to <strong>Technology/Software</strong>.</p><p>For company size, I selected <strong>Small</strong>, since it was the option closest to the reality of a personal website.</p><p>We do not need a formal company, CNPJ, or corporate structure to use Google Analytics on a personal website.</p><h3>Setting the time zone and currency</h3><p>During property setup, we also need to define the time zone and currency.</p><p>Choose the time zone that corresponds to the region we want to use as the reference for our reports.</p><p>For example:</p><pre>Time zone: (GMT-03:00) São Paulo<br>Currency: BRL — Brazilian Real</pre><p>The time zone is important because it affects how data is grouped by day in reports.</p><h3>Creating a Data Stream</h3><p>After creating the property, we need to tell Google Analytics where the data will come from.</p><p>For a website, we should create a <strong>Web</strong> data stream.</p><p>We need to enter the URL of the website we want to monitor. In this article’s example:</p><pre>https://mynewwebsite.com</pre><p>We can also define a name for the stream:</p><pre>New Website</pre><p>During this setup, keep <strong>Enhanced measurement</strong> enabled.</p><p>It allows Google Analytics to automatically collect certain events and information about user navigation without requiring us to implement each event manually.</p><p>After creating the stream, Google Analytics will display information about it, including the <strong>Measurement ID</strong>.</p><p>The ID looks something like this:</p><pre>G-XXXXXXXXXX</pre><p>This identifier will be used by the tag installed on the website.</p><h3>Installing the Google tag</h3><p>After creating the Web data stream, Google Analytics provides an option to install the Google tag on the website. Do not close this page or tab, because we will return to it later to validate the installation.</p><p>The tag needs to be added to the code of the pages we want to monitor.</p><p>Google Analytics provides code similar to this:</p><pre>&lt;!-- Google tag (gtag.js) --&gt;<br>&lt;script async src=&quot;https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX&quot;&gt;&lt;/script&gt;<br>&lt;script&gt;<br> window.dataLayer = window.dataLayer || [];<br> function gtag(){dataLayer.push(arguments);}<br> gtag(&#39;js&#39;, new Date());<br><br> gtag(&#39;config&#39;, &#39;G-XXXXXXXXXX&#39;);<br>&lt;/script&gt;</pre><p>Replace G-XXXXXXXXXX with the Measurement ID generated for your Web data stream. It is best to copy this code directly from Google Analytics rather than from this article. That way, we do not need to worry about replacing the ID manually.</p><p>How we add this code depends on the technology used by the website.</p><p>If the website uses plain HTML, for example, the tag can be added to the &lt;head&gt; of <strong>every</strong> page. Pages that do not include the tag will not send data to Google Analytics.</p><p>If the website uses a framework or site generator, there is usually a shared layout, template, or component where we can add the code once. That is what I did in my case. I am using Astro, so I added the tag to the layout shared by the site’s pages, ensuring that it is present everywhere. This also means that new pages will include the code automatically.</p><p>It is important to make sure this code runs only in production. Otherwise, visits generated during development or in staging environments may also be counted by Google Analytics, affecting the metrics.</p><p>In my case, I added a condition that checks whether the current environment is production (<strong>import.meta.env.PROD</strong>) before rendering the GA code:</p><pre>&lt;!-- Google tag (gtag.js) --&gt;<br>{import.meta.env.PROD &amp;&amp; (   <br> &lt;script async src=&quot;https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX&quot;&gt;&lt;/script&gt;<br> &lt;script&gt;<br>  window.dataLayer = window.dataLayer || [];<br>  function gtag(){dataLayer.push(arguments);}<br>  gtag(&#39;js&#39;, new Date());<br><br>  gtag(&#39;config&#39;, &#39;G-XXXXXXXXXX&#39;);<br> &lt;/script&gt;<br>)}</pre><h3>Testing the installation</h3><p>After publishing the website with the tag, we can use the verification tools provided by Google Analytics.</p><p>During the stream setup, there is a <strong>Test installation</strong> button.</p><p>Use this option after the new version of the website has been published.</p><p>In this article’s example, Google returned:</p><blockquote><em>Google tag detected on your website.</em></blockquote><p>This confirms that Google was able to find the tag on the page.</p><p>The <strong>Test installation</strong> button then changed to <strong>Confirm</strong>. When we click it, Google displays information such as:</p><ul><li>stream name;</li><li>stream URL;</li><li>Measurement ID.</li></ul><p>We may also see a message indicating that data collection is not active yet. Something like:</p><blockquote><em>Data collection isn’t active on your website. If you installed the tags more than 48 hours ago, verify that they are configured correctly.</em></blockquote><p>This message does not necessarily mean that the installation is incorrect. Data needs to reach Google Analytics before collection can be confirmed. For an immediate check, we can use the <strong>Realtime</strong> report.</p><h3>Verifying data collection</h3><p>For a more complete verification, we can use the <strong>Realtime</strong> report in Google Analytics.</p><p>After publishing the website:</p><ol><li>Open Google Analytics.</li><li>Go to <strong>Reports → Realtime</strong>.</li><li>Open the website in another browser tab or window.</li><li>Browse through a few pages.</li><li>Wait a few moments.</li><li>Check whether the activity appears in the report.</li></ol><p>In this article’s example, the activity appeared correctly in the report, confirming that data collection was working.</p><p>The Realtime report is especially useful during the initial setup because it allows us to verify recent activity without waiting for historical reports to be consolidated.</p><h3>Changing the domain in the future</h3><p>It is common for a website to start with an address provided by a hosting platform and later move to a custom domain.</p><p>For example, the website used in this article might initially be available at:</p><pre>https://mynewwebsite.com</pre><p>and later move to:</p><pre>https://mywebsite.com</pre><p>Changing the domain does not necessarily mean that we need to create a new Google Analytics property. We can continue using the existing property and preserve the data history already collected.</p><p>Once the new domain is configured, we can update the URL of the existing Web data stream and continue using the same Measurement ID.</p><p>The code installed on the website can also continue using the same ID ( G-XXXXXXXXXX).</p><p>This allows us to keep using the same property and Web data stream while preserving the historical data already collected.</p><h3>Conclusion</h3><p>Setting up Google Analytics on a website is a straightforward process.</p><p>First, we create the account and property, configure the Web data stream, and obtain the Measurement ID. Then we add the tag to the website, making sure it runs only in production, and publish the site so the code becomes available to visitors.</p><p>Finally, we use Google’s verification tools and the Realtime report to confirm that data is being collected.</p><p>From that point on, we start to get a clearer view of how the website is being used. As new content is published and traffic grows, this data can help us understand which pages are receiving the most visits and where visitors are coming from.</p><h3>Useful links</h3><p>If you do not have a website yet and want to build one with Astro, you may also want to read:</p><ul><li><a href="https://dougcosta.com/en/blog/building-a-site-with-astro-github-pages/">Building a Website with Astro and Publishing It on GitHub Pages with GitHub Actions</a></li></ul><p>If you use Astro and, like me, want external links on your site to open in a new tab, see how I implemented it in:</p><ul><li><a href="https://dougcosta.com/en/blog/astro-external-links-new-tab/">Opening External Post Links in a New Tab in Astro</a></li></ul><h3>References</h3><p>The documentation used as references for this article is:</p><p><em>Originally published at </em><a href="https://dougcosta.com/en/blog/setting-up-google-analytics-on-a-website/"><em>https://dougcosta.com</em></a><em> on September 21, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a78ec8baedb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Opening External Post Links in a New Tab in Astro]]></title>
            <link>https://medium.com/@doug.cost/opening-external-post-links-in-a-new-tab-in-astro-c1ae3d7ee1f4?source=rss-9a65542b6634------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1ae3d7ee1f4</guid>
            <category><![CDATA[astros]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[sätteri]]></category>
            <category><![CDATA[markdown]]></category>
            <dc:creator><![CDATA[Doug Costa]]></dc:creator>
            <pubDate>Thu, 17 Sep 2026 00:00:07 GMT</pubDate>
            <atom:updated>2026-09-22T16:34:01.703Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BQTIQfhssqpMDcHMH2aAQQ.jpeg" /></figure><h4>How to create and configure a Sätteri plugin to automatically open external links from Markdown posts in a new tab.</h4><h3>Introduction</h3><p>When building a website or writing articles, it is common to use external links for additional information, references, code repositories, or other content.</p><p>When a reader follows one of these links, we usually want the main content to remain open. That is why it is common to open these links in a new browser tab or window.</p><p>I was surprised to discover that Astro does not open these links in a new tab by default. The links continue to open in the same tab, whether we use Markdown or the HTML anchor tag (&lt;a href=&quot;...&quot;&gt;) directly.</p><p>The problem is that Markdown does not have its own syntax for defining HTML attributes such as target=&quot;_blank&quot;. The traditional syntax is still something like:</p><pre>[Astro Doc](https://docs.astro.build/)</pre><p>To handle this automatically, we can use a plugin that modifies the links generated by Markdown before they are turned into HTML.</p><p>In this article, we will create this plugin using <strong>Sätteri</strong>, the Markdown processor we are using in the project for this type of extension.</p><h3>What We Want to Do</h3><p>The idea is simple. Whenever a link’s href starts with http:// or https://, we want the HTML generated by Astro to look like this:</p><pre>&lt;a href=&quot;https://docs.astro.build/&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;<br>  Astro Doc<br>&lt;/a&gt;</pre><p>We do not want to add attributes manually to every link. The plugin will handle this change automatically.</p><p>Internal links to the site itself, on the other hand, should not be changed.</p><h3>Installing Sätteri</h3><p>Astro supports the Sätteri processor through the @astrojs/markdown-satteri package. To create our plugin, we will also use the satteri package.</p><p>Run:</p><pre>npm install @astrojs/markdown-satteri satteri</pre><p>@astrojs/markdown-satteri lets us use Sätteri as the Markdown processor in Astro, while the satteri package provides the APIs used to create custom plugins.</p><p>Astro’s documentation also presents Sätteri as an option for creating plugins that modify HTML elements generated from Markdown.</p><h3>Creating the Plugin</h3><p>Now let’s create a file for our plugin.</p><p>In my project, I organized plugins under src/plugins. So, create:</p><pre>src/plugins/external-links.ts</pre><p>The file contents will be:</p><pre>import { defineHastPlugin } from &#39;satteri&#39;;<br><br>export const externalLinks = defineHastPlugin({<br> name: &#39;external-links&#39;,<br> element: {<br>  filter: [&#39;a&#39;],<br>  visit(node, ctx) {<br>   const href = node.properties?.href;<br><br>   if (typeof href === &#39;string&#39; &amp;&amp; /^https?:\/\//.test(href)) {<br>    ctx.setProperty(node, &#39;target&#39;, &#39;_blank&#39;);<br>    ctx.setProperty(node, &#39;rel&#39;, [&#39;noopener&#39;, &#39;noreferrer&#39;]);<br>   }<br>  },<br> },<br>});</pre><p>Let’s take a look at what is happening.</p><h3>Identifying Links</h3><p>The plugin uses defineHastPlugin to define a HAST plugin.</p><p>HAST is a tree representation of HTML. This means that, at this stage of processing, we can work with the HTML elements that will be generated from Markdown.</p><p>In our case, we are only interested in &lt;a&gt; elements:</p><pre>element: {<br> filter: [&#39;a&#39;],</pre><p>visit will be executed for these elements.</p><h3>Checking Whether the Link Is External</h3><p>Inside visit, we first retrieve the link address:</p><pre>const href = node.properties?.href;</pre><p>We then check whether it starts with http:// or <a href="https://:">https://:</a></p><pre>const href = node.properties?.href;</pre><p>This check is important because we only want to modify external links.</p><p>For example:</p><pre>https://docs.astro.build/<br>https://github.com/<br>http://example.com/</pre><p>Internal links such as:</p><pre>/blog/</pre><p>do not pass this condition and retain the site’s normal behavior.</p><h3>Adding the target</h3><p>When we find an external link, we add:</p><pre>ctx.setProperty(node, &#39;target&#39;, &#39;_blank&#39;);</pre><p>This makes the resulting HTML use:</p><pre>target=&quot;_blank&quot;</pre><p>This causes the browser to open the address in a new tab.</p><h3>Adding rel</h3><p>We also add:</p><pre>ctx.setProperty(node, &#39;rel&#39;, [&#39;noopener&#39;, &#39;noreferrer&#39;]);</pre><p>The result will be equivalent to:</p><pre>rel=&quot;noopener noreferrer&quot;</pre><p>In addition to being a recommended setting for links that use target=&quot;_blank&quot;, noopener prevents the opened page from accessing the window that initiated the navigation. noreferrer also prevents the referrer information ( Referer) from being sent to the destination page.</p><p>This makes opening in a separate tab the default behavior for links with http:// or https:// URLs found in Markdown content.</p><p>If you want to add other attributes by default, simply follow the same approach and include them here.</p><h3>Configuring Astro</h3><p>Now we need to tell Astro that we want to use our plugin while processing Markdown files.</p><p>Open the following file, which is located at the project root:</p><pre>astro.config.mjs</pre><p>First, import satteri and the plugin we just created:</p><pre>import { satteri } from &#39;@astrojs/markdown-satteri&#39;;<br>import { externalLinks } from &#39;./src/plugins/external-links&#39;;</pre><p>Then configure the processor inside markdown:</p><pre>markdown: {<br> processor: satteri({<br>  hastPlugins: [externalLinks],<br> }),<br>},</pre><p>In my project, the configuration looks like this:</p><pre>// @ts-check<br><br>import mdx from &#39;@astrojs/mdx&#39;;<br>import sitemap from &#39;@astrojs/sitemap&#39;;<br>import { defineConfig } from &#39;astro/config&#39;;<br>import { satteri } from &#39;@astrojs/markdown-satteri&#39;;<br>import { externalLinks } from &#39;./src/plugins/external-links&#39;;<br><br>export default defineConfig({<br> site: &#39;https://dougcosta.com&#39;,<br> integrations: [mdx(), sitemap()],<br> markdown: {<br>  processor: satteri({<br>   hastPlugins: [externalLinks],<br>  }),<br> },<br>});</pre><h3>Testing the Plugin</h3><p>Now we can test the behavior.</p><p>Add an external link to a Markdown post:</p><pre>[Astro Doc](https://docs.astro.build/)</pre><p>Then run the project locally:</p><pre>npm run dev</pre><p>Open the post in your browser and click the link. It should open in a new tab or window, depending on the browser and its settings.</p><p>We can also inspect the HTML generated by the browser. Right-click the page and choose the option corresponding to Inspect (the wording may vary depending on the browser).</p><p>The link should contain:</p><pre>target=&quot;_blank&quot;</pre><p>and:</p><pre>rel=&quot;noopener noreferrer&quot;</pre><h3>An Important Detail: Be Careful with draft: true</h3><p>During this process, I came across a detail that can easily lead to the wrong conclusion while testing.</p><p>In my project, posts marked as:</p><pre>draft: true</pre><p>are not included in the production build.</p><p>This means that if you test the plugin by running the command below while the post is marked as draft: true, the post&#39;s HTML file will not be generated:</p><pre>npm run build</pre><p>In that case, looking for target=&quot;_blank&quot; in the dist directory will not allow you to verify that the plugin is working, because the post itself will not be present in the build. Therefore, there will be no HTML file for that post to inspect.</p><p>Therefore, <strong>before testing the plugin in a production build, make sure the post you are using for the test is not marked as </strong><strong>draft: true</strong>.</p><p>For a post that should be included in the build, the frontmatter should look like this, for example:</p><pre>---<br>title: &quot;My post&quot;<br>description: &quot;Post description.&quot;<br>pubDate: 2026-09-16<br>draft: false<br>---</pre><p>This detail may seem minor, but it was precisely what initially made validating the plugin in my project more difficult.</p><h3>Why Use a Plugin for This?</h3><p>An alternative would be to control target=&quot;_blank&quot; individually in each component or manually modify the links after the Markdown had been rendered.</p><p>However, that would create an additional responsibility for every new post.</p><p>With the plugin, the rule is centralized:</p><pre>Post Markdown<br>     ↓<br>Sätteri<br>     ↓<br>Plugin external-links<br>     ↓<br>Identifica links externos<br>     ↓<br>Adiciona target=&quot;_blank&quot;<br>     ↓<br>HTML final</pre><p>From that point on, any new external link added to a post goes through the same processing automatically.</p><p>This also means we do not need to remember to add specific attributes every time we create a link to documentation or another website.</p><h3>Conclusion</h3><p>In my view, it is surprising that Markdown does not have its own syntax for controlling HTML attributes such as target. This type of behavior is quite common when building a website, so it would be useful to have a more direct way to configure it. The solution I found was to use a plugin, as described in this article, but it would also be possible to control this behavior individually in each component or use another approach.</p><p>The solution itself turned out to be relatively simpland: use Sätteri to intercept the &lt;a&gt; elements generated by Markdown and add the required attributes to the links. Even so, it took some additional research to arrive at this approach.</p><p>The important takeaway was realizing that this type of behavior can be centralized in a plugin. Instead of adapting each post individually, we create a rule that applies to all Markdown content on the site.</p><p>Another important lesson concerns testing. When working with posts that have draft: true, we need to remember that they are not included in the production build. Otherwise, we may interpret the absence of generated content as a problem with the plugin, when the post simply was not included in the build.</p><h3>Useful Links</h3><p>If you do not have a website yet and want to build one with Astro, also check out this article:</p><ul><li><a href="https://dougcosta.com/en/blog/building-a-site-with-astro-github-pages/">Building a Website with Astro and Publishing It to GitHub Pages with GitHub Actions</a></li></ul><p>In it, I walk through the process of creating an Astro project from the blog template and configuring automatic deployment to GitHub Pages using GitHub Actions.</p><h3>References</h3><p>The documentation used as references for this article is:</p><p><em>Originally published at </em><a href="https://dougcosta.com/en/blog/astro-external-links-new-tab/"><em>https://dougcosta.com</em></a><em> on September 17, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1ae3d7ee1f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Website with Astro and Publishing It on GitHub Pages with GitHub Actions]]></title>
            <link>https://medium.com/@doug.cost/building-a-website-with-astro-and-publishing-it-on-github-pages-with-github-actions-doug-costa-2cac9b0c349f?source=rss-9a65542b6634------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cac9b0c349f</guid>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[astros]]></category>
            <category><![CDATA[github-pages]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Doug Costa]]></dc:creator>
            <pubDate>Wed, 16 Sep 2026 00:00:03 GMT</pubDate>
            <atom:updated>2026-09-21T19:50:34.387Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4YZLOQVEgI9SBONx3xWDYA.jpeg" /></figure><h4>A practical guide to creating a website with Astro’s blog template and automating its publication on GitHub Pages.</h4><h3>Introduction</h3><p>I remember that, early in my career, creating a website was not a complex activity, but it was very labor-intensive. Building all the HTML and CSS, as well as validating the site across different browsers, took a considerable amount of time. When it came to blogs, we would usually choose an existing platform such as Blogger, which already provided all the necessary structure. Today, tools such as Astro and GitHub Pages make this process much simpler. We can create our own website with just a few commands and choose a dedicated blog template, without having to rely on external solutions.</p><p>In this article, I will show, step by step, how to create a website using Astro’s blog template, add it to a GitHub repository, and configure an automated publishing workflow with GitHub Actions. All it takes is a push to the main branch, and our site will be published.</p><p>The goal is to start with a newly created project and end up with a website published and accessible on the internet, with the build and deploy process fully automated.</p><h3>Creating the project</h3><h3>Prerequisites</h3><p>Before creating the project, we need to have Node.js and Git installed. In this article, we will use NVM to manage Node.js versions.</p><p>Before installing anything, we can check whether Node.js, NVM, and Git are already available in the environment.</p><p>We can check the Node.js installation with:</p><pre>node --version</pre><p>We can check the NVM installation with:</p><pre>nvm --version</pre><p>We will also need Git installed and a GitHub account for the version control and publishing steps.</p><p>To check whether Git is available:</p><pre>git --version</pre><h3>Installing the prerequisites</h3><p>If any of the prerequisites are not installed, we can install them before continuing.</p><p>I am using a MacBook and Homebrew for the installations. Therefore, the commands shown in this article assume that environment, but they can be adapted to other operating systems.</p><p>First, let’s install NVM, which allows us to switch between Node versions without creating conflicts between different projects. For example:</p><pre>Project A → Node 20<br>Project B → Node 22<br>Project C → Node 24</pre><p>To install NVM:</p><pre>brew install nvm</pre><p>I use the Z shell (zsh) to interpret commands in my Terminal. Therefore, it needs to be configured so that it can properly interpret NVM commands. These steps are not required in environments that do not use Z shell and can be skipped.</p><p>The first step is to create the NVM directory:</p><pre>mkdir -p ~/.nvm</pre><p>In my case, using a MacBook with Apple Silicon, Homebrew is installed under /opt/homebrew/opt/nvm/. Before running the next command, check the path on your machine and adjust it accordingly.</p><p>We add NVM to the .zshrc file by running this entire command:</p><pre>cat &lt;&lt;&#39;EOF&#39; &gt;&gt; ~/.zshrc<br><br># NVM<br>export NVM_DIR=&quot;$HOME/.nvm&quot;<br>[ -s &quot;/opt/homebrew/opt/nvm/nvm.sh&quot; ] &amp;&amp; \. &quot;/opt/homebrew/opt/nvm/nvm.sh&quot;<br>[ -s &quot;/opt/homebrew/opt/nvm/etc/bash_completion.d/nvm&quot; ] &amp;&amp; \. &quot;/opt/homebrew/opt/nvm/etc/bash_completion.d/nvm&quot;<br>EOF</pre><p>Reload the configuration:</p><pre>source ~/.zshrc</pre><p>Let’s verify that NVM was installed successfully and that the zsh configuration is correct:</p><pre>nvm --version</pre><p>It should return something like the following (NVM version):</p><pre>0.40.7</pre><p>If everything went as expected, we can now install Node.js.</p><p>For the Astro project, we will use the LTS version of Node. LTS stands for Long-Term Support and refers to a version that receives support and security updates for an extended period.</p><p>Run:</p><pre>nvm install --lts</pre><p>When you run the command, NVM will:</p><ol><li>download the LTS version of Node;</li><li>install it under ~/.nvm;</li><li>make node and npm available;</li><li>normally select this version for the current session.</li></ol><p>Then verify the installation with:</p><pre>node --version<br>npm --version</pre><p>The commands should return something similar to:</p><pre>v24.x.x<br>11.x.x</pre><p>The exact numbers may differ depending on the current LTS version.</p><p>With the installation confirmed, let’s make the LTS version the default:</p><pre>nvm alias default &quot;lts/*&quot;</pre><p>When you open a new Terminal, NVM can automatically select this LTS version.</p><p>We have just put together a small toolchain that will be useful for any Node project you work on from now on:</p><pre>macOS<br>  │<br>  ├── Homebrew<br>  │      └── installs tools<br>  │<br>  └── NVM<br>         └── manages Node versions<br>                │<br>                ├── node<br>                └── npm<br>                       │<br>                       └── Astro</pre><p>Now we are ready to start setting up the blog with Astro.</p><h3>Creating the project with the blog template</h3><p>With the environment ready, we can create a new Astro project using:</p><pre>npm create astro@latest</pre><p>Astro starts an interactive wizard to configure the new project.</p><p>Among the available options are different project types, including a basic starter project, a blog template, a documentation template based on Starlight, and a minimal project. At some point, the wizard will ask us to choose the project type, displaying something like:</p><pre>How would you like to start your new project?<br>         ○ A basic, helpful starter project (recommended)<br>         ● Use blog template<br>         ○ Use docs (Starlight) template<br>         ○ Use minimal (empty) template</pre><p>We will choose <strong>Use blog template</strong>, because it already provides a suitable starting structure for a content-based website.</p><p>Next, the wizard will ask whether it should install the dependencies. For this walkthrough, choose <strong>No</strong>:</p><pre>Install dependencies? (recommended)<br>         ○ Yes  ● No</pre><p>The wizard will then ask whether it should initialize a new Git repository. Again, choose <strong>No</strong>. We will do that later:</p><pre>Initialize a new git repository? (optional)<br>         ○ Yes  ● No</pre><p>Once the wizard finishes, enter the directory we selected for the project. In my case, I created a directory called blog. So:</p><pre>cd blog</pre><p>Since we chose not to install the dependencies through the wizard, we need to install them explicitly:</p><pre>npm install</pre><h3>Running the project locally</h3><p>Astro provides several commands through package.json.</p><p>We can view the available scripts with:</p><pre>npm run</pre><p>Some of the main commands are:</p><ul><li>npm run dev: starts the development server.</li><li>npm run build: generates the production build.</li><li>npm run preview: runs the production build locally.</li><li>npm run astro: provides the Astro CLI.</li></ul><p>The available scripts may vary depending on the template and project configuration.</p><p>To start the development server:</p><pre>npm run dev</pre><p>Astro will make the site available at: <a href="http://localhost:4321/">http://localhost:4321/</a>.</p><p>Open this address in your browser to see the project running locally.</p><p>At this point, the flow is straightforward:</p><pre>Astro code<br>    ↓<br>npm run dev<br>    ↓<br>Astro development server<br>    ↓<br>localhost:4321<br>    ↓<br>Browser</pre><h3>Understanding the initial project</h3><h3>Directory structure</h3><p>After creating the project, it is worth getting familiar with its structure before starting to modify it. We can use:</p><pre>ls -la</pre><p>The structure will look similar to the following and may vary depending on the Astro version and the options selected in the wizard:</p><pre>blog/<br>├── public/<br>├── src/<br>│   ├── assets/<br>│   ├── components/<br>│   ├── content/<br>│   │   └── blog/<br>│   ├── layouts/<br>│   ├── pages/<br>│   └── styles/<br>├── .gitignore<br>├── astro.config.mjs<br>├── package.json<br>└── tsconfig.json</pre><p>Some of the most important directories are:</p><ul><li>src/pages/: contains the site&#39;s pages and routes.</li><li>src/components/: reusable components.</li><li>src/layouts/: layouts used by the pages.</li><li>src/content/: content organized into collections.</li><li>src/assets/: files that can be processed by Astro, such as images.</li><li>public/: static files that will be served directly.</li><li>astro.config.mjs: the main Astro configuration file.</li></ul><p>One of the advantages of starting with the blog template is that much of the structure needed for a content website is already in place.</p><p>The project already includes components for common site elements, layouts for pages, Markdown/MDX content configuration, and features related to publishing.</p><p>It is also worth noting that there are many free and paid Astro templates available online that can be used as a starting point. You are not limited to customizing this particular layout.</p><p>The package.json file also defines some basic scripts:</p><pre>{<br>  &quot;scripts&quot;: {<br>    &quot;dev&quot;: &quot;astro dev&quot;,<br>    &quot;build&quot;: &quot;astro build&quot;,<br>    &quot;preview&quot;: &quot;astro preview&quot;,<br>    &quot;astro&quot;: &quot;astro&quot;<br>  }<br>}</pre><h3>Preparing the project for GitHub</h3><h3>Creating the repository</h3><p>When creating the Astro project, we chose not to initialize a new repository. We therefore need to do this manually. Run:</p><pre>git init</pre><p>To use GitHub Pages as a <strong>personal website</strong>, the repository follows a specific naming convention:</p><pre>&lt;your-username&gt;.github.io</pre><p>In my case, for example, the repository is:</p><pre>dougcosta.github.io</pre><p>Create a new empty repository on GitHub, without adding a README, .gitignore, or other initial files, since the project already exists locally. Then connect the local directory to it (make sure to use the settings specific to your directory):</p><pre>git branch -M main<br>git remote add origin https://github.com/&lt;your-username&gt;/&lt;your-username&gt;.github.io.git</pre><p>Since we are using npm, package-lock.json should also be committed. It records the dependency versions used by the project and allows the installation to be reproduced more consistently. It is used by the Astro action during the build process. Therefore, make sure it is not included in .gitignore.</p><h3>Configuring the site URL in Astro</h3><p>Astro needs to know the public URL of the site.</p><p>This configuration is made in the <strong>astro.config.mjs</strong> file at the root of the project.</p><p>The site property should contain the public URL. In my case, it will be <a href="https://dougcosta.github.io/">https://dougcosta.github.io</a>; replace it with the URL you defined:</p><pre>export default defineConfig({<br>  site: &#39;https://dougcosta.github.io&#39;,<br>});</pre><p>The site property is used by Astro to generate absolute URLs when necessary.</p><p>Because the repository follows the convention for a personal GitHub Pages site, the site will be published directly at the root of the domain:</p><pre>https://dougcosta.github.io/</pre><h3>Publishing on GitHub Pages</h3><h3>Configuring GitHub Actions</h3><p>At this point, we can run the project locally and prepare the repository for version control and automated publishing.</p><p>GitHub Pages can host the static output generated by Astro, while GitHub Actions can automatically run the build and deployment process.</p><p>To do this, we need to manually create the <strong>.github/workflows/deploy.yml</strong> file and add the following content, which configures a basic workflow for this project:</p><pre>name: Deploy to GitHub Pages<br><br>on:<br>  push:<br>    branches: [main]<br>  workflow_dispatch:<br><br>permissions:<br>  contents: read<br>  pages: write<br>  id-token: write<br><br>jobs:<br>  build:<br>    runs-on: ubuntu-latest<br><br>    steps:<br>      - name: Checkout repository<br>        uses: actions/checkout@v6<br><br>      - name: Install, build, and upload site<br>        uses: withastro/action@v6<br><br>  deploy:<br>    needs: build<br>    runs-on: ubuntu-latest<br><br>    environment:<br>      name: github-pages<br>      url: ${{ steps.deployment.outputs.page_url }}<br><br>    steps:<br>      - name: Deploy to GitHub Pages<br>        id: deployment<br>        uses: actions/deploy-pages@v5</pre><p>The workflow runs automatically whenever a push occurs on the main branch.</p><p>There is also a workflow_dispatch option, which allows the workflow to be started manually from the GitHub interface.</p><p>The Astro action installs the dependencies, runs the build, and uploads the artifact.</p><p>First, the build job:</p><pre>Checkout the code<br>       ↓<br>Install dependencies<br>       ↓<br>Build Astro<br>       ↓<br>Upload artifact</pre><p>Then, the deploy job uses the generated artifact to publish it to GitHub Pages.</p><h3>Configuring GitHub Pages</h3><p>On GitHub, open the project repository and go to:</p><pre>Settings → Pages</pre><p>Under Build and deployment, select GitHub Actions as the publishing source.</p><h3>Making the first push</h3><p>Before sending changes to main, it is good practice to validate the production build locally.</p><pre>npm run build</pre><p>If the build completes without errors, we can push the code to GitHub.</p><p>After pushing to the main branch, GitHub Actions will detect the change and automatically start the workflow.</p><p>Add the files to version control:</p><pre>git add .</pre><p>Create the first commit:</p><pre>git commit -m &quot;Initial commit&quot;</pre><p>Push the changes to the remote repository:</p><pre>git push -u origin main</pre><h3>The build and deploy process</h3><p>From this point on, publishing no longer depends on a manual process.</p><p>Whenever there is a new push to the main branch:</p><pre>git push<br>    ↓<br>GitHub<br>    ↓<br>GitHub Actions<br>    ↓<br>Astro build<br>    ↓<br>Site artifact<br>    ↓<br>GitHub Pages<br>    ↓<br>Updated site</pre><p>This means that, after the initial setup, publishing a change to the site becomes a natural consequence of the development workflow.</p><p>At the end of this process, we have an Astro website published on GitHub Pages with an automated build and deployment process.</p><p>The code remains versioned on GitHub, and every change pushed to the main branch generates a new production version that is published automatically.</p><h3>Conclusion</h3><p>Creating and publishing a website with Astro and GitHub Pages is a very straightforward process. Much of the work described here is related to preparing the environment and installing the prerequisites. Only a few commands are needed to get Astro running locally.</p><p>Starting from a ready-made template, we versioned the code and configured a build and deployment workflow using GitHub Actions, resulting in a static website with an automated publishing process and no need to maintain our own server.</p><p>For someone who started working in software development two decades ago, the difference is particularly interesting. Early in my career, putting a website online involved many more configuration, infrastructure, and publishing steps. Today, it is possible to go from an empty directory to a published and automated website in relatively few steps. I think that simplicity is one of the most interesting aspects of modern web development.</p><h3>References</h3><p>The official documentation used as references for this article is:</p><p><em>Originally published at </em><a href="https://dougcosta.com/en/blog/building-a-site-with-astro-github-pages/"><em>https://dougcosta.com</em></a><em> on September 16, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cac9b0c349f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>