Content in server routes
Can I use the content plugin in server routes? Specifically, I would like to expose content collection as a JSON API.
5 Replies
Hi @tpluscode. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
Yes. Nuxt Content’s query utilities are available in Nitro, so you can use them inside server routes to expose collections as JSON.
Examples:
- Query a page by path:
(Uses server-side variant of queryCollection where event is passed first) (Server usage: queryCollection).
- Build navigation JSON:
(Server usage: queryCollectionNavigation).
- Return searchable sections:
(Server usage: queryCollectionSearchSections).
Notes:
- Create server/tsconfig.json extending ../.nuxt/tsconfig.server.json to avoid type errors (applies to these server utilities) (queryCollection server usage).
- Server routes live under server/api and are powered by Nitro/h3; handlers can directly return JSON (Server directory). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
- Server routes live under server/api and are powered by Nitro/h3; handlers can directly return JSON (Server directory). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
<@555413648382623754> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
thanks @kapa.ai. is it also possible to get raw markdown?
Let me check the knowledge base for you again. One moment! :books:
----------------------
Yes. Define a rawbody field in your collection schema, and Nuxt Content will fill it with the file’s raw Markdown. Then you can query it (including from server routes) and return it as JSON.
- Add to content.config.ts:
(Raw Content).
- Server route example:
(Use server variant of queryCollection by passing event first) (Server usage: queryCollection).
Tip: If you don’t want a specific file’s raw content shipped, set rawbody: '' in its frontmatter (Raw Content).
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------
<@555413648382623754> Kapa.ai is still learning and improving, please let me know how I did by reacting below.