Using Sanity GROQ queries in nuxt.config.js for dynamic route generation
I can definitely help you get this working with the proper @sanity/client and GROQ queries instead of using axios!
The solution is to use @sanity/client in your nuxt.config.js file to execute your GROQ queries. Here's how to do it:
First, make sure you have @sanity/client installed:
npm install @sanity/clientThen in your nuxt.config.js, import and configure the Sanity client at the top of the file:
const sanityClient = require('@sanity/client')
const client = sanityClient({
projectId: 'YOUR_PROJECT_ID',
dataset: 'YOUR_DATASET', // usually 'production'
apiVersion: '2024-01-01', // use current date
useCdn: false, // `false` if you want to ensure fresh data for build
})
const dynamicRoutes = async () => {
const query = `*[_type in ["aaa", "bbb"]]{
_type,
"slug": slug.current
}`
const results = await client.fetch(query)
return results.map((el) =>
el._type === 'bbb'
? `/detail-bbb/${el.slug}/`
: `/detail-aaa/${el.slug}/`
)
}
export default {
// ... other config
generate: {
routes: dynamicRoutes
}
}Key points:
Use
require()notimport- Sincenuxt.config.jsruns in a Node context during build time, you need to use CommonJSrequire()syntax rather than ES6 importsSet
useCdn: false- For build-time queries, you want fresh data directly from the API, not cached CDN dataUse async/await - The
client.fetch()method returns a Promise, so make yourdynamicRoutesfunction asyncapiVersion - Always specify an API version. You can use today's date or a fixed date for consistency
If you're using Nuxt 3, the config file might be nuxt.config.ts and you can use ES6 imports:
import sanityClient from '@sanity/client'
const client = sanityClient({
projectId: 'YOUR_PROJECT_ID',
dataset: 'production',
apiVersion: '2024-01-01',
useCdn: false,
})
export default defineNuxtConfig({
// ... other config
hooks: {
async 'nitro:config'(nitroConfig) {
const query = `*[_type in ["aaa", "bbb"]]{ _type, "slug": slug.current }`
const results = await client.fetch(query)
const routes = results.map((el) =>
el._type === 'bbb' ? `/detail-bbb/${el.slug}/` : `/detail-aaa/${el.slug}/`
)
nitroConfig.prerender.routes = routes
}
}
})This gives you the proper Sanity client integration with full GROQ query support, just like you're using in your components! The Nuxt.js quickstart guide has more details on setting up Sanity with Nuxt.
Show original thread13 replies
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.