11/20/2024
I am trying to add a new API route and use it in the same deployment, the new API route is what I am using to fetch the posts from this headless CMS system. Basically, fetching the data on the server side, build the page, and then send the html to the client side to load. Everything worked fine locally in the dev mode. I do need to add a new baseUrl environment variable because the API call requires an absolute URL. Added that, define the absolute URL as http://localhost:3000 and everything works. I didn’t test the build script, but it’ll build fine since http://localhost:3000 does have the new route.
Fast forward, codes are pushed, build is triggered on Netlify and then the Build Error showed up. The error code is saying unexpected character in API response. I am baffled. What is going on here? Why would it not return the correct JSON data structure. Debugging locally yields nothing, everything seems to be working fine.
Time to ask the internet for help. I found some articles that has the same error code as mine, but none of the solutions worked. Internet has failed me this time.
At this point, I am at a lost, what else can I do? Then I remembered that the local build environment is different than the production build environment. The baseUrl env variable has different values. To test it, I should make sure I am mimic the production build environment as much as possible. And that’s when I found out that the new API route is returning a 404 page and of course it is not a valid JSON structure.
It makes sense, I haven’t been able to deploy my code yet, so the route is not available in the production at https://thedepartedonline/api/cms. However, what I don’t understand is why it worked locally using http://localhost:3000. Is it because the code is already there? I am sure people must have running into this kind of issue before on Vercel, then how come Netlify is not able to fix the build issue?
A few days later, I came across this article about OpenNext. https://thenewstack.io/opennext-gets-closer-to-making-next-js-truly-portable/. What I got from the article is that Next.js is very opinionated about how user deploy apps written using their framework and Next.js knows exactly what to do but people outside doesn’t. OpenNext is aim to solve that issue so that the framework is just a framework and people can deploy it however they want. Anyway, that’s not the point of this article.
To fix this issue, I will have to deploy the API route first, and then deploy the server side component that uses it. It worked and my blog is pulling content from a headless CMS. Everything is good.