Fixed notfound headers, r2storage

This commit is contained in:
2026-10-13 15:57:59 +02:00
parent 86c873e4e7
commit 786dd346a9
24 changed files with 1506 additions and 2765 deletions
+57 -56
View File
@@ -74,8 +74,8 @@ export function createContentHelpers({
settingsSlug = 'site-settings',
}: CreateContentHelpersArgs) {
const origin = baseUrl ?? process.env.NEXT_PUBLIC_SERVER_URL ?? ''
const getCachedPayload = cache(async (): Promise<BasePayload> =>
getPayload({ config: await config }),
const getCachedPayload = cache(
async (): Promise<BasePayload> => getPayload({ config: await config }),
)
const getConfiguredLocales = cache(async (): Promise<string[]> => {
@@ -102,8 +102,9 @@ export function createContentHelpers({
/**
* The page assigned as 404 in System Pages (or null → built-in fallback).
* For app/not-found.tsx; never throws. Locale comes from the x-locale header
* set by createProxy (not-found.tsx receives no params).
* For app/not-found.tsx; never throws. not-found.tsx receives no params and
* must NOT read headers() (breaks SSG/ISR) — call this for every configured
* locale and let <LocaleView> (client) pick the one from the URL. See pages.md.
*/
const getNotFoundPage = cache(async (locale: string) => {
try {
@@ -150,7 +151,9 @@ export function createContentHelpers({
*/
const sitemap = cache(async (): Promise<SitemapEntry[]> => {
if (!i18n) {
throw new Error('[ipal] createContentHelpers: pass `i18n` to use the sitemap handler.')
throw new Error(
'[ipal] createContentHelpers: pass `i18n` to use the sitemap handler.',
)
}
try {
return await buildSitemapEntries({
@@ -235,62 +238,60 @@ export function createContentHelpers({
const params: Array<{ locale: string; slug: string[] } | { slug: string[] }> = []
for (const locale of locales) {
// NO where:{_status} filter — collections without drafts enabled don't
// register the _status field, and querying it throws
// "path cannot be queried: _status". We filter drafts in memory below,
// which is safe for every collection (with or without drafts).
const result = await payload.find({
collection: pagesSlug as never,
depth: 0,
limit: 1000,
locale: (locale ?? 'all') as never,
})
// NO where:{_status} filter — collections without drafts enabled don't
// register the _status field, and querying it throws
// "path cannot be queried: _status". We filter drafts in memory below,
// which is safe for every collection (with or without drafts).
const result = await payload.find({
collection: pagesSlug as never,
depth: 0,
limit: 1000,
locale: (locale ?? 'all') as never,
})
for (const raw of result.docs as Array<{
_status?: string
id: number | string
meta?: { noindex?: boolean } | null
slug?: unknown
}>) {
// Draft filter in memory (safe whether or not the collection has drafts).
if (raw._status && raw._status !== 'published') {continue}
if (notFoundId !== undefined && raw.id === notFoundId) {continue}
for (const raw of result.docs as Array<{
_status?: string
id: number | string
meta?: { noindex?: boolean } | null
slug?: unknown
}>) {
// Draft filter in memory (safe whether or not the collection has drafts).
if (raw._status && raw._status !== 'published') {continue}
if (notFoundId !== undefined && raw.id === notFoundId) {continue}
// NOTE: unlike the sitemap, we do NOT skip meta.noindex here. A noindex
// page (privacy, cookies, terms) still needs to render — users reach it
// from the footer and crawlers read its <meta robots=noindex>. Pre-render
// it as SSG so it's fast and its <head> is complete; noindex controls
// INDEXING, not whether the page exists. Skipping it would force dynamic
// rendering (the very streaming problem we're avoiding).
// NOTE: unlike the sitemap, we do NOT skip meta.noindex here. A noindex
// page (privacy, cookies, terms) still needs to render — users reach it
// from the footer and crawlers read its <meta robots=noindex>. Pre-render
// it as SSG so it's fast and its <head> is complete; noindex controls
// INDEXING, not whether the page exists. Skipping it would force dynamic
// rendering (the very streaming problem we're avoiding).
if (homeId && raw.id === homeId) {
// Homepage → root. Emit an empty-slug param so '/' (or '/pl') builds.
const empty = singleLocale ? { slug: [] } : { slug: [], locale: locale as string }
if (!params.some((p) => JSON.stringify(p) === JSON.stringify(empty))) {params.push(empty)}
continue
}
// Slug may be a plain string OR a localized map ({ pl: 'kontakt' }) when
// read with locale:'all' or left unflattened. Handle both, or localized
// pages get silently dropped.
const rawSlug = raw.slug
const slug =
typeof rawSlug === 'string'
? rawSlug
: rawSlug && typeof rawSlug === 'object'
? (((rawSlug as Record<string, unknown>)[locale ?? ''] as string | undefined) ??
(Object.values(rawSlug as Record<string, unknown>)[0] as string | undefined))
: undefined
if (!slug || EXCLUDED.has(slug)) {continue}
// Multi-level slugs ('atrakcje/telefon') → array segments.
const segments = String(slug).split('/').filter(Boolean)
params.push(
singleLocale ? { slug: segments } : { slug: segments, locale: locale as string },
)
if (homeId && raw.id === homeId) {
// Homepage → root. Emit an empty-slug param so '/' (or '/pl') builds.
const empty = singleLocale ? { slug: [] } : { slug: [], locale: locale as string }
if (!params.some((p) => JSON.stringify(p) === JSON.stringify(empty))) {params.push(empty)}
continue
}
// Slug may be a plain string OR a localized map ({ pl: 'kontakt' }) when
// read with locale:'all' or left unflattened. Handle both, or localized
// pages get silently dropped.
const rawSlug = raw.slug
const slug =
typeof rawSlug === 'string'
? rawSlug
: rawSlug && typeof rawSlug === 'object'
? ((rawSlug as Record<string, unknown>)[locale ?? ''] as string | undefined) ??
(Object.values(rawSlug as Record<string, unknown>)[0] as string | undefined)
: undefined
if (!slug || EXCLUDED.has(slug)) {continue}
// Multi-level slugs ('atrakcje/telefon') → array segments.
const segments = String(slug).split('/').filter(Boolean)
params.push(singleLocale ? { slug: segments } : { slug: segments, locale: locale as string })
}
}
return params
} catch (err) {
+32
View File
@@ -0,0 +1,32 @@
'use client'
import type { ReactNode } from 'react'
// '.js' is required: `next` has no package.json "exports", so NodeNext resolution
// (this plugin's tsconfig) can't find 'next/navigation' without the extension.
// Bundlers in the project resolve the same file either way.
import { usePathname } from 'next/navigation.js'
type LocaleViewProps = {
/** Used when the URL has no locale segment (single-locale site) or an unknown one. */
defaultLocale: string
/**
* One pre-rendered view per locale, e.g. { pl: <RenderBlocks …/>, en: … }.
* Rendered on the SERVER (RSC) and passed in as props — this component only
* picks one, so the content can come from the panel and the route stays static.
*/
views: Record<string, ReactNode>
}
/**
* Shows the view matching the locale in the current URL (`/en/...` → `en`).
*
* Made for `not-found.tsx`, which receives no `params`: reading the locale with
* `headers()` there turns an SSG/ISR route dynamic ("Page changed from static
* to dynamic at runtime"). `usePathname()` is client-side and static-safe, and
* it also runs during SSR, so the HTML already contains the right language.
*/
export function LocaleView({ defaultLocale, views }: LocaleViewProps) {
const pathname = usePathname() ?? ''
const segment = pathname.split('/').filter(Boolean)[0] ?? ''
const locale = segment in views ? segment : defaultLocale
return <>{views[locale] ?? views[defaultLocale] ?? null}</>
}
+48 -3
View File
@@ -1,6 +1,27 @@
import type { Plugin } from 'payload'
import { s3Storage } from '@payloadcms/storage-s3'
type GenerateFileURL = (args: { filename: string; prefix?: string }) => string
/**
* Minimal shape of `s3Storage` from @payloadcms/storage-s3 — the plugin never
* imports that package (it's optional: projects on local disk don't install it).
* The project injects the real function; TypeScript checks it fits this shape.
*/
export type S3StorageFactory = (options: {
bucket: string
collections: Record<string, { generateFileURL: GenerateFileURL } | true>
config: {
credentials: { accessKeyId: string; secretAccessKey: string }
endpoint: string
forcePathStyle: boolean
region: string
}
}) => Plugin
export type BuildR2StorageDeps = {
/** `import { s3Storage } from '@payloadcms/storage-s3'` — required when R2 env is set. */
s3Storage?: S3StorageFactory
}
/**
* Cloudflare R2 media storage — configured from environment variables (agency
@@ -16,9 +37,22 @@ import { s3Storage } from '@payloadcms/storage-s3'
* storage (useful in dev without R2). This mirrors how mailAdapter degrades
* gracefully when a transport isn't configured.
*
* The S3 adapter is INJECTED by the project (same pattern as 2FA / NextResponse):
*
* import { s3Storage } from '@payloadcms/storage-s3'
* plugins: [buildR2Storage(['media'], { s3Storage })]
*
* A static import here would make @payloadcms/storage-s3 mandatory for every
* project — including ones on local disk — because this module is exported
* from the package's main entry.
*
* @param collections - slugs of upload collections to offload to R2 (e.g. ['media'])
* @param deps - `{ s3Storage }` from @payloadcms/storage-s3 (needed only when R2 env is set)
*/
export const buildR2Storage = (collections: string[] = ['media']): Plugin => {
export const buildR2Storage = (
collections: string[] = ['media'],
deps: BuildR2StorageDeps = {},
): Plugin => {
const bucket = process.env.R2_BUCKET
const endpoint = process.env.R2_ENDPOINT
const accessKeyId = process.env.R2_ACCESS_KEY_ID
@@ -54,7 +88,18 @@ export const buildR2Storage = (collections: string[] = ['media']): Plugin => {
[publicUrl, prefix, filename].filter(Boolean).join('/')
: undefined
const collectionsConfig: Record<string, { generateFileURL: typeof generateFileURL } | true> = {}
// R2 env is complete → the adapter is required. Fail loudly at boot rather
// than silently storing media on the container disk (lost on redeploy).
const { s3Storage } = deps
if (!s3Storage) {
throw new Error(
'[ipal] R2 storage: R2_* env is set but the S3 adapter was not injected. ' +
"Install @payloadcms/storage-s3 and pass it: buildR2Storage(['media'], { s3Storage }) " +
"with `import { s3Storage } from '@payloadcms/storage-s3'`. See docs/storage.md.",
)
}
const collectionsConfig: Record<string, { generateFileURL: GenerateFileURL } | true> = {}
for (const slug of collections) {
collectionsConfig[slug] = generateFileURL ? { generateFileURL } : true
}
+1
View File
@@ -1 +1,2 @@
export { buildR2Storage } from './buildR2Storage.js'
export type { BuildR2StorageDeps, S3StorageFactory } from './buildR2Storage.js'