Home > database >  How can I fetch data from the host URL in getStaticPaths() in Next.js serverless function?
How can I fetch data from the host URL in getStaticPaths() in Next.js serverless function?

Time:02-03

I have a Next.js app that uses a serverless function to fetch data from its host. The host URL is stored in a .env file and is set to http://localhost:3000/api/data for dev and https://productionurl.com/api/data for production.

However, for testing purposes, I have hosted the app on Vercel, and the testing URL will be randomly generated, such as https://randomvercelurl_abcd1234.com/api/data.

I can use ctx or req to get the host URL in the getServerSideProps method, as shown in the example code below:

export async function getServerSideProps({query, req}){
    const API_URL = req.protocol   req.headers.host   "/api/data"
    const res = await axios.get(API_URL)
 ...
}

The problem arises in the getStaticPaths method, where I need to fetch data to generate dynamic routes. I don't have any way to get the host URL in this method, as demonstrated in the following example code:

export async function getStaticPaths() {
    const host = ???
    const res = await fetch(`${host}/api/data`)
    const posts = await res.json()

    const paths = posts.map((post) => ({
        params: { id: post.id },
    }))

    return { paths, fallback: false }
}

How can I access the host URL in the getStaticPaths method to fetch data?

CodePudding user response:

You cannot get a ctx with host like in getServerSideProps because getStaticPaths runs at build time. So the URL from which you want to fetch data should be fully known, either in the code or through an environment variable.

getStaticPaths will only run during build in production, it will not be called during runtime. You can validate code written inside getStaticPaths is removed from the client-side bundle with this tool.

The solution is to add the randomly generated URL into your environment variable on Vercel, or wherever you host your app. You may also want to read when should I use getStaticPaths.

  • Related