context.req is missing in getStaticProps
See original GitHub issueFeature request
Is your feature request related to a problem? Please describe.
For my website I’ve built up some APIs via /pages/api
for the various data fetching needs that my application has. Sometimes I want to hit those endpoints via the client, and other times via the server, and often at build time using getStaticProps
. Unfortunately, at the moment I cannot call those API methods from the getStaticProps
method.
My initial instinct was to try:
export const getStaticProps = async () => {
const data = await fetch('/api/mydata');
}
But that gives me TypeError: Only absolute URLs are supported
. It makes sense because you must provide a hostname to fetch()
when it’s run at build time. How do I give it the hostname of whatever the current server is (localhost during development, but my production server on production)… Not sure.
Describe the solution you’d like
Ideally I could use the code above to fetch data from my API inside getStaticProps
. Or alternatively, if context.req
was exposed in getStaticProps
then I could do something like this to figure out my current hostname:
// This doesn't work.
export const getStaticProps = async (context) => {
const data = await fetch(context.req.headers.host + '/api/mydata');
}
However the above code doesn’t work because context.req
doesn’t exist when using getStaticProps
.
Describe alternatives you’ve considered
For now, I’ve had to go with something like this:
export const getStaticProps = async (context) => {
const URL = process.env.NODE_ENV === 'production' ? 'https://mydeployedsite.com' : 'http://localhost:3000';
const data = await fetch(URL + '/api/mydata');
}
Issue Analytics
- State:
- Created 3 years ago
- Comments:7 (4 by maintainers)
Top GitHub Comments
@Timer IMO this documentation leads to the same confusion; https://swr.vercel.app/docs/with-nextjs#pre-rendering
You can refactor your API endpoint into a
getData
method and just thereq/res
wrapper!