Skip to content

Commit 6a238d8

Browse files
committedDec 17, 2024·
fix: gracefully handle broken nuxt content endpoint
1 parent 1293ac7 commit 6a238d8

File tree

3 files changed

+17
-8
lines changed

3 files changed

+17
-8
lines changed
 

Diff for: ‎src/runtime/server/plugins/initContext.ts

-1
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ export default defineNitroPlugin(async (nitroApp: NitroApp) => {
2020
}
2121
catch (e) {
2222
logger.error('Failed to read robot rules from content files.', e)
23-
// silently fail I suppose
2423
}
2524
if (urls && Array.isArray(urls) && urls.length) {
2625
urls.forEach((url: string) => nuxtContentUrls.add(withoutTrailingSlash(url)))

Diff for: ‎src/runtime/server/routes/robots-txt.ts

+14-7
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { HookRobotsConfigContext, HookRobotsTxtContext } from '../../types'
2+
import { logger } from '#robots/server/logger'
23
import { withSiteUrl } from '#site-config/server/composables/utils'
34
import { defineEventHandler, setHeader } from 'h3'
45
import { useNitroApp, useRuntimeConfig } from 'nitropack/runtime'
@@ -32,17 +33,23 @@ export default defineEventHandler(async (e) => {
3233
.map(s => !s.startsWith('http') ? withSiteUrl(e, s, { withBase: true, absolute: true }) : s),
3334
)]
3435
if (usingNuxtContent) {
35-
const contentWithRobotRules = await e.$fetch<string[]>('/__robots__/nuxt-content.json', {
36+
const contentWithRobotRules = await e.$fetch<string[]>('/__robots__/3nuxt-content.json', {
3637
headers: {
3738
Accept: 'application/json',
3839
},
3940
})
40-
// add to first '*' group
41-
for (const group of robotsTxtCtx.groups) {
42-
if (group.userAgent.includes('*')) {
43-
group.disallow.push(...contentWithRobotRules)
44-
// need to filter out empty strings since we now have some content
45-
group.disallow = group.disallow.filter(Boolean)
41+
// ensure it's valid json
42+
if (String(contentWithRobotRules).trim().startsWith('<!DOCTYPE')) {
43+
logger.error('Invalid HTML returned from /__robots__/nuxt-content.json, skipping.')
44+
}
45+
else {
46+
// add to first '*' group
47+
for (const group of robotsTxtCtx.groups) {
48+
if (group.userAgent.includes('*')) {
49+
group.disallow.push(...contentWithRobotRules)
50+
// need to filter out empty strings since we now have some content
51+
group.disallow = group.disallow.filter(Boolean)
52+
}
4653
}
4754
}
4855
}

Diff for: ‎test/fixtures/content/nuxt.config.ts

+3
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,11 @@ export default defineNuxtConfig({
66
NuxteRobots,
77
'@nuxt/content',
88
],
9+
910
site: {
1011
url: 'https://nuxtseo.com',
1112
},
13+
1214
debug: process.env.NODE_ENV === 'test',
15+
compatibilityDate: '2024-12-18',
1316
})

0 commit comments

Comments
 (0)
Please sign in to comment.