0

I am trying to deploy my nextJS project however the console keeps returning this error

Error occurred prerendering page "/". Read more: https://nextjs.org/docs/messages/prerender-error
SyntaxError: Unexpected token < in JSON at position 0
    at JSON.parse (<anonymous>)
    at parseJSONFromBytes (node:internal/deps/undici/undici:6498:19)
    at successSteps (node:internal/deps/undici/undici:6472:27)
    at node:internal/deps/undici/undici:1145:60
    at node:internal/process/task_queues:140:7
    at AsyncResource.runInAsyncScope (node:async_hooks:204:9)
    at AsyncResource.runMicrotask (node:internal/process/task_queues:137:8)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
info  - Generating static pages (4/4)

> Build error occurred
Error: Export encountered errors on following paths:
    /
    at /vercel/path0/node_modules/next/dist/export/index.js:425:19
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Span.traceAsyncFn (/vercel/path0/node_modules/next/dist/trace/trace.js:79:20)
    at async /vercel/path0/node_modules/next/dist/build/index.js:1422:21
    at async Span.traceAsyncFn (/vercel/path0/node_modules/next/dist/trace/trace.js:79:20)
    at async /vercel/path0/node_modules/next/dist/build/index.js:1280:17
    at async Span.traceAsyncFn (/vercel/path0/node_modules/next/dist/trace/trace.js:79:20)
    at async Object.build [as default] (/vercel/path0/node_modules/next/dist/build/index.js:73:29)
Error: Command "npm run build" exited with 1
BUILD_UTILS_SPAWN_1: Command "npm run build" exited with 1

When I try to build it locally on my terminal I also get a very similar error (using "npm run build")

Error: Export encountered errors on following paths:
        /
    at /Users/username/Desktop/Projects/React/Next/typescript-portfolio/node_modules/next/dist/export/index.js:425:19
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async Span.traceAsyncFn (/Users/username/Desktop/Projects/React/Next/typescript-portfolio/node_modules/next/dist/trace/trace.js:79:20)
    at async /Users/username/Desktop/Projects/React/Next/typescript-portfolio/node_modules/next/dist/build/index.js:1422:21
    at async Span.traceAsyncFn (/Users/username/Desktop/Projects/React/Next/typescript-portfolio/node_modules/next/dist/trace/trace.js:79:20)
    at async /Users/username/Desktop/Projects/React/Next/typescript-portfolio/node_modules/next/dist/build/index.js:1280:17
    at async Span.traceAsyncFn (/Users/username/Desktop/Projects/React/Next/typescript-portfolio/node_modules/next/dist/trace/trace.js:79:20)
    at async Object.build [as default] (/Users/username/Desktop/Projects/React/Next/typescript-portfolio/node_modules/next/dist/build/index.js:73:29)

I've tried looking at NextJS prerender error page but I haven't gotten any luck with the tips through there. I'm still pretty new to Next and decided to learn through it.

I am using a "getStaticProps" but I'm not sure if thats what the problem is. This is my code in index.tsx

export const getStaticProps: GetStaticProps<Props> = async () => {
  const pageInfo = await fetchPageInfo();
  const experiences = await fetchExperiences();
  const projects = await fetchProjects();
  const skills = await fetchSkills();
  const socials = await fetchSocials();

  return {
    props: {
      pageInfo,
      experiences,
      projects,
      skills,
      socials,
    },

    // Next.js will attempt to re-generate the page:
    // - When a request comes in
    // - At most once every day
    revalidate: 86400, // In seconds
  };
};

Looking at the error it doesn't say a specific page is erroring out, only "/" which leads me to believe it is a problem in my index file.

Here is an example of my code to fetch the api request in utils/fetchProject.ts

import { Project } from "@/typings";

export const fetchProjects = async () => {
  const res = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/getProject`);

  const data = await res.json();
  const projects: Project[] = data.projects;

  return projects;
};

Here is an example of my code to get the api response in pages/api/getProject.ts

import { sanityClient } from "../../sanity";
import { Project } from "../../typings";

const query = groq`
  *[_type == "project" ] {
    ...,
    technologies[]->
  }
`;

type Data = {
  projects: Project[];
};

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<Data>
) {
  const projects: Project[] = await sanityClient.fetch(query);
  res.status(200).json({ projects });
}

I've been following this youtube video as a walkthrough.

2 Answers2

1

From the error message you've shared, it seems that the main issue is related to parsing JSON data. The error message says: Unexpected token < in JSON at position 0. This error usually occurs when you're expecting a JSON response from a server and you're instead receiving HTML. The < character is a typical start character for an HTML document.

This may happen when the server sends an error page (which is often in HTML format) instead of the JSON data you're expecting.

Looking at your code, you're making fetch requests in your getStaticProps. The error likely occurs in one of these fetch requests, in particular, when you call the res.json() method to parse the JSON data.

To solve this issue, I recommend the following steps:

  1. Check if the APIs are up and running: Visit the URLs in the browser to see if they are working as expected.

  2. Check the response before parsing it: Add a check in your fetchProjects function to see if the response from the server is okay before parsing the response as JSON.

Here's how you could modify fetchProjects:

export const fetchProjects = async () => {
  const res = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/getProject`);

  // check if the response was successful
  if (!res.ok) {
    throw new Error(`Server responded with status: ${res.status}`);
  }

  const data = await res.json();
  const projects: Project[] = data.projects;

  return projects;
};

In this code, res.ok is true if the response status is in the range 200-299. If it's outside this range, it means that there was a server error, and you probably received an HTML error page instead of the expected JSON data.

Adding the check and throwing an error allows you to see what the status code was, which might provide a clue about what went wrong.

  1. Inspect your response: If the error persists, add console.log(res) or console.log(await res.text()) before the res.json() line to print out what you're receiving from the server.

  2. Check your server code: Ensure your server at /api/getProject is correctly handling errors and always responding with JSON.

You should add try/catch blocks in your server code to handle any errors that might occur and respond with an error in JSON format, rather than letting the server default to sending an HTML error page.

Here is a modified version of your handler function that includes error handling:

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<Data>
) {
  try {
    const projects: Project[] = await sanityClient.fetch(query);
    res.status(200).json({ projects });
  } catch (error) {
    console.error('Error fetching projects:', error);
    res.status(500).json({ error: 'An error occurred fetching projects' });
  }
}

With these checks, you should be able to narrow down where the error is coming from and fix it.

neo-jgrec
  • 167
  • 8
  • Thank you for the tips! I've tried them, but the same error still persists. I wanted to add that locally it doesn't return any errors. All of my API endpoints seem to be working well too. They also return a JSON file as well. Do you know how I'd be able to check the "/" route? – Thenamesoak Jun 12 '23 at 18:58
  • To check your "/" route, you should inspect your `pages/index.tsx` file (or `pages/index.js` if you're not using TypeScript). Check that all data fetching is handled correctly, and that there are no issues with the data that is being passed to your components. – neo-jgrec Jun 13 '23 at 20:34
0

Fixed it by deploying a static version of the site first. Then after deploying, inputting the url into the environment variables in the vercel project. I suspect the error was happening in the utils/fetchProject.ts (and other api response helpers) because it couldn't find the link to actually fetch the api response from the url