fix: lang switch
All checks were successful
Build & Deploy / 🔍 Prepare (push) Successful in 6s
Build & Deploy / 🧪 QA (push) Successful in 2m14s
Build & Deploy / 🏗️ Build (push) Successful in 3m24s
Build & Deploy / 🚀 Deploy (push) Successful in 16s
Build & Deploy / 🧪 Post-Deploy Verification (push) Successful in 42m44s
Build & Deploy / 🔔 Notify (push) Successful in 2s

This commit is contained in:
2026-02-27 02:56:23 +01:00
parent b3057d8be0
commit 9e7f6ec76f
8 changed files with 311 additions and 71 deletions

View File

@@ -59,7 +59,8 @@ export async function getPostBySlug(slug: string, locale: string): Promise<PostD
try {
const payload = await getPayload({ config: configPromise });
const { docs } = await payload.find({
// First try: Find in the requested locale
let { docs } = await payload.find({
collection: 'posts',
where: {
slug: { equals: slug },
@@ -70,6 +71,38 @@ export async function getPostBySlug(slug: string, locale: string): Promise<PostD
limit: 1,
});
// Fallback: If not found, try searching across all locales.
// This happens when a user uses the static language switcher
// e.g. switching from /en/blog/en-slug to /de/blog/en-slug.
if (!docs || docs.length === 0) {
const { docs: crossLocaleDocs } = await payload.find({
collection: 'posts',
where: {
slug: { equals: slug },
...(!config.showDrafts ? { _status: { equals: 'published' } } : {}),
},
locale: 'all',
draft: config.showDrafts,
limit: 1,
});
if (crossLocaleDocs && crossLocaleDocs.length > 0) {
// Fetch the found document again, but strictly in the requested locale
// so we get the correctly translated fields (like the localized slug)
const { docs: correctLocaleDocs } = await payload.find({
collection: 'posts',
where: {
id: { equals: crossLocaleDocs[0].id },
},
locale: locale as any,
draft: config.showDrafts,
limit: 1,
});
docs = correctLocaleDocs;
}
}
if (!docs || docs.length === 0) return null;
const doc = docs[0];