Skip to content

πŸ“ˆ Open source, privacy-first web analytics β€” a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

SEO optimisations

Blue Mouse04573ad5176a
diff --git a/web/app/api/api.server.ts b/web/app/api/api.server.ts
index b13e14e3e..5aa574f96 100644
--- a/web/app/api/api.server.ts
+++ b/web/app/api/api.server.ts
@@ -633,6 +633,8 @@ interface BlogPostContent {
title?: string
seoTitle?: string
seoDescription?: string
+ modified?: string
+ image?: string
hidden?: boolean
intro?: string
date?: string
diff --git a/web/app/pages/Blog/ArticleNav.tsx b/web/app/pages/Blog/ArticleNav.tsx
index a48dfbfb2..1e843210b 100644
--- a/web/app/pages/Blog/ArticleNav.tsx
+++ b/web/app/pages/Blog/ArticleNav.tsx
@@ -11,11 +11,7 @@ import { Fragment, RefObject, useCallback, useEffect, useState } from 'react'
import { Text } from '~/ui/Text'
import { cn } from '~/utils/generic'
-interface Heading {
- id: string
- text: string
- level: number
-}
+import type { ArticleHeading } from '~/utils/toc'
const PROGRESS_RADIUS = 15
const PROGRESS_STROKE = 2
@@ -73,20 +69,13 @@ function HeadingSelector({
headings,
activeId,
}: {
- headings: Heading[]
+ headings: ArticleHeading[]
activeId: string | null
}) {
const activeHeading = headings.find((h) => h.id === activeId)
const label = activeHeading?.text ?? headings[0]?.text ?? ''
const labelKey = activeHeading?.id ?? headings[0]?.id ?? 'toc'
- const scrollToHeading = (id: string) => {
- const el = document.getElementById(id)
- if (!el) return
- const y = el.getBoundingClientRect().top + window.scrollY - 80
- window.scrollTo({ top: y, behavior: 'smooth' })
- }
-
return (
<Popover className='relative min-w-0 flex-1'>
{({ close }) => (
@@ -123,6 +112,7 @@ function HeadingSelector({
<Transition
as={Fragment}
+ unmount={false}
enter='transition ease-out duration-150'
enterFrom='opacity-0 translate-y-2'
enterTo='opacity-100 translate-y-0'
@@ -131,8 +121,10 @@ function HeadingSelector({
leaveTo='opacity-0 translate-y-2'
>
<PopoverPanel
- anchor={{ to: 'top end', gap: 12 }}
- className='z-50 w-[min(400px,calc(100vw-2rem))] rounded-xl border border-gray-200/90 bg-white/92 p-1.5 shadow-2xl ring-1 ring-gray-300/60 backdrop-blur-xl backdrop-saturate-150 supports-backdrop-filter:bg-white/88 dark:border-white/10 dark:bg-slate-950/92 dark:ring-slate-600/50 dark:supports-backdrop-filter:bg-slate-950/84'
+ unmount={false}
+ as='nav'
+ aria-label='On this page'
+ className='absolute right-0 bottom-full z-50 mb-3 w-[min(400px,calc(100vw-4rem))] rounded-xl border border-gray-200/90 bg-white/92 p-1.5 shadow-2xl ring-1 ring-gray-300/60 backdrop-blur-xl backdrop-saturate-150 supports-backdrop-filter:bg-white/88 dark:border-white/10 dark:bg-slate-950/92 dark:ring-slate-600/50 dark:supports-backdrop-filter:bg-slate-950/84'
>
<div className='max-h-[50vh] overflow-y-auto'>
{headings.map((heading, index) => {
@@ -140,13 +132,10 @@ function HeadingSelector({
const isActive = heading.id === activeId
return (
- <button
+ <a
key={heading.id}
- type='button'
- onClick={() => {
- scrollToHeading(heading.id)
- close()
- }}
+ href={`#${heading.id}`}
+ onClick={() => close()}
className={cn(
'flex w-full items-center gap-2.5 rounded-lg px-2 py-1.5 text-left transition-colors',
isActive
@@ -182,7 +171,7 @@ function HeadingSelector({
>
{heading.text}
</Text>
- </button>
+ </a>
)
})}
</div>
@@ -196,27 +185,15 @@ function HeadingSelector({
export default function ArticleNav({
articleRef,
+ headings,
}: {
articleRef: RefObject<HTMLElement | null>
+ headings: ArticleHeading[]
}) {
- const [headings, setHeadings] = useState<Heading[]>([])
const [activeId, setActiveId] = useState<string | null>(null)
const [progress, setProgress] = useState(0)
const [visible, setVisible] = useState(false)
- useEffect(() => {
- const article = articleRef.current
- if (!article) return
-
- const els = article.querySelectorAll<HTMLElement>('h2[id], h3[id]')
- const items: Heading[] = Array.from(els).map((el) => ({
- id: el.id,
- text: el.textContent?.trim() ?? '',
- level: parseInt(el.tagName[1], 10),
- }))
- setHeadings(items)
- }, [articleRef])
-
const handleScroll = useCallback(() => {
const article = articleRef.current
if (!article) return
@@ -261,26 +238,26 @@ export default function ArticleNav({
window.removeEventListener('scroll', onScroll)
cancelAnimationFrame(rafId)
}
- }, [handleScroll])
+ }, [handleScroll, headings])
if (headings.length === 0) return null
return (
<AnimatePresence>
- {visible && (
- <motion.div
- initial={{ opacity: 0, y: 20 }}
- animate={{ opacity: 1, y: 0 }}
- exit={{ opacity: 0, y: 20 }}
- transition={{ duration: 0.2, ease: 'easeOut' }}
- className='fixed bottom-5 left-1/2 z-50 -translate-x-1/2'
- >
- <div className='flex max-w-[min(320px,calc(100vw-2rem))] min-w-0 items-center gap-0.5 rounded-full border border-gray-200/90 bg-white/90 py-0.5 pr-0.5 pl-1 shadow-2xl ring-1 ring-gray-300/60 backdrop-blur-xl backdrop-saturate-150 supports-backdrop-filter:bg-white/82 dark:border-white/10 dark:bg-slate-950/90 dark:ring-slate-600/50 dark:supports-backdrop-filter:bg-slate-950/82'>
- <ScrollToTopButton progress={progress} />
- <HeadingSelector headings={headings} activeId={activeId} />
- </div>
- </motion.div>
- )}
+ <motion.div
+ initial={false}
+ animate={{ opacity: visible ? 1 : 0, y: visible ? 0 : 20 }}
+ inert={!visible}
+ aria-hidden={!visible}
+ style={{ visibility: visible ? 'visible' : 'hidden' }}
+ transition={{ duration: 0.2, ease: 'easeOut' }}
+ className='fixed bottom-5 left-1/2 z-50 -translate-x-1/2'
+ >
+ <div className='flex max-w-[min(320px,calc(100vw-2rem))] min-w-0 items-center gap-0.5 rounded-full border border-gray-200/90 bg-white/90 py-0.5 pr-0.5 pl-1 shadow-2xl ring-1 ring-gray-300/60 backdrop-blur-xl backdrop-saturate-150 supports-backdrop-filter:bg-white/82 dark:border-white/10 dark:bg-slate-950/90 dark:ring-slate-600/50 dark:supports-backdrop-filter:bg-slate-950/82'>
+ <ScrollToTopButton progress={progress} />
+ <HeadingSelector headings={headings} activeId={activeId} />
+ </div>
+ </motion.div>
</AnimatePresence>
)
}
diff --git a/web/app/pages/Blog/Post.tsx b/web/app/pages/Blog/Post.tsx
index 31d42db72..5a290771c 100644
--- a/web/app/pages/Blog/Post.tsx
+++ b/web/app/pages/Blog/Post.tsx
@@ -8,17 +8,23 @@ import ExitIntentPopup from '~/components/ExitIntentPopup'
import NotFound from '~/pages/NotFound'
import ArticleNav from '~/pages/Blog/ArticleNav'
import { Text } from '~/ui/Text'
+import { getOgImageUrl } from '~/lib/constants'
+import {
+ blogBreadcrumbs,
+ blogDateToIso,
+ blogPostSchema,
+ serializeBlogSchema,
+ type BlogMetadata,
+} from '~/utils/blogMetadata'
+import type { ArticleHeading } from '~/utils/toc'
-interface Post {
+interface Post extends BlogMetadata {
slug: string
- title?: string
html: string
hidden?: boolean
- standalone?: boolean
- intro?: string
- date?: string
- author?: string
- twitter_handle?: string
+ headings: ArticleHeading[]
+ seoTitle?: string
+ seoDescription?: string
}
export default function PostSlug() {
@@ -54,7 +60,9 @@ export default function PostSlug() {
<dl>
<dt className='sr-only'>Date</dt>
<dd className='text-slate-700 dark:text-slate-400'>
- <time dateTime={post.date}>{post.date}</time>
+ <time dateTime={blogDateToIso(post.date)}>
+ {post.date}
+ </time>
</dd>
</dl>
</div>
@@ -96,49 +104,37 @@ export default function PostSlug() {
</li>
</ul>
</div>
- <div className='prose mt-6 max-w-4xl prose-slate dark:prose-invert'>
+ <div className='prose mt-6 max-w-4xl prose-slate dark:prose-invert prose-headings:scroll-mt-20'>
<div dangerouslySetInnerHTML={{ __html: post.html }} />
</div>
</article>
- {!post.standalone && <ArticleNav articleRef={articleRef} />}
+ {!post.standalone && (
+ <ArticleNav articleRef={articleRef} headings={post.headings} />
+ )}
{post.title ? (
<script
type='application/ld+json'
dangerouslySetInnerHTML={{
- __html: JSON.stringify({
- '@context': 'https://schema.org',
- '@type': 'BlogPosting',
- headline: post.title,
- ...(post.intro && { description: post.intro }),
- ...(post.date && {
- datePublished: post.date,
- dateModified: post.date,
- }),
- ...(post.author && {
- author: {
- '@type': 'Person',
- name: post.author,
- ...(post.twitter_handle && {
- url: `https://x.com/${post.twitter_handle}`,
- }),
- },
- }),
- publisher: {
- '@type': 'Organization',
- name: 'Swetrix',
- url: 'https://swetrix.com',
- logo: {
- '@type': 'ImageObject',
- url: 'https://swetrix.com/assets/logo_blue.png',
- },
- },
- mainEntityOfPage: {
- '@type': 'WebPage',
- '@id': `https://swetrix.com${location.pathname}`,
- },
- })
- .replace(/</g, '\\u003c')
- .replace(/\u2028|\u2029/g, ''),
+ __html: serializeBlogSchema([
+ blogPostSchema(
+ post,
+ location.pathname,
+ getOgImageUrl(
+ post.seoTitle || post.title || 'Blog',
+ post.seoDescription ||
+ post.intro ||
+ t('description.blog'),
+ ),
+ ),
+ ...(!post.standalone
+ ? [
+ blogBreadcrumbs(
+ post.title,
+ `https://swetrix.com${location.pathname}`,
+ ),
+ ]
+ : []),
+ ]),
}}
/>
) : null}
diff --git a/web/app/root.tsx b/web/app/root.tsx
index bddd57cf3..db1d80adb 100644
--- a/web/app/root.tsx
+++ b/web/app/root.tsx
@@ -28,6 +28,7 @@ import {
useRouteError,
useSearchParams,
useLocation,
+ useMatches,
} from 'react-router'
import { getAuthenticatedUser } from '~/api/api.server'
@@ -520,6 +521,17 @@ export default function App() {
}, [i18n, locale])
const isEmbedded = searchParams.get('embedded') === 'true'
+ const matches = useMatches()
+ const isArticle = matches.some(
+ ({ id, loaderData: data }) =>
+ ['routes/blog.$slug', 'routes/blog.$category.$slug', 'routes/$'].includes(
+ id,
+ ) &&
+ !!data &&
+ typeof data === 'object' &&
+ 'html' in data &&
+ 'title' in data,
+ )
const canonicalUrl = (() => {
const localisedPathname = localisePath(
@@ -528,6 +540,7 @@ export default function App() {
)
const next = new URL(`${MAIN_URL}${localisedPathname}${search}`)
next.searchParams.delete('lng')
+ if (isArticle || stripLangFromPath(pathname) === '/blog') next.search = ''
return next.toString()
})()
@@ -551,7 +564,7 @@ export default function App() {
<meta name='twitter:card' content='summary_large_image' />
<meta property='og:site_name' content='Swetrix' />
<meta property='og:url' content={canonicalUrl} />
- <meta property='og:type' content='website' />
+ <meta property='og:type' content={isArticle ? 'article' : 'website'} />
<meta name='language' content={i18n.language.toUpperCase()} />
<meta
httpEquiv='content-language'
diff --git a/web/app/routes/$.tsx b/web/app/routes/$.tsx
index 85c69e920..119646a57 100644
--- a/web/app/routes/$.tsx
+++ b/web/app/routes/$.tsx
@@ -12,6 +12,7 @@ import Post from '~/pages/Blog/Post'
import NotFound from '~/pages/NotFound'
import { getPost } from '~/utils/getPosts.server'
import { getDescription, getPreviewImage, getTitle } from '~/utils/seo'
+import { blogArticleMeta, blogImageUrl } from '~/utils/blogMetadata'
export const meta: MetaFunction<typeof loader> = ({ loaderData: data }) => {
// eslint-disable-next-line react-hooks/rules-of-hooks
@@ -27,12 +28,13 @@ export const meta: MetaFunction<typeof loader> = ({ loaderData: data }) => {
const title = data?.seoTitle || data?.title || 'Blog'
const intro = data?.seoDescription || data?.intro || t('description.blog')
- const ogImageUrl = getOgImageUrl(title, intro)
+ const ogImageUrl = blogImageUrl(data?.image) || getOgImageUrl(title, intro)
return [
...getTitle(title, title.length <= 50),
...getDescription(intro),
...getPreviewImage(ogImageUrl),
+ ...blogArticleMeta(data),
]
}
diff --git a/web/app/routes/blog.$category.$slug.tsx b/web/app/routes/blog.$category.$slug.tsx
index fc6e91e73..d31dd5621 100644
--- a/web/app/routes/blog.$category.$slug.tsx
+++ b/web/app/routes/blog.$category.$slug.tsx
@@ -10,6 +10,7 @@ import {
import Post from '~/pages/Blog/Post'
import { getPost } from '~/utils/getPosts.server'
import { getDescription, getPreviewImage, getTitle } from '~/utils/seo'
+import { blogArticleMeta, blogImageUrl } from '~/utils/blogMetadata'
export const meta: MetaFunction<typeof loader> = ({ loaderData: data }) => {
// eslint-disable-next-line react-hooks/rules-of-hooks
@@ -17,12 +18,13 @@ export const meta: MetaFunction<typeof loader> = ({ loaderData: data }) => {
const title = data?.seoTitle || data?.title || 'Blog'
const intro = data?.seoDescription || data?.intro || t('description.blog')
- const ogImageUrl = getOgImageUrl(title, intro)
+ const ogImageUrl = blogImageUrl(data?.image) || getOgImageUrl(title, intro)
return [
...getTitle(title, title.length <= 50),
...getDescription(intro),
...getPreviewImage(ogImageUrl),
+ ...blogArticleMeta(data),
]
}
diff --git a/web/app/routes/blog.$slug.tsx b/web/app/routes/blog.$slug.tsx
index 01d766e26..51d8958d6 100644
--- a/web/app/routes/blog.$slug.tsx
+++ b/web/app/routes/blog.$slug.tsx
@@ -16,6 +16,7 @@ import Post from '~/pages/Blog/Post'
import { getSlugFromFilename, getDateFromFilename } from '~/utils/blog'
import { getPost } from '~/utils/getPosts.server'
import { getDescription, getPreviewImage, getTitle } from '~/utils/seo'
+import { blogArticleMeta, blogImageUrl } from '~/utils/blogMetadata'
export const meta: MetaFunction<typeof loader> = ({ loaderData: data }) => {
// eslint-disable-next-line react-hooks/rules-of-hooks
@@ -23,12 +24,13 @@ export const meta: MetaFunction<typeof loader> = ({ loaderData: data }) => {
const title = data?.seoTitle || data?.title || 'Blog'
const intro = data?.seoDescription || data?.intro || t('description.blog')
- const ogImageUrl = getOgImageUrl(title, intro)
+ const ogImageUrl = blogImageUrl(data?.image) || getOgImageUrl(title, intro)
return [
...getTitle(title, title.length <= 50),
...getDescription(intro),
...getPreviewImage(ogImageUrl),
+ ...blogArticleMeta(data),
]
}
diff --git a/web/app/routes/blog._index.tsx b/web/app/routes/blog._index.tsx
index 0baabec26..37be3b241 100644
--- a/web/app/routes/blog._index.tsx
+++ b/web/app/routes/blog._index.tsx
@@ -1,4 +1,3 @@
-import _filter from 'lodash/filter'
import _isEmpty from 'lodash/isEmpty'
import _map from 'lodash/map'
import { CaretRightIcon } from '@phosphor-icons/react'
@@ -15,6 +14,11 @@ import {
} from '~/lib/constants'
import { getDescription, getPreviewImage, getTitle } from '~/utils/seo'
import { Text } from '~/ui/Text'
+import {
+ blogBreadcrumbs,
+ blogDateToIso,
+ serializeBlogSchema,
+} from '~/utils/blogMetadata'
export async function loader({ request }: LoaderFunctionArgs) {
if (isSelfhosted || isDisableMarketingPages) {
@@ -36,36 +40,78 @@ export const meta: MetaFunction = () => {
return [
...getTitle('Blog'),
- ...getDescription(t('description.blog')),
- ...getPreviewImage(getOgImageUrl('Blog', t('description.blog'))),
+ ...getDescription(t('blogPage.description')),
+ ...getPreviewImage(
+ getOgImageUrl('The Swetrix Blog', t('blogPage.description')),
+ ),
]
}
export default function Posts() {
- const posts: any[] = useLoaderData()
-
- if (_filter(posts, (post) => !post.hidden).length === 0) {
- return (
- <div className='flex min-h-min-footer items-center justify-center'>
- <Text as='h1' size='3xl' weight='bold'>
- No posts found
- </Text>
- </div>
- )
- }
+ const posts: any[] = useLoaderData() || []
+ const { t } = useTranslation('common')
+ const visiblePosts = posts.filter((post) => !post.hidden)
return (
<div className='bg-gray-50 py-10 text-gray-700 dark:bg-slate-950 dark:text-gray-300'>
<div className='mx-auto max-w-[52rem] px-4 pb-28 sm:px-6 md:px-8 lg:max-w-6xl xl:px-12'>
- <div className='relative mt-10 sm:ml-[calc(2rem+1px)] sm:pb-12 md:ml-[calc(3.5rem+1px)] lg:ml-[max(calc(14.5rem+1px),calc(100%-48rem))]'>
+ <header className='mx-auto max-w-3xl pt-6 pb-12 text-center sm:pt-10 sm:pb-16'>
+ <nav
+ aria-label={t('blogPage.breadcrumbLabel')}
+ className='mb-8 flex items-center justify-center gap-2 text-sm text-slate-500 dark:text-slate-400'
+ >
+ <Link to='/' className='hover:text-slate-900 dark:hover:text-white'>
+ {t('blogPage.home')}
+ </Link>
+ <CaretRightIcon className='size-3.5' aria-hidden='true' />
+ <span aria-current='page'>{t('footer.blog')}</span>
+ </nav>
+ <Text
+ as='h1'
+ weight='bold'
+ tracking='tight'
+ className='text-4xl text-slate-900 sm:text-5xl dark:text-white'
+ >
+ {t('blogPage.title')} <span aria-hidden='true'>πŸ“š</span>
+ </Text>
+ <p className='mx-auto mt-5 max-w-2xl text-base leading-7 text-slate-600 sm:text-lg sm:leading-8 dark:text-slate-400'>
+ {t('blogPage.description')}
+ </p>
+ </header>
+ <script
+ type='application/ld+json'
+ dangerouslySetInnerHTML={{
+ __html: serializeBlogSchema([
+ {
+ '@context': 'https://schema.org',
+ '@type': 'CollectionPage',
+ '@id': 'https://swetrix.com/blog#collection',
+ url: 'https://swetrix.com/blog',
+ name: t('blogPage.title'),
+ description: t('blogPage.description'),
+ mainEntity: {
+ '@type': 'ItemList',
+ itemListElement: visiblePosts.map((post, index) => ({
+ '@type': 'ListItem',
+ position: index + 1,
+ name: post.title,
+ url: `https://swetrix.com${post.standalone ? '/' : '/blog/'}${post.slug}`,
+ })),
+ },
+ },
+ blogBreadcrumbs(),
+ ]),
+ }}
+ />
+ {visiblePosts.length === 0 && (
+ <p className='text-center'>{t('blogPage.empty')}</p>
+ )}
+
+ <div className='relative sm:ml-[calc(2rem+1px)] sm:pb-12 md:ml-[calc(3.5rem+1px)] lg:ml-[max(calc(14.5rem+1px),calc(100%-48rem))]'>
<div className='absolute top-3 right-full bottom-0 mr-7 hidden w-px bg-slate-200 sm:block md:mr-[3.25rem] dark:bg-slate-700'></div>
<div className='space-y-16'>
- {_map(posts, (post) => {
- if (post.hidden) {
- return null
- }
-
+ {_map(visiblePosts, (post) => {
return (
<article className='group relative' key={post.slug}>
<svg
@@ -84,7 +130,7 @@ export default function Posts() {
<div className='relative'>
<Link to={post.standalone ? `/${post.slug}` : post.slug}>
<Text
- as='h3'
+ as='h2'
size='base'
weight='semibold'
className='pt-8 lg:pt-0'
@@ -100,7 +146,9 @@ export default function Posts() {
<dl className='absolute top-0 left-0 font-mono text-sm font-medium tracking-wide uppercase lg:right-full lg:left-auto lg:mr-[calc(5rem+1px)]'>
<dt className='sr-only'>Date</dt>
<dd className='text-sm leading-6 whitespace-nowrap dark:text-slate-400'>
- <time dateTime={post.date}>{post.date}</time>
+ <time dateTime={blogDateToIso(post.date)}>
+ {post.date}
+ </time>
</dd>
</dl>
</div>
diff --git a/web/app/utils/blogMetadata.ts b/web/app/utils/blogMetadata.ts
new file mode 100644
index 000000000..624e32be0
--- /dev/null
+++ b/web/app/utils/blogMetadata.ts
@@ -0,0 +1,167 @@
+export interface BlogMetadata {
+ title?: string
+ intro?: string
+ date?: string
+ modified?: string
+ image?: string
+ author?: string
+ twitter_handle?: string
+ standalone?: boolean
+}
+
+const MONTHS = [
+ 'january',
+ 'february',
+ 'march',
+ 'april',
+ 'may',
+ 'june',
+ 'july',
+ 'august',
+ 'september',
+ 'october',
+ 'november',
+ 'december',
+]
+
+export function blogDateToIso(value: unknown): string | undefined {
+ if (value instanceof Date) {
+ return Number.isNaN(value.getTime()) ? undefined : value.toISOString()
+ }
+ if (typeof value !== 'string') return undefined
+
+ const input = value.trim()
+ const written = /^([a-z]+) (\d{1,2}), (\d{4})$/i.exec(input)
+ const iso = /^(\d{4})-(\d{2})-(\d{2})(T.*)?$/.exec(input)
+ if (!written && !iso) return undefined
+
+ const year = Number(written ? written[3] : iso![1])
+ const month = written
+ ? MONTHS.indexOf(written[1].toLowerCase()) + 1
+ : Number(iso![2])
+ const day = Number(written ? written[2] : iso![3])
+ const calendarDate = new Date(0)
+ calendarDate.setUTCFullYear(year, month - 1, day)
+ calendarDate.setUTCHours(0, 0, 0, 0)
+ if (
+ month < 1 ||
+ month > 12 ||
+ day < 1 ||
+ calendarDate.getUTCFullYear() !== year ||
+ calendarDate.getUTCMonth() !== month - 1 ||
+ calendarDate.getUTCDate() !== day
+ )
+ return undefined
+
+ if (iso?.[4]) {
+ if (!/T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2})$/.test(iso[4]))
+ return undefined
+ const parsed = new Date(input)
+ return Number.isNaN(parsed.getTime()) ? undefined : parsed.toISOString()
+ }
+ return calendarDate.toISOString().slice(0, 10)
+}
+
+export function blogImageUrl(value: unknown): string | undefined {
+ if (typeof value !== 'string' || !value.trim()) return undefined
+ try {
+ const url = new URL(value)
+ return ['https:', 'http:'].includes(url.protocol) &&
+ !url.username &&
+ !url.password
+ ? url.href
+ : undefined
+ } catch {
+ return undefined
+ }
+}
+
+export function blogModifiedDate(post: BlogMetadata): string | undefined {
+ const published = blogDateToIso(post.date)
+ const modified = blogDateToIso(post.modified)
+ return modified &&
+ (!published || Date.parse(modified) >= Date.parse(published))
+ ? modified
+ : undefined
+}
+
+export function blogBreadcrumbs(title?: string, url?: string) {
+ const items = [
+ { name: 'Home', item: 'https://swetrix.com/' },
+ { name: 'Blog', item: 'https://swetrix.com/blog' },
+ ...(title && url ? [{ name: title, item: url }] : []),
+ ]
+ return {
+ '@context': 'https://schema.org',
+ '@type': 'BreadcrumbList',
+ itemListElement: items.map((item, index) => ({
+ '@type': 'ListItem',
+ position: index + 1,
+ ...item,
+ })),
+ }
+}
+
+export function blogPostSchema(
+ post: BlogMetadata,
+ pathname: string,
+ fallbackImageUrl: string,
+) {
+ const url = new URL(pathname, 'https://swetrix.com')
+ url.search = ''
+ url.hash = ''
+ const published = blogDateToIso(post.date)
+ const modified = blogModifiedDate(post)
+ const image = blogImageUrl(post.image) || blogImageUrl(fallbackImageUrl)
+ return {
+ '@context': 'https://schema.org',
+ '@type': 'BlogPosting',
+ '@id': `${url.href}#article`,
+ url: url.href,
+ headline: post.title,
+ ...(post.intro && { description: post.intro }),
+ ...(published && { datePublished: published }),
+ ...(modified && { dateModified: modified }),
+ ...(image && { image }),
+ ...(post.author && {
+ author: {
+ '@type': 'Person',
+ name: post.author,
+ ...(post.twitter_handle && {
+ url: `https://x.com/${post.twitter_handle}`,
+ }),
+ },
+ }),
+ publisher: {
+ '@type': 'Organization',
+ name: 'Swetrix',
+ url: 'https://swetrix.com',
+ logo: {
+ '@type': 'ImageObject',
+ url: 'https://swetrix.com/assets/logo_blue.png',
+ },
+ },
+ mainEntityOfPage: { '@type': 'WebPage', '@id': url.href },
+ }
+}
+
+export function blogArticleMeta(post?: BlogMetadata | null) {
+ if (!post?.title) return []
+ const published = blogDateToIso(post.date)
+ const modified = blogModifiedDate(post)
+ return [
+ ...(published
+ ? [{ property: 'article:published_time', content: published }]
+ : []),
+ ...(modified
+ ? [{ property: 'article:modified_time', content: modified }]
+ : []),
+ ...(post.author ? [{ name: 'author', content: post.author }] : []),
+ ]
+}
+
+export function serializeBlogSchema(value: unknown): string {
+ return JSON.stringify(value)
+ .replace(/</g, '\\u003c')
+ .replace(/\u2028|\u2029/g, '')
+}
diff --git a/web/app/utils/getPosts.server.ts b/web/app/utils/getPosts.server.ts
index 13ba422d9..190b8256a 100644
--- a/web/app/utils/getPosts.server.ts
+++ b/web/app/utils/getPosts.server.ts
@@ -7,8 +7,9 @@ import { getBlogPost, getBlogPostWithCategory } from '~/api/api.server'
import { renderTimeToSwitchCta, renderDitchGoogleCta } from './renderCtaHtml'
import {
extractTableOfContents,
+ extractArticleHeadings,
+ type ArticleHeading,
ensureHeaderIds,
- generateSlug,
renderTocAsHtml,
} from './toc'
@@ -23,16 +24,11 @@ renderer.link = ({ href, text }: Tokens.Link) => {
return text
}
- if (url.hostname !== 'swetrix.com') {
- url.searchParams.set('utm_source', 'swetrix.com')
- }
-
- return `<a href="${url.toString()}" referrerpolicy="strict-origin-when-cross-origin" target="_blank" rel="noopener noreferrer">${text}</a>`
+ return `<a href="${url.toString()}" referrerpolicy="strict-origin-when-cross-origin" target="_blank" rel="noopener">${text}</a>`
}
renderer.heading = ({ text, depth }: Tokens.Heading) => {
- const id = generateSlug(text)
- return `<h${depth} id="${id}">${text}</h${depth}>`
+ return `<h${depth}>${text}</h${depth}>`
}
function parseInlineMarkdown(text: string): string {
@@ -185,6 +181,9 @@ interface GetPost {
standalone?: boolean
intro?: string
date?: string
+ modified?: string
+ image?: string
+ headings: ArticleHeading[]
author?: string
twitter_handle?: string
}
@@ -318,6 +317,9 @@ export async function getPost(
hidden: post.attributes?.hidden,
intro: post.attributes?.intro,
date: post.attributes?.date,
+ modified: post.attributes?.modified,
+ image: post.attributes?.image,
+ headings: extractArticleHeadings(html),
author: post.attributes?.author,
twitter_handle: post.attributes?.twitter_handle,
standalone: post.attributes?.standalone,
diff --git a/web/app/utils/toc.ts b/web/app/utils/toc.ts
index c25cb6dbf..59dffcddd 100644
--- a/web/app/utils/toc.ts
+++ b/web/app/utils/toc.ts
@@ -5,6 +5,12 @@ interface TocItem {
children: TocItem[]
}
+export interface ArticleHeading {
+ id: string
+ text: string
+ level: number
+}
+
import { escapeHtml } from './generic'
function stripHtmlTags(input: string): string {
@@ -108,17 +114,54 @@ export function extractTableOfContents(html: string): TocItem[] {
}
export function ensureHeaderIds(html: string): string {
+ const used = new Set<string>()
return html.replace(
/<h([1-6])(?:\s+id="([^"]*)")?([^>]*)>(.*?)<\/h[1-6]>/gi,
(match, level, existingId, attrs, content) => {
- if (existingId) {
- return match // Already has an ID
- }
-
const text = stripHtmlTags(content)
- const id = generateSlug(text)
+ const base = existingId || generateSlug(text) || 'section'
+ let id = base
+ let suffix = 2
+ while (used.has(id)) id = `${base}-${suffix++}`
+ used.add(id)
return `<h${level} id="${id}"${attrs}>${content}</h${level}>`
},
)
}
+
+export function extractArticleHeadings(html: string): ArticleHeading[] {
+ const headings: ArticleHeading[] = []
+ const collect = (items: TocItem[]) => {
+ for (const item of items) {
+ if (item.level === 2 || item.level === 3) {
+ const text = item.text.replace(
+ /&(#x[\da-f]+|#\d+|amp|lt|gt|quot|apos|nbsp);/gi,
+ (entity, name: string) => {
+ const named: Record<string, string> = {
+ amp: '&',
+ lt: '<',
+ gt: '>',
+ quot: '"',
+ apos: "'",
+ nbsp: ' ',
+ }
+ if (!name.startsWith('#'))
+ return named[name.toLowerCase()] || entity
+ const value =
+ name[1].toLowerCase() === 'x'
+ ? parseInt(name.slice(2), 16)
+ : Number(name.slice(1))
+ return value > 0 && value <= 0x10ffff
+ ? String.fromCodePoint(value)
+ : entity
+ },
+ )
+ headings.push({ id: item.id, text, level: item.level })
+ }
+ collect(item.children)
+ }
+ }
+ collect(extractTableOfContents(html))
+ return headings
+}
diff --git a/web/public/locales/en.json b/web/public/locales/en.json
index a4462f444..d22f64adb 100644
--- a/web/public/locales/en.json
+++ b/web/public/locales/en.json
@@ -3652,6 +3652,13 @@
}
}
},
+ "blogPage": {
+ "title": "The Swetrix Blog",
+ "description": "Practical guides to web analytics, privacy, and growing your website. Learn what brings people to your site, what they do next, and how to turn those insights into better decisions.",
+ "home": "Home",
+ "breadcrumbLabel": "Breadcrumb",
+ "empty": "No posts found"
+ },
"exitIntentPopup": {
"freeTrial": "Free Trial",
"title": "Web Analytics without cookies",
diff --git a/web/scripts/tests/blog-metadata.test.mjs b/web/scripts/tests/blog-metadata.test.mjs
new file mode 100644
index 000000000..4785ad957
--- /dev/null
+++ b/web/scripts/tests/blog-metadata.test.mjs
@@ -0,0 +1,127 @@
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import {
+ blogArticleMeta,
+ blogBreadcrumbs,
+ blogDateToIso,
+ blogImageUrl,
+ blogPostSchema,
+ serializeBlogSchema,
+} from '../../app/utils/blogMetadata.ts'
+
+test('converts existing written dates and preserves ISO calendar dates', () => {
+ assert.equal(blogDateToIso('July 17, 2026'), '2026-07-17')
+ assert.equal(blogDateToIso('September 24, 2026'), '2026-09-24')
+ assert.equal(blogDateToIso('2024-02-29'), '2024-02-29')
+ assert.equal(
+ blogDateToIso('2026-09-24T12:00:00+01:00'),
+ '2026-09-24T11:00:00.000Z',
+ )
+ assert.equal(
+ blogDateToIso(new Date('2026-09-24T11:00:00Z')),
+ '2026-09-24T11:00:00.000Z',
+ )
+})
+
+test('omits invalid or ambiguous dates instead of rolling into another month', () => {
+ for (const input of [
+ 'February 30, 2026',
+ '2026-02-29',
+ '2026-13-01',
+ 'Nope 2, 2026',
+ '24/09/2026',
+ '2026-09-24T12:00:00',
+ undefined,
+ '',
+ new Date('invalid'),
+ ]) {
+ assert.equal(blogDateToIso(input), undefined)
+ }
+})
+
+test('adds only supplied, valid image and modification metadata', () => {
+ const post = {
+ title: 'A useful article',
+ date: 'July 17, 2026',
+ author: 'Andrii Romasiun',
+ }
+ const fallbackImage =
+ 'https://swetrix.com/api/og-image.png?title=A%20useful%20article&description='
+ const old = blogPostSchema(
+ post,
+ '/blog/article?utm_source=test',
+ fallbackImage,
+ )
+ assert.equal(old.datePublished, '2026-07-17')
+ assert.equal('dateModified' in old, false)
+ assert.equal(old.image, fallbackImage)
+ assert.equal(old.mainEntityOfPage['@id'], 'https://swetrix.com/blog/article')
+ const updated = blogPostSchema(
+ {
+ ...post,
+ modified: 'September 24, 2026',
+ image: 'https://cdn.swetrix.com/file/cover.png',
+ },
+ '/blog/article',
+ fallbackImage,
+ )
+ assert.equal(updated.dateModified, '2026-09-24')
+ assert.equal(updated.image, 'https://cdn.swetrix.com/file/cover.png')
+ assert.equal(
+ 'dateModified' in
+ blogPostSchema(
+ { ...post, modified: 'July 16, 2026' },
+ '/blog/article',
+ fallbackImage,
+ ),
+ false,
+ )
+ assert.equal(
+ blogPostSchema(
+ { ...post, image: 'javascript:alert(1)' },
+ '/blog/article',
+ fallbackImage,
+ ).image,
+ fallbackImage,
+ )
+ assert.equal(
+ blogArticleMeta({ ...post, modified: 'September 24, 2026' }).find(
+ (entry) => entry.property === 'article:modified_time',
+ )?.content,
+ '2026-09-24',
+ )
+})
+
+test('rejects non-web image URLs and credentials', () => {
+ for (const input of [
+ 'javascript:alert(1)',
+ 'data:image/png;base64,a',
+ 'ftp://example.com/image.png',
+ '/relative.png',
+ 'https://user:[email protected]/image.png',
+ undefined,
+ ]) {
+ assert.equal(blogImageUrl(input), undefined)
+ }
+})
+
+test('describes the blog hierarchy and safely serializes article titles', () => {
+ const crumbs = blogBreadcrumbs(
+ 'Article',
+ 'https://swetrix.com/blog/article',
+ ).itemListElement
+ assert.deepEqual(
+ crumbs.map((item) => item.position),
+ [1, 2, 3],
+ )
+ assert.equal(crumbs[1].item, 'https://swetrix.com/blog')
+ assert.equal(blogBreadcrumbs().itemListElement.length, 2)
+ const encoded = serializeBlogSchema({
+ headline: '</script><script>alert(1)</script>',
+ })
+ assert.equal(encoded.includes('<'), false)
+ assert.equal(
+ JSON.parse(encoded).headline,
+ '</script><script>alert(1)</script>',
+ )
+})