feat: Journal author and tag pages, SEO, sitemap source and RSS route

- author pages resolve slug or login and canonicalise to the slug
- tag pages, per-page SEO meta and canonicals that keep ?page=N
- sitemap source pages the API and builds locs from journal.routes
- /rss.xml proxies the API feed with x-forwarded-for
- neutral README; version 0.1.0
This commit is contained in:
2026-10-09 18:06:20 +02:00
parent c408eeb2ca
commit 70e0eddb47
17 changed files with 501 additions and 21 deletions

View File

@@ -3,6 +3,7 @@
export default defineNuxtConfig({
extends: ['..'],
compatibilityDate: '2025-07-15',
site: { url: 'https://acme.test', name: 'Acme Blog' },
i18n: {
strategy: 'prefix_except_default',
defaultLocale: 'en',

153
README.md Normal file
View File

@@ -0,0 +1,153 @@
# vue-journal-layer
A Nuxt 4 layer that renders a Journal blog (post list, post, category, tag and author pages, RSS link, SEO and sitemap) from the Journal API of a SummerCMS application.
```bash
pnpm add git+https://git.golem15.com/golem15/vue-journal-layer.git#v0.1.0
```
## Overview
The layer is consumed with `extends: ['vue-journal-layer']`. It reads content only from the anonymous GET routes of the Journal API (`/_journal/api/v1`) and never calls a write route. Pages render on the server (SSR), so every URL answers with full HTML.
The layer is neutral: it ships no site colours and no site copy. Its look comes from `--journal-*` CSS custom properties, which an app overrides, and every component can be replaced by a file of the same name in the app.
Route paths are configuration, not files. The layer's page components live in `app/journal-pages/` and a local module registers them at the paths in `journal.routes`, so an app moves the blog to any URL shape, or switches a view off, without copying pages. Route names stay stable, and links are always built from the names.
## Features
- **Post list** (`journal-index`): paginated with `?page=N`. A non-numeric page or a page past the last one answers 404.
- **Post** (`journal-post`): title, date, reading time, categories, author, featured image, body, previous and next links, and related posts. When the API returns no related posts (a post without a category), the latest posts are shown instead.
- **Category** (`journal-category`): name, description and the category's rich HTML content above its posts. Categories are always requested with `include_empty=1`, so a category without posts still has a page. An unknown category answers 404, which makes the route safe as a root-level catch-all such as `/:category`.
- **Tag** (`journal-tag`) and **author** (`journal-author`) pages. An author resolves by author slug, or by login once the author has a published post; a login URL sets the canonical to the slug URL.
- **RSS**: `/rss.xml` proxies the API feed, and list and post pages link it in the head.
- **SEO**: per-page title and description, Open Graph tags (`og:image` from the featured image, article times), canonical URLs that keep `?page=N`, robots and `sitemap.xml` through `@nuxtjs/seo`.
- **HTML gate**: post bodies and category content pass the Journal API's three-pattern gate (raw script, iframe, object or embed tags; event-handler attributes; javascript, vbscript or data URLs) before `v-html`. A value that fails it renders a neutral notice and never reaches the page or the SSR payload.
- **i18n**: English and Polish UI strings, registered only for the locales the app enables.
## Usage
```ts
// nuxt.config.ts of the app
export default defineNuxtConfig({
extends: ['vue-journal-layer'],
site: { url: 'https://blog.acme.test', name: 'Acme Blog' },
i18n: {
strategy: 'prefix_except_default',
defaultLocale: 'en',
locales: [{ code: 'en', language: 'en-US' }],
},
journal: {
routes: {
index: '/blog',
post: '/blog/:slug',
category: '/:category', // category pages at the root
author: '/authors/:author',
tag: false, // no tag pages
},
perPage: { index: 12, category: 10 },
},
// SSR cache, so a new post shows up without a rebuild.
routeRules: { '/**': { swr: 300 } },
})
```
The layer declares `@nuxt/fonts`, `@nuxtjs/i18n` and `@nuxtjs/seo` itself. Do not list them again in the app; if the app must, pin the same exact versions. Static app pages such as `/about` take precedence over a `/:category` route.
Run the built app with `node .output/server/index.mjs` next to the SummerCMS application and point `NUXT_JOURNAL_API_BASE` at it.
## Configuration
Options under the `journal` key of `nuxt.config`:
| Key | Default | Meaning |
|-----|---------|---------|
| `journal.routes.index` | `/blog` | Post list path, or `false` |
| `journal.routes.post` | `/blog/:slug` | Post path; must contain `:slug`, or `false` |
| `journal.routes.category` | `/blog/category/:category` | Category path; must contain `:category`, or `false` |
| `journal.routes.tag` | `/blog/tag/:tag` | Tag path; must contain `:tag`, or `false` |
| `journal.routes.author` | `/blog/author/:author` | Author path; must contain `:author`, or `false` |
| `journal.perPage.index` | `9` | Posts per list page (the API caps at 30) |
| `journal.perPage.category` | `9` | Posts per category page |
| `journal.perPage.tag` | `9` | Posts per tag page |
| `journal.perPage.author` | `9` | Posts per author page |
| `journal.sort` | `published_at desc` | `<column> <asc\|desc>`; columns `published_at`, `created_at`, `updated_at`, `title`, `id` |
| `journal.relatedCount` | `3` | Related posts under a post |
| `journal.rss` | `true` | Serve and link `/rss.xml` |
A route path must be `false` or start with `/`; a missing param fails the build with an error naming `journal.routes.<key>`.
Runtime config, overridable by environment variables at start:
| Key | Env | Default | Meaning |
|-----|-----|---------|---------|
| `runtimeConfig.journal.apiBase` | `NUXT_JOURNAL_API_BASE` | `http://127.0.0.1:8096/_journal/api/v1` | Server-side API base for SSR, the sitemap and RSS. Use the internal address of the SummerCMS application, not its public URL. |
| `runtimeConfig.public.journal.apiBase` | `NUXT_PUBLIC_JOURNAL_API_BASE` | `/_journal/api/v1` | Browser API base for client-side navigation; the reverse proxy routes it to the application. |
The module also copies `routes`, `perPage`, `sort`, `relatedCount` and `rss` into `runtimeConfig.public.journal`.
Server-side requests forward the visitor's `x-forwarded-for` and append the address of the peer that reached Nuxt. The Journal API rate-limits anonymous reads per client address; with a trusted proxy configured for the Nuxt server's address, each visitor keeps their own bucket instead of all SSR traffic sharing one. The API base always comes from runtime config, never from request input.
## Theming
Every visual value is a token in `app/assets/css/journal-tokens.css`:
- Colour: `--journal-color-text`, `--journal-color-muted`, `--journal-color-bg`, `--journal-color-surface`, `--journal-color-border`, `--journal-color-link`, `--journal-color-link-hover`, `--journal-color-accent`, `--journal-color-on-accent`
- Type: `--journal-font-body`, `--journal-font-heading`, `--journal-font-mono`, `--journal-font-size-base`, `--journal-line-height`
- Spacing: `--journal-space-1` to `--journal-space-6`
- Radii: `--journal-radius-sm`, `--journal-radius-md`, `--journal-radius-lg`
- Layout: `--journal-content-width`, `--journal-wide-width`, `--journal-card-min`, `--journal-image-ratio`
Override tokens in the app's CSS. The app's `css` entries load after the layer's; a `:root:root` selector wins regardless of order:
```css
:root:root {
--journal-color-link: #b4232a;
--journal-font-heading: 'Acme Serif', serif;
}
```
Override a component by creating the same file in the app, for example `app/components/Journal/PostCard.vue`. The overridable components are `JournalPostBody`, `JournalPostCard`, `JournalPostList`, `JournalPostMeta`, `JournalFeaturedImage`, `JournalPagination`, `JournalRelatedPosts`, `JournalIndexHeader`, `JournalCategoryHeader`, `JournalAuthorCard` and `JournalRssLink`. A replacement that renders HTML from the API must keep the gate (`gateJournalHtml`) in front of `v-html`.
Pages and components can use the `useJournalApi()` client and the `useJournalLinks()` link helpers (`postLink`, `categoryLink`, `tagLink`, `authorLink`, `indexLink`), which return `null` for a disabled view.
## i18n
The layer ships `i18n/locales/en.json` and `pl.json` under the `journal.*` key tree. It declares no locales itself: its module registers a string file only for a locale the app enables, so an app that enables only `pl` gets no `/en` routes. An app that enables another locale adds its own `journal.*` strings in its locale file. Dates are formatted with `Intl.DateTimeFormat` for the active locale's `language`, in UTC.
## SEO and sitemap
Set `site.url` and `site.name` in the app: titles take the form `<page title> | <site.name>`, and canonical and Open Graph URLs are absolute against `site.url`. Canonical URLs keep only the `page` query parameter (`seo.canonicalQueryWhitelist`).
`sitemap.xml` includes the app's static pages plus a dynamic source at `/api/__sitemap__/journal`, which pages through the posts (30 per request) and adds every category, building each URL from `journal.routes`. A disabled view adds no URLs.
The feed's item links come from the Journal API, which links posts under `/blog/<slug>` on the application's configured URL. An app that moves `journal.routes.post` away from `/blog/:slug` should keep that in mind.
## Local development
```bash
pnpm install
pnpm dev # the .playground app, extending this layer
pnpm build:playground # production build of the playground
```
To work on the layer inside an app, link it instead of installing from git: `pnpm link ../vue-journal-layer`, or an `overrides` entry `vue-journal-layer: link:../vue-journal-layer` in `pnpm-workspace.yaml`. Never commit the link; the app's committed dependency stays the git tag.
## Releasing
A release is an annotated git tag (`v0.1.0`) on `main`, pushed to git.golem15.com. Apps pin it in `package.json` as `git+https://git.golem15.com/golem15/vue-journal-layer.git#<tag>`, and `pnpm-lock.yaml` records the tag's commit. To upgrade, change the tag and run `pnpm install`. The repository is public, so installing needs no credentials. The layer has no install-time build or `prepare` script, which a git-hosted dependency would need to run during `pnpm install`.
## Testing
- `scripts/check-git-install.sh <tag>` installs the layer from the git tag into a scratch app, checks that `pnpm-lock.yaml` pins the tag's commit, runs `nuxt build`, and runs the SSR smoke against the build. Run it from a directory that is not inside a directory named `vue-journal-layer` (Nuxt treats such a path segment as the layer).
- `testing/smoke-ssr.mjs --output <.output> --fixtures <dir> --expect <file>` boots a fixture Journal API and the built server and checks each line of the expectations file (`STATUS PATH [contains=TEXT] [notcontains=TEXT] [type=PREFIX]`). It also checks that SSR requests forwarded `x-forwarded-for` and that categories were requested with `include_empty=1`.
- `testing/fixture-api.mjs` (`startFixtureApi`) serves the anonymous Journal routes from JSON fixtures in `testing/fixtures/acme/`; `testing/nuxt-server.mjs` (`startNuxtServer`) starts a built server. Apps can import both from `node_modules/vue-journal-layer/testing/`.
```bash
pnpm build:playground
node testing/smoke-ssr.mjs --output .playground/.output --fixtures testing/fixtures/acme --expect testing/expect-acme.txt
```

View File

@@ -0,0 +1,18 @@
<script setup lang="ts">
// The author heading of an author page: the author's name from the public
// author endpoint. An app adds profile details by overriding this component
// or filling the default slot.
import type { JournalAuthor } from '../../utils/types.ts'
const props = defineProps<{ author: JournalAuthor; page?: number }>()
const name = computed(() => `${props.author.first_name} ${props.author.last_name}`.trim() || props.author.slug)
</script>
<template>
<header class="journal-author-card">
<h1 class="journal-author-card__name">
{{ $t('journal.author.title', { name }) }}<template v-if="page && page > 1"> · {{ $t('journal.pagination.pageTitle', { page }) }}</template>
</h1>
<slot />
</header>
</template>

View File

@@ -0,0 +1,16 @@
<script setup lang="ts">
// Advertises /rss.xml in the head and shows a visible feed link. Renders
// nothing when journal.rss is false.
const rss = (useRuntimeConfig().public.journal as { rss?: boolean }).rss !== false
const { t } = useI18n()
if (rss) {
useHead({
link: [{ rel: 'alternate', type: 'application/rss+xml', title: t('journal.rss.title'), href: '/rss.xml', key: 'journal-rss' }],
})
}
</script>
<template>
<a v-if="rss" href="/rss.xml" class="journal-rss-link" type="application/rss+xml">{{ $t('journal.rss.title') }}</a>
</template>

View File

@@ -1,21 +1,59 @@
<script setup lang="ts">
// journal-author: an author and their posts; an unknown author is a 404.
// journal-author: an author and their published posts, paginated with
// ?page=N. {author} is the author slug, or a login with published posts. An
// unknown author or an out-of-range page is a real 404. When the visitor came
// in by login, the canonical points at the slug URL.
import { pageOutOfRange, parsePageParam } from '../utils/pagination.ts'
import { absoluteUrl, listTitle } from '../utils/seo.ts'
import { toListPost } from '../utils/view.ts'
import type { JournalModuleOptions } from '../utils/types.ts'
definePageMeta({ key: (route) => route.fullPath })
const route = useRoute()
const api = useJournalApi()
const slug = String(route.params.author ?? '')
const { data } = await useAsyncData(`journal-author-${slug}`, async () => {
const author = await api.getAuthor(slug)
const links = useJournalLinks()
const site = useSiteConfig()
const { t } = useI18n()
const cfg = useRuntimeConfig().public.journal as JournalModuleOptions
const param = String(route.params.author ?? '')
const page = parsePageParam(route.query.page)
if (page === null) throw createError({ statusCode: 404, statusMessage: 'Page not found', fatal: true })
const { data, error } = await useAsyncData(`journal-author-${param}-${page}`, async () => {
const author = await api.getAuthor(param)
if (!author) return null
return { author, page: await api.listAuthorPosts(slug) }
const posts = await api.listAuthorPosts(param, { page, perPage: cfg.perPage.author, sort: cfg.sort })
if (!posts) return null
return { author, posts: { ...posts, data: posts.data.map(toListPost) } }
})
if (!data.value) throw createError({ statusCode: 404, fatal: true })
if (error.value) {
throw createError({ statusCode: (error.value as { statusCode?: number }).statusCode ?? 500, fatal: true })
}
if (!data.value) throw createError({ statusCode: 404, statusMessage: 'Author not found', fatal: true })
if (pageOutOfRange(page, data.value.posts.meta.last_page)) {
throw createError({ statusCode: 404, statusMessage: 'Page not found', fatal: true })
}
const author = data.value.author
const name = `${author.first_name} ${author.last_name}`.trim() || author.slug
const title = listTitle(t('journal.author.title', { name }), page, t('journal.pagination.pageTitle', { page }))
useSeoMeta({ title, ogTitle: title, ogType: 'profile' })
if (author.slug !== param) {
const path = links.authorLink(author.slug)
if (path) {
const href = absoluteUrl(page > 1 ? `${path}?page=${page}` : path, site.url || useRequestURL().origin)
useHead({ link: [{ rel: 'canonical', href, key: 'canonical' }] })
}
}
</script>
<template>
<section v-if="data" class="journal-author">
<h1>{{ data.author.first_name }} {{ data.author.last_name }}</h1>
<ul v-if="data.page">
<li v-for="post in data.page.data" :key="post.id">{{ post.title }}</li>
</ul>
<JournalAuthorCard :author="data.author" :page="page" />
<JournalPostList :posts="data.posts.data" :empty="$t('journal.author.empty')" />
<JournalPagination :current="data.posts.meta.current_page" :last="data.posts.meta.last_page" />
</section>
</template>

View File

@@ -5,6 +5,7 @@
// route may be a root-level catch-all in the app).
import { gateJournalHtml } from '../utils/htmlGate.ts'
import { pageOutOfRange, parsePageParam } from '../utils/pagination.ts'
import { listTitle } from '../utils/seo.ts'
import { toListPost } from '../utils/view.ts'
import type { JournalModuleOptions } from '../utils/types.ts'
@@ -13,6 +14,7 @@ definePageMeta({ key: (route) => route.fullPath })
const route = useRoute()
const api = useJournalApi()
const cfg = useRuntimeConfig().public.journal as JournalModuleOptions
const { t } = useI18n()
const slug = String(route.params.category ?? '')
const page = parsePageParam(route.query.page)
@@ -38,6 +40,10 @@ if (!data.value) throw createError({ statusCode: 404, statusMessage: 'Category n
if (pageOutOfRange(page, data.value.posts.meta.last_page)) {
throw createError({ statusCode: 404, statusMessage: 'Page not found', fatal: true })
}
const title = listTitle(data.value.category.name, page, t('journal.pagination.pageTitle', { page }))
const description = data.value.category.description ?? undefined
useSeoMeta({ title, ogTitle: title, description, ogDescription: description })
</script>
<template>

View File

@@ -2,6 +2,7 @@
// journal-index: the post list, paginated with ?page=N. A non-numeric page
// or a page past the last one is a real 404.
import { pageOutOfRange, parsePageParam } from '../utils/pagination.ts'
import { listTitle } from '../utils/seo.ts'
import { toListPost } from '../utils/view.ts'
import type { JournalModuleOptions } from '../utils/types.ts'
@@ -11,6 +12,7 @@ definePageMeta({ key: (route) => route.fullPath })
const route = useRoute()
const api = useJournalApi()
const cfg = useRuntimeConfig().public.journal as JournalModuleOptions
const { t } = useI18n()
const page = parsePageParam(route.query.page)
if (page === null) throw createError({ statusCode: 404, statusMessage: 'Page not found', fatal: true })
@@ -26,6 +28,9 @@ if (error.value || !data.value) {
if (pageOutOfRange(page, data.value.meta.last_page)) {
throw createError({ statusCode: 404, statusMessage: 'Page not found', fatal: true })
}
const title = listTitle(t('journal.index.title'), page, t('journal.pagination.pageTitle', { page }))
useSeoMeta({ title, ogTitle: title })
</script>
<template>
@@ -33,5 +38,6 @@ if (pageOutOfRange(page, data.value.meta.last_page)) {
<JournalIndexHeader :page="page" />
<JournalPostList :posts="data.data" />
<JournalPagination :current="data.meta.current_page" :last="data.meta.last_page" />
<JournalRssLink />
</section>
</template>

View File

@@ -3,6 +3,7 @@
// is a real 404. The transform gates the body before it reaches the payload.
// Related posts fall back to the latest posts when the API has none (it
// returns none for a post without a category).
import { postSeoMeta } from '../utils/seo.ts'
import { toListPost, toPostView } from '../utils/view.ts'
import type { JournalModuleOptions } from '../utils/types.ts'
@@ -34,6 +35,8 @@ if (error.value) {
if (!post.value) {
throw createError({ statusCode: 404, statusMessage: 'Post not found', fatal: true })
}
useSeoMeta(postSeoMeta(post.value, useSiteConfig().url || useRequestURL().origin))
</script>
<template>
@@ -63,5 +66,6 @@ if (!post.value) {
</NuxtLink>
</nav>
<JournalRelatedPosts :posts="post.related_posts" />
<JournalRssLink />
</article>
</template>

View File

@@ -1,21 +1,47 @@
<script setup lang="ts">
// journal-tag: posts with one tag; an unknown tag is a 404.
// journal-tag: posts with one tag, paginated with ?page=N. An unknown tag or
// an out-of-range page is a real 404.
import { pageOutOfRange, parsePageParam } from '../utils/pagination.ts'
import { listTitle } from '../utils/seo.ts'
import { toListPost } from '../utils/view.ts'
import type { JournalModuleOptions } from '../utils/types.ts'
definePageMeta({ key: (route) => route.fullPath })
const route = useRoute()
const api = useJournalApi()
const { t } = useI18n()
const cfg = useRuntimeConfig().public.journal as JournalModuleOptions
const slug = String(route.params.tag ?? '')
const { data } = await useAsyncData(`journal-tag-${slug}`, async () => {
const tag = (await api.listTags()).find((t) => t.slug === slug)
const page = parsePageParam(route.query.page)
if (page === null) throw createError({ statusCode: 404, statusMessage: 'Page not found', fatal: true })
const { data, error } = await useAsyncData(`journal-tag-${slug}-${page}`, async () => {
const tag = (await api.listTags()).find((row) => row.slug === slug)
if (!tag) return null
return { tag, page: await api.listPosts({ tag: tag.slug }) }
const posts = await api.listPosts({ tag: tag.slug, page, perPage: cfg.perPage.tag, sort: cfg.sort })
return { tag, posts: { ...posts, data: posts.data.map(toListPost) } }
})
if (!data.value) throw createError({ statusCode: 404, fatal: true })
if (error.value) {
throw createError({ statusCode: (error.value as { statusCode?: number }).statusCode ?? 500, fatal: true })
}
if (!data.value) throw createError({ statusCode: 404, statusMessage: 'Tag not found', fatal: true })
if (pageOutOfRange(page, data.value.posts.meta.last_page)) {
throw createError({ statusCode: 404, statusMessage: 'Page not found', fatal: true })
}
const heading = t('journal.tag.title', { name: data.value.tag.name })
const title = listTitle(heading, page, t('journal.pagination.pageTitle', { page }))
useSeoMeta({ title, ogTitle: title })
</script>
<template>
<section v-if="data" class="journal-tag">
<h1>{{ data.tag.name }}</h1>
<ul>
<li v-for="post in data.page.data" :key="post.id">{{ post.title }}</li>
</ul>
<header class="journal-index-header">
<h1 class="journal-index-header__title">{{ title }}</h1>
</header>
<JournalPostList :posts="data.posts.data" :empty="$t('journal.tag.empty')" />
<JournalPagination :current="data.posts.meta.current_page" :last="data.posts.meta.last_page" />
</section>
</template>

70
app/utils/seo.ts Normal file
View File

@@ -0,0 +1,70 @@
// SEO values for Journal pages, fed to useSeoMeta. The site name suffix comes
// from the app's site.name through the SEO title template, not from here.
import type { JournalPost } from './types.ts'
/** Plain text of an HTML fragment: tags dropped, common entities decoded, whitespace collapsed. */
export function htmlToText(html: string | null | undefined): string {
if (!html) return ''
return html
.replace(/<(script|style)\b[\s\S]*?<\/\1>/gi, ' ')
.replace(/<[^>]*>/g, ' ')
.replace(/&nbsp;/g, ' ')
.replace(/&quot;/g, '"')
.replace(/&#39;|&apos;/g, "'")
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&amp;/g, '&')
.replace(/\s+/g, ' ')
.trim()
}
/** Cuts `text` to at most `max` characters, at a word boundary when one is near, with an ellipsis. */
export function truncateText(text: string, max: number = 160): string {
if (text.length <= max) return text
const cut = text.slice(0, max - 1)
const space = cut.lastIndexOf(' ')
return `${(space > max * 0.6 ? cut.slice(0, space) : cut).trimEnd()}…`
}
/** Makes `url` absolute against `siteUrl`; already absolute URLs and a missing siteUrl pass through. */
export function absoluteUrl(url: string, siteUrl?: string | null): string {
if (/^https?:\/\//i.test(url) || !siteUrl) return url
return `${siteUrl.replace(/\/+$/, '')}/${url.replace(/^\/+/, '')}`
}
export interface JournalPostSeo {
title: string
ogTitle: string
description: string
ogDescription: string
ogType: 'article'
ogImage?: string
articlePublishedTime?: string
articleModifiedTime?: string
}
/**
* Meta for a post page: the post title, the excerpt (or the first 160
* characters of the body text) as description, the featured image as
* og:image, and the publish and update times.
*/
export function postSeoMeta(post: JournalPost, siteUrl?: string | null): JournalPostSeo {
const description = truncateText(htmlToText(post.excerpt) || htmlToText(post.content_html), 160)
const meta: JournalPostSeo = {
title: post.title,
ogTitle: post.title,
description,
ogDescription: description,
ogType: 'article',
}
if (post.featured_image_url) meta.ogImage = absoluteUrl(post.featured_image_url, siteUrl)
if (post.published_at) meta.articlePublishedTime = post.published_at
if (post.updated_at) meta.articleModifiedTime = post.updated_at
return meta
}
/** A listing title; pages after the first append the "Page N" string. */
export function listTitle(base: string, page: number, pageTitle: string): string {
return page > 1 ? `${base} · ${pageTitle}` : base
}

40
app/utils/sitemap.ts Normal file
View File

@@ -0,0 +1,40 @@
// Sitemap entries for Journal content. Every loc is built from journal.routes,
// so moving or disabling a view moves or drops its URLs; nothing hard-codes
// a path.
import { flattenCategories } from './client.ts'
import { fillJournalPath } from './routes.ts'
import type { JournalCategory, JournalPost, JournalRoutes } from './types.ts'
export interface JournalSitemapEntry {
loc: string
lastmod?: string
}
/**
* One entry per published post (lastmod = updated_at) at routes.post, and one
* per category of the flattened tree at routes.category. A disabled route
* contributes nothing.
*/
export function buildJournalSitemapEntries(
posts: readonly JournalPost[],
categories: readonly JournalCategory[],
routes: JournalRoutes,
): JournalSitemapEntry[] {
const entries: JournalSitemapEntry[] = []
if (routes.post !== false) {
for (const post of posts) {
if (!post.published || !post.slug) continue
const entry: JournalSitemapEntry = { loc: fillJournalPath(routes.post, { slug: post.slug }) }
if (post.updated_at) entry.lastmod = post.updated_at
entries.push(entry)
}
}
if (routes.category !== false) {
for (const category of flattenCategories(categories)) {
if (!category.slug) continue
entries.push({ loc: fillJournalPath(routes.category, { category: category.slug }) })
}
}
return entries
}

View File

@@ -41,6 +41,14 @@ export default defineNuxtConfig({
// No OG image rendering at runtime.
ogImage: { enabled: false },
// Paginated listings keep ?page=N in their canonical URL. nuxt-seo-utils
// already whitelists page by default; set explicitly to lock the behaviour.
seo: { canonicalQueryWhitelist: ['page'] },
// Journal posts and categories come from the API through the layer's
// sitemap source; locs are built from journal.routes. One flat sitemap.
sitemap: { sources: ['/api/__sitemap__/journal'], autoI18n: false },
// i18n: the layer declares no locales. The journal module registers the
// layer's pl/en strings only for locales the app enables.
})

View File

@@ -1,6 +1,6 @@
{
"name": "vue-journal-layer",
"version": "0.0.1",
"version": "0.1.0",
"private": true,
"type": "module",
"main": "./nuxt.config.ts",

View File

@@ -20,6 +20,12 @@ for tool in git pnpm node; do
done
WORK="$(mktemp -d "${TMPDIR:-/tmp}/journal-git-install.XXXXXX")"
# Nuxt applies its auto-import transform to any path with a
# /vue-journal-layer/ segment (how it finds a layer inside node_modules), so a
# scratch app below such a directory would transform every dependency.
case "$WORK/" in
*/vue-journal-layer/*) rm -rf "$WORK"; die "TMPDIR must not be inside a directory named vue-journal-layer" ;;
esac
cleanup() { rm -rf "$WORK"; }
trap cleanup EXIT
@@ -56,6 +62,7 @@ cat >nuxt.config.ts <<'TS'
export default defineNuxtConfig({
extends: ['vue-journal-layer'],
compatibilityDate: '2025-07-15',
site: { url: 'https://acme.test', name: 'Acme Blog' },
i18n: {
strategy: 'prefix_except_default',
defaultLocale: 'en',

View File

@@ -0,0 +1,36 @@
// Sitemap source for Journal content (sitemap.sources in the layer config).
// It pages GET /posts at per_page=30 until meta.last_page, fetches the
// category tree with include_empty=1, and builds every loc from
// journal.routes. The API base is server runtime config, never request input.
import { createJournalClient, type JournalFetcher } from '../../../app/utils/client.ts'
import { buildJournalSitemapEntries } from '../../../app/utils/sitemap.ts'
import type { JournalPost, JournalRoutes } from '../../../app/utils/types.ts'
/** Hard stop for a runaway last_page (30 000 posts). */
const MAX_PAGES = 1000
export default defineSitemapEventHandler(async (event) => {
const config = useRuntimeConfig(event)
const base = (config.journal as { apiBase: string }).apiBase
const routes = (config.public.journal as { routes: JournalRoutes }).routes
const forwarded = [getRequestHeader(event, 'x-forwarded-for'), getRequestIP(event)]
.filter((v): v is string => typeof v === 'string' && v !== '')
.join(', ')
const headers: Record<string, string> = forwarded ? { 'x-forwarded-for': forwarded } : {}
const fetcher: JournalFetcher = (path, query) => $fetch(path, { baseURL: base, query, headers })
const api = createJournalClient(fetcher)
const posts: JournalPost[] = []
if (routes.post !== false) {
for (let page = 1; page <= MAX_PAGES; page++) {
const res = await api.listPosts({ page, perPage: 30 })
posts.push(...res.data)
if (page >= res.meta.last_page) break
}
}
const categories = routes.category !== false ? await api.listCategories() : []
return buildJournalSitemapEntries(posts, categories, routes)
})

32
server/routes/rss.xml.ts Normal file
View File

@@ -0,0 +1,32 @@
// /rss.xml: the Journal API's RSS 2.0 feed, served from the site origin.
// The visitor's x-forwarded-for is forwarded (plus the peer address) so the
// API's rate limiter keeps one bucket per visitor. 404 when journal.rss is
// false, 502 when the API does not answer.
export default defineEventHandler(async (event) => {
const config = useRuntimeConfig(event)
if ((config.public.journal as { rss?: boolean }).rss === false) {
throw createError({ statusCode: 404, statusMessage: 'Not found' })
}
const base = (config.journal as { apiBase: string }).apiBase
const forwarded = [getRequestHeader(event, 'x-forwarded-for'), getRequestIP(event)]
.filter((v): v is string => typeof v === 'string' && v !== '')
.join(', ')
let body: string
try {
body = await $fetch<string>('/rss', {
baseURL: base,
responseType: 'text',
headers: forwarded ? { 'x-forwarded-for': forwarded } : {},
})
} catch {
setResponseStatus(event, 502)
setResponseHeader(event, 'content-type', 'text/plain; charset=utf-8')
return 'The feed is unavailable.'
}
setResponseHeader(event, 'content-type', 'application/rss+xml; charset=utf-8')
return body
})

View File

@@ -1,6 +1,7 @@
# SSR expectations against the acme fixtures (testing/fixtures/acme).
# Grammar: STATUS PATH [contains=TEXT] [notcontains=TEXT] [type=PREFIX]
# The consumer enables en (default, no prefix) and pl (/pl prefix).
# The consumer enables en (default, no prefix) and pl (/pl prefix), and sets
# site.url to https://acme.test.
# Single post
200 /blog/hello-acme contains=Hello Acme
@@ -23,3 +24,21 @@
# Related posts fall back to the latest posts for a post without a category
200 /blog/uncategorised-note contains=Hello Acme
# Author (slug and login resolve) and tag pages
200 /blog/author/jane-doe contains=Jane Doe
200 /blog/author/jdoe contains=<link rel="canonical" href="https://acme.test/blog/author/jane-doe"
404 /blog/author/nobody
200 /blog/tag/release contains=Hello Acme
404 /blog/tag/nope
# RSS, sitemap, canonical and meta
200 /rss.xml type=application/rss+xml
200 /blog contains=href="/rss.xml"
200 /sitemap.xml contains=/blog/hello-acme
200 /sitemap.xml contains=/blog/category/quiet
200 /sitemap.xml notcontains=/blog/draft-note
200 /blog?page=2 contains=?page=2
200 /blog?page=2 contains=<link rel="canonical" href="https://acme.test/blog?page=2">
200 /blog/hello-acme contains=og:title
200 /blog/hello-acme contains=Acme says hello and introduces its blog.