1

So I'm trying to deploy my Next JS application using Vercel with GIT repository, I started using getStaticProps and getStaticPaths fetching data from a local API, on development it works because the fetching URL is http://localhost:3000/... and on production it changes to my vercel domain but with vercel when you deploy your website it creates a preview domain with the build before assigning the production domain and I think that's what is causing the problem.

config.js

const dev = process.env.NODE_ENV !== 'production';

export const server = dev ? 'http://localhost:3000' : 'domain.com';

[project].js

export async function getStaticProps(content){
  const res = await fetch(`${server}/api/${content.params.project}`);
  const data = await res.json();

  return {
    props: {
      data,
    },
  }
}

export async function getStaticPaths(){
  const res = await fetch(`${server}/api/paths`);
  const data = await res.json();

  return {
    paths: data.paths.map((p) => {
      return {params: {project: p}}
    }),
    fallback: false,
  }
}

path.js (api for paths)

export default function handler(req, res) {
    res.status(200).json({ 
        paths: ["aibloc"]
     })
}

And there is a similar API as path.js where is just an object with data.

The build error: Collecting page data ..FetchError: invalid json response body at domain.com/paths reason: Unexpected token < in JSON at position 0

Useful information: When deploying to Vercel with Git:

  1. Commit to branch
  2. Vercel makes a "preview domain" for that specific commit
  3. Vercel runs npm run build, if there are no errors the build will be assigned to the production domain, if there are errors, in my situation the error is the one from above, the deploying fails. My thoughts are that is failing because at first the domain is that random generated "preview domain", if Vercel deployed first to the production domain I think there will be no issue.

If anyone knows how to fix this I will be glad, an idea that I thought of is making a public API with the data I need so it will not depend on what domain I have.

Note: I need the data as JSON, not string.

Tudor Alexandru
  • 277
  • 2
  • 13
  • 2
    Does this answer your question: [Fetch error when building Next.js static website in production](https://stackoverflow.com/a/66206394/1870780)? You should not call an internal API route inside `getStaticProps`/`getStaticPaths`. You can use your API logic directly. – juliomalves Feb 20 '22 at 18:47
  • 2
    Oh, yeah, I don't really need an internal API for my project in this case, how did I not thought about that, thanks a lot. – Tudor Alexandru Feb 20 '22 at 19:03

0 Answers0