Advanced
Hooks
Modify your content using Nuxt build time hooks
content:file:beforeParse
This hook is called before the content is parsed.
It can be used to modify the raw content from a file before it is transformed
or modify the transform options.
export default defineNuxtConfig({
hooks: {
'content:file:beforeParse'(ctx) {
// ...
}
}
})
content:file:afterParse
This hook is called after the content is parsed and before it is saved to the database.
export default defineNuxtConfig({
hooks: {
'content:file:afterParse'(ctx) {
// ...
}
}
})
Example Usage
nuxt.config.ts
export default defineNuxtConfig({
// ...
hooks: {
'content:file:beforeParse'(ctx) {
const { file } = ctx;
if (file.id.endsWith(".md")) {
file.body = file.body.replace(/react/gi, "Vue");
}
},
'content:file:afterParse'(ctx) {
const { file, content } = ctx;
const wordsPerMinute = 180;
const text = typeof file.body === 'string' ? file.body : '';
const wordCount = text.split(/\s+/).length;
content.readingTime = Math.ceil(wordCount / wordsPerMinute);
}
}
})
In the
content:file:afterParse hook, we added a custom property to our content object. To be able to access that property within our pages using queryCollection(), we first need to define it in our content schema.content.config.ts
export default defineContentConfig({
collections: {
content: defineCollection({
type: 'page',
source: '**/*.md',
schema: z.object({
readingTime: z.number().optional()
})
})
}
});