Skip to content

Instantly share code, notes, and snippets.

@d4rekanguok
Last active August 2, 2021 16:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save d4rekanguok/70175a936faa4ab708c3d5cb418d920f to your computer and use it in GitHub Desktop.
Save d4rekanguok/70175a936faa4ab708c3d5cb418d920f to your computer and use it in GitHub Desktop.
Script to fetch metadata w/ Sanity before initiating Gatsby/Next/etc.
const path = require('path')
const fs = require('fs/promises')
require('dotenv').config({
// vvvvvvvvvv replace w/ your env
path: path.resolve(process.cwd(), '.env.local')
})
const createClient = require('@sanity/client')
const client = createClient({
projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID,
dataset: process.env.NEXT_PUBLIC_SANITY_DATASET,
token: process.env.SANITY_EDITOR_TOKEN,
useCdn: process.env.NEXT_PUBLIC_ENV === 'production',
})
const fetchMeta = async () => {
console.log(`Pre-export: Fetching metadata`)
const data = await client.fetch(`*[_id == 'config_site'][0]`)
// { "url": "https://www.foo.bar", etc. }
if (!data) {
throw new Error(`No data found.`)
}
await fs.writeFile(path.resolve(process.cwd(), 'temp/data.json'), JSON.stringify(data))
console.log(`Pre-export: Successfully fetched metadata.`)
}
{
"name": "foo",
"scripts": {
"preexport": "node ./scripts/fetch-meta.js",
"export": "next build && next export",
"prebuild": "node ./scripts/fetch-meta.js",
"build": "next build"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment