'Build fails while building SSR/ISR pages with new API routes

I am getting issues while building new ISR/SSR pages with getStaticProps and getStaticPaths

Brief explanation: While creating ISR/SSR pages and adding new API route never existed before, building on Vercel fails because of building pages before building API routes (/pages/api folder)

Detailed explanation:

A. Creating next SSR page with code (/pages/item/[pid].tsx)

export async function getStaticProps(context) {
    const pid = context.params.pid;
    //newly created API route
    const res = await fetch(process.env.APIpath + '/api/getItem?pid=' + (pid));
    const data = await res.json();
    return {
        props: {item: data}
    }
}   
    
export async function getStaticPaths(context) {
    //newly created API route
    let res = await fetch(process.env.APIpath + '/api/getItemsList')
    const items = await res.json()
    
    let paths = []
    //multi-language support for the pages
    for (const item of items){
        for (const locale of context.locales){
            paths.push({params: {pid: item.url }, locale: locale})
        }
    }

    return { paths, fallback: false }
}

B. Local checks work, deploying to Vercel

C. During deploying Vercel triggers an error because trying to get data from the API route doesn't exist yet. (Vercel is deploying /pages/item/[pid].tsx first and /api/getItemsList file after). Vercel trying to get data from https://yourwebsite.com/api/getItemsList which does not exist.

Only way I am avoiding this error:

  • Creating API routes needed
  • Deploying project to Vercel
  • Creating [pid].tsx page/s and then deploy it
  • Deploying final version of code

The big issue with my approach is you are making 1 deployment you don't actually. The problems appears also while remaking the code for your API routes also.

Question: there is an way/possiblity to force Versel to deploy firstly routes and than pages?

Any help appreciated



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source