next.js SyntaxError: Unexpected token < in JSON at position 0 - javascript

API is working, I can use this API on other pages. but this page can't, I don't know where's wrong??
code:
export async function getStaticPaths() {
const response = await fetch("http://localhost:8080/students");
const data = await response.json();
const paths = data.map((d) => {
return {
params: {
id: d._id.toString(),
},
};
});
return {
paths,
fallback: false,
};
}
export async function getStaticProps({ params }) {
const response = await fetch(`http://localhost:8080/students/${params.id}`);
const data = await response.json();
return {
props: {
data,
S,
},
};
}
export default function StudentProfile({ data }) {
return (
<div>
<h1>{data.name}</h1>
<h1>{data.age}</h1>
<h1>{data.id}</h1>
</div>
);
}
error message:
Server Error
SyntaxError: Unexpected token < in JSON at position 0
This error happened while generating the page. Any console logs will be displayed in the terminal window.
pages/profile/[id].js (26:15) # async getStaticProps
24 | export async function getStaticProps({ params }) {
25 | const response = await fetch(http://localhost:8080/students/${params.id});
26 | const data = await response.json();
| ^
27 | return {
28 | props: {
29 | data,
I sure about the API is successfully connected.
This code can run successfully and display data:
export async function getStaticProps() {
const respone = await fetch("http://localhost:8080/students");
const data = await respone.json();
return {
props: {
data,
},
};
}
export default function StaticGenerationPage({ data }) {
return (
<div>
{data.map((d) => {
return <h1>{d.name + " " + d._id}</h1>;
})}
</div>
);
}
Are there any other potential causes of error?

Unexpected token < in JSON at position 0 means the JSON returned by the API is not valid
Also, getStaticProps does not have access to the incoming request (such as query parameters or HTTP headers) see getStaticProps docs.

Related

next.js getStaticProps Serialize issue

I'm using next.js for a project where axios fetch in getStaticProps doesnot seem to work even though the URL is serialised in configuration.I tried serializing again by passing the response to JSON.parse but still cant find a solution.
import axios from "axios";
import Qs from "qs";
My axios config code below:
const axiosTmdbApi = axios.create({
baseURL: "https://api.themoviedb.org/3",
headers: { "content-Type": "application/json/" },
paramsSerializer: {
serialize: (params) =>
Qs.stringify({ ...params, api_key: apiKey }, { arrayFormat: "brackets" }),
},
});```
**My category which is passed as a parameter to invoke getTvList or getMovieList data below:**
import axiosTmdbApi from "./axiosTmdbApi";
export const category = {
movie: "movie",
tv: "tv",
};
export const type = {
top_rated: "top_rated",
popular: "popular",
};
const tmdbApi = {
getTvList: (tvType, params) => {
const url = "tv/" + type[tvType];
return axiosTmdbApi.get(url, params);
},
getMovielist: (movieType, params) => {
const url = "movie/" + type[movieType];
return axiosTmdbApi.get(url, params);
},
};
export default tmdbApi;```
Using getStaticProps to fetch my API
import tmdbApi from "../../api/tmdbApi";
import { type, category } from "../../api/tmdbApi";
const Movies = ({ data }) => {
console.log(data);
return (
<>
<h1 className="bg-success">Movies</h1>
</>
);
};
export default Movies;
export async function getStaticProps() {
let params = {};
let response;
response = await tmdbApi.getMovielist(type.popular, {
params,
});
const data = JSON.parse(JSON.stringify(response));
return {
props: { data },
};
}```
**Error :index.js?46cb:602 Uncaught TypeError: Converting circular structure to JSON
--> starting at object with constructor 'ClientRequest'
| property 'socket' -> object with constructor 'TLSSocket'
--- property '_httpMessage' closes the circle **
Try adding console.log and see what values are being handled at each stage. Instead of const data = JSON.parse(JSON.stringify(response)), you should be doing const data = response.data.
and change return statement to
return {
props: { data: data || [] },
};

Getting stray fetch request to JSON files while running getStaticProps/ getStaticPaths

My page is working correctly, but When I look in the console I'm getting 5, 404 errors on fetch request. not sure where this is coming from..
I only get these 404s in production. Nothing in development.
Page File Structure
live site: https://real-fake-store.vercel.app/
github repo: https://github.com/Haviles04/real-fake-store
Here is the code I think it's coming from.
export async function getStaticPaths() {
const { products } = await import("../../../data/products/allData.json");
return {
paths: products.map((item) => {
const productId = item.id;
const productName = item.title
.toLowerCase()
.replace(/\s/g, "")
.toString();
const catName = item.category.name.toLowerCase().toString();
return {
params: {
catName,
productId: `${productId}=${productName}`,
},
};
}),
fallback:false,
};
}
export async function getStaticProps({ params }) {
const { categoryItems } = await import(
`../../../data/products/${params.catName}Data.json`
);
const pageProduct = categoryItems.find(
(item) => item.id === parseInt(params.productId)
);
return {
props: {
pageProduct,
},
};
}
and I'm getting this in the console
This was fixed by adding passHref to the LINK component that was directing to the page.

NextJS project not generating static pages on build. Fails with timeout error

I am working on NextJS project with TypeScript. For some strange reasons it is failing to compile either for development or production. It fails with timeout error as shown in the following error trace
> Build error occurred
Error: Static page generation for /posts/introducing-hapana-v1 is still timing out after 3 attempts. See more info here https://nextjs.org/docs/messages/static-page-generation-timeout
at onRestart (/app/node_modules/next/dist/build/index.js:487:31)
at Worker.exportPage (/app/node_modules/next/dist/lib/worker.js:49:40)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async /app/node_modules/next/dist/export/index.js:412:32
at async Span.traceAsyncFn (/app/node_modules/next/dist/trace/trace.js:74:20)
at async Promise.all (index 3)
at async /app/node_modules/next/dist/export/index.js:407:9
at async Span.traceAsyncFn (/app/node_modules/next/dist/trace/trace.js:74:20)
at async /app/node_modules/next/dist/build/index.js:987:17
This following is the dynamic page [slug].tsx
const PostDetailsPage: React.FC<PostDetailsProps> = (props) => {
// console.log(post);
const { post, posts } = props;
if (!post || !posts) return <Loader />;
return <Post post={post} posts={posts} />;
};
export async function getStaticProps(context: any) {
const slug = context.params.slug;
const { data: postData } = await getPost(slug);
const { data: posts }: DataInterface = await getBlogPosts(1);
return {
props: {
post: postData,
posts: posts.results,
},
};
}
export async function getStaticPaths() {
const { data: posts }: DataInterface = await getBlogPosts(1);
const slugs = posts.results.map((p) => ({ params: { slug: p.slug } }));
return {
paths: slugs,
fallback: true,
};
}
export default PostDetailsPage;
export const getBlogPosts = (page: number) => {
return http.get(apiEndpoint + `posts/?cats=blog&page=${page}`);
};
export const getPost = (postSlug: string) => {
return http.get(postUrl("posts/" + postSlug + "/"));
};
Please note http is just an axios interceptor function
Could anyone help me resolve this issue?

How to redirect to 404 page if data is invalid in getStaticProps?

In my Next.js app I will fetch Author's all article. I'm getting author Id from request params. I pre-generated some of my authors with getStaticPaths.
In getStaticPaths I set fallback to true. If author Id is provided correctly it works fine but if you write wrong text to request params it returns an error.
[authorId].js page
export async function getStaticPaths() {
const fetchAuthors = await axios.get(
"http://localhost:3000/api/articles/authors"
);
return {
paths: [
...fetchAuthors.data.map((item) => {
return { params: { authorId: item.author._id } };
}),
],
fallback: true,
};
}
export async function getStaticProps(context) {
const {
params: { authorId },
} = context;
const fetchArticles = await axios.get(
`http://localhost:3000/api/articles/${authorId}/1`
);
const fetchAuthor = await axios.get(
`http://localhost:3000/api/articles/authors/${authorId}`
);
return {
props: {
Articles: fetchArticles.data,
Author: fetchAuthor.data,
},
revalidate: 60,
};
}
const AuthorProfilePage = ({ Articles, Author }) => {
return <>
<div className={styles.authorImgContainerBig}>
<Image
src={Author.author.photo.url}
className={styles.authorImgBig}
layout="fill"
objectFit="cover"
quality={100}
alt=""
/>
</div>
</>
}
If Author Id exists in database it works fine. But if you pass for example 'asljnsaf' as Author Id it returns error.
Error message
Server Error
TypeError: Cannot read property 'author' of undefined
<Image
55 | src={
> 56 | Author.author.photo.url ||
| ^
57 | "https://res.cloudinary.com/bizimsehir-gazetesi/image/upload/v1624802793/blank-profile-picture-973460_1280_duksmn.png"
58 | }
59 | className={styles.authorImgBig}
How can I redirect to 404 page if author does not exist?
You can return a 404 page directly from the getStaticProps function if the author data doesn't exist.
export async function getStaticProps(context) {
const { params: { authorId } } = context;
const fetchArticles = await axios.get(`http://localhost:3000/api/articles/${authorId}/1`);
const fetchAuthor = await axios.get(`http://localhost:3000/api/articles/authors/${authorId}`);
// Handle `undefined` author data
if (!fetchAuthor.data) {
return {
notFound: true
};
}
return {
props: {
Articles: fetchArticles.data,
Author: fetchAuthor.data
},
revalidate: 60
};
}

undefined getStaticProps causes build failure on page that doesn't exist

I'm fetching page data from a cms, so far I have only one page in pages/posts.
pages/posts/[slug].js
import { getAllPostsWithSlug, getPostAndMorePosts } from '../../lib/api';
export default function Post({ post }) {
const router = useRouter();
const { slug } = router.query;
return (
<div>
<p>
title: {typeof post == 'undefined' ? 'no post' : post.title}
</p>
</div>
);
}
export async function getStaticProps({ params, preview = null }) {
const data = await getPostAndMorePosts(params.slug, preview);
const content = await markdownToHtml(data?.posts[0]?.content || '');
return {
props: {
preview,
post: {
...data?.posts[0],
content,
},
morePosts: data?.morePosts,
},
};
}
export async function getStaticPaths() {
const allPosts = await getAllPostsWithSlug();
return {
paths: allPosts?.map((post) => `/posts/${post.slug}`) || [],
fallback: true,
};
}
That will correctly display post.title, but if I access the property directly with
<p>title: {post.title}</p>
I get the build error:
post undefined
Is next trying to build a page out of the template with no data? When the build succeeds I only have one route in /posts.

Categories

Resources