Send KQL query for nuxt.config.ts
?
#14
-
I'm trying to get a list of draft pages from Kirby during the static generation stage of my site, so that I can pass it to I need to be able to fetch the draft pages with nuxt-kql directly from within
This gives me the error
How can I import and use |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Great question! tl;dr: You can't. However, you can create a custom module that fetches a query and adds routes to Nitro prerender queue. Save the following module as import { ofetch } from 'ofetch'
import { defineNuxtModule, useLogger } from 'nuxt/kit'
import type { KirbyQueryResponse, KirbyQuerySchema } from '#nuxt-kql'
export default defineNuxtModule({
meta: {
name: 'prerender:drafts',
},
async setup(options, nuxt) {
const logger = useLogger('prerender')
const $kirby = ofetch.create({
baseURL: nuxt.options.kql?.url || process.env.KIRBY_BASE_URL,
method: 'POST',
headers: {
Authorization: `Bearer ${nuxt.options.kql?.token || process.env.KIRBY_API_TOKEN}`,
},
})
const query: KirbyQuerySchema = {
query: 'site.children',
select: ['id'],
}
const response = await $kirby<KirbyQueryResponse>('api/kql', {
body: query,
})
if (!response.result) return
nuxt.hook('nitro:config', (config) => {
config.prerender ||= {}
config.prerender.routes ||= []
config.prerender.routes.push(...response.result.map((page: any) => page.id))
})
logger.success(
`Added ${response.result.length} draft pages to prerender queue`,
)
},
}) Hope that helps. 🙌 |
Beta Was this translation helpful? Give feedback.
Great question!
tl;dr: You can't.
useKql
is only available during a component's lifecycle; during thesetup()
phase of a component. Just like Nuxt'suseFetch
,useNuxtApp
and other composables. Also,useKql
needs the Nuxt instance to retrieve values like the Kirby backend URL from the runtime config.However, you can create a custom module that fetches a query and adds routes to Nitro prerender queue.
Save the following module as
modules/prerender.ts
. Nuxt will auto-import the module. I assume you use the Kirby Headless plugin with the bearer-token authentication? If not, you have to adapt the authentication method for the$kirby
fetch instance.