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!

2.5 KB
Raw Blame
import { useTranslation } from 'react-i18next'
import type { LoaderFunctionArgs, MetaFunction } from 'react-router'
import { data, redirect, useLoaderData } from 'react-router'
import type { SitemapFunction } from 'remix-sitemap'

import {
  defaultLanguage,
  getLangFromPath,
  getOgImageUrl,
} from '~/lib/constants'
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
  const { t } = useTranslation('common')

  if (!data) {
    return [
      ...getTitle(t('notFoundPage.title')),
      ...getDescription(t('notFoundPage.description')),
      ...getPreviewImage(),
    ]
  }

  const title = data?.seoTitle || data?.title || 'Blog'
  const intro = data?.seoDescription || data?.intro || t('description.blog')
  const ogImageUrl = blogImageUrl(data?.image) || getOgImageUrl(title, intro)

  return [
    ...getTitle(title, title.length <= 50),
    ...getDescription(intro),
    ...getPreviewImage(ogImageUrl),
    ...blogArticleMeta(data),
  ]
}

export const sitemap: SitemapFunction = () => ({
  exclude: true,
})

export async function loader({ request, params, url }: LoaderFunctionArgs) {
  const catchAllPath = params['*']

  if (!catchAllPath) {
    return data(null, { status: 404 })
  }

  // Blog-style content (rendered through this catch-all) lives under canonical
  // unprefixed URLs. If someone hits /de/imprint, redirect them to /imprint
  // rather than 404'ing β€” the language is still picked up from the cookie.
  const lang = getLangFromPath(`/${catchAllPath}`)
  if (lang) {
    const stripped = catchAllPath.slice(`${lang}/`.length)
    if (stripped) {
      return redirect(`/${stripped}${url.search}`, 301)
    }
  } else if (catchAllPath.startsWith(`${defaultLanguage}/`)) {
    // /en/imprint β†’ /imprint (default language is never present in the path)
    const stripped = catchAllPath.slice(`${defaultLanguage}/`.length)
    if (stripped) {
      return redirect(`/${stripped}${url.search}`, 301)
    }
  }

  const post = await getPost(request, catchAllPath, undefined, true)

  if (post) {
    return post
  }

  return data(null, { status: 404 })
}

export default function CatchAll() {
  const post = useLoaderData()

  if (post) {
    return <Post />
  }

  return <NotFound />
}