Skip to content

Commit 7aba38f

Browse files
committed
fix: useBotDetection() empty when ran client side only
1 parent c71a226 commit 7aba38f

File tree

4 files changed

+59
-0
lines changed

4 files changed

+59
-0
lines changed

src/runtime/app/composables/useBotDetection.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,11 @@ export function useBotDetection(options: UseBotDetectionOptions = {}): UseBotDet
1616
}
1717
}
1818

19+
// SPA fallback: use navigator.userAgent
20+
if (import.meta.client) {
21+
return getBotDetectionFromHeaders({ 'user-agent': navigator.userAgent })
22+
}
23+
1924
return null
2025
})
2126

test/e2e/spa-bot-detection.test.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import { createResolver } from '@nuxt/kit'
2+
import { createPage, setup } from '@nuxt/test-utils'
3+
import { describe, expect, it } from 'vitest'
4+
5+
const { resolve } = createResolver(import.meta.url)
6+
7+
process.env.NODE_ENV = 'production'
8+
9+
await setup({
10+
rootDir: resolve('../fixtures/spa'),
11+
build: true,
12+
})
13+
14+
describe('bot detection in SPA mode', () => {
15+
it('detects bot via navigator.userAgent fallback in SPA', async () => {
16+
const page = await createPage('/bot-detection')
17+
18+
// No need to wait - userAgent detection is synchronous on init
19+
const isBotText = await page.textContent('[data-test-id="is-bot"]')
20+
const botNameText = await page.textContent('[data-test-id="bot-name"]')
21+
22+
// HeadlessChrome user-agent detected via navigator.userAgent fallback
23+
expect(isBotText).toContain('is bot: true')
24+
expect(botNameText).toContain('puppeteer')
25+
}, 15_000)
26+
})

test/fixtures/spa/nuxt.config.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import NuxtRobots from '../../../src/module'
2+
3+
export default defineNuxtConfig({
4+
modules: [NuxtRobots],
5+
ssr: false,
6+
site: {
7+
url: 'https://nuxtseo.com',
8+
},
9+
})
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<script lang="ts" setup>
2+
import { useBotDetection } from '#robots/app/composables/useBotDetection'
3+
4+
const { isBot, botName, trusted } = useBotDetection()
5+
</script>
6+
7+
<template>
8+
<div>
9+
<div data-test-id="is-bot">
10+
is bot: {{ isBot }}
11+
</div>
12+
<div data-test-id="bot-name">
13+
bot name: {{ botName }}
14+
</div>
15+
<div data-test-id="trusted">
16+
trusted: {{ trusted }}
17+
</div>
18+
</div>
19+
</template>

0 commit comments

Comments
 (0)