I’m using next.js to build static HTML webpages.
One of my webpages needs data from a third-party API, which I’d like to fetch at build time and bake into the resulting HTML.
I don’t want this call to ever happen on the client, because:
- CORS prevents the request from succeeding anyway
- I would have to expose an API key on the client (no thank you)
I thought getInitialProps
was the answer, because the fetched data is indeed baked in during the build/export process, but when I navigate away from the page and return from it, getInitialProps
gets triggered on the client, breaking everything.
My current code in getInitialProps is something like:
static async getInitialProps(){
// Get Behance posts
const behanceEndpoint = `https://www.behance.net/v2/users/${process.env.BEHANCE_USERNAME}/projects?api_key=${process.env.BEHANCE_API_KEY}`
const behanceRes = await fetch(behanceEndpoint)
let behancePosts = await behanceRes.json()
// Return only the required number of posts
return {
behancePosts: behancePosts
}
}
有关如何处理此问题的任何建议或最佳做法?我知道Gatsby.js是开箱即用的。
一种可能是,如果您只想在服务器上执行一次以检查req参数是否在getInitialProps中:(文档)
req
-HTTP请求对象(仅服务器)。一种肮脏的方法:
希望这会有所帮助。