I have been following a tutorial on youtube to build a twitter-clone website. However, when trying to fetch tweets from Sanity I am getting this error. I even git cloned the repo of the person that made the tutorial and I'm still getting the same error. This leads me to believe it is an issue with my VS code and not the code itself, if anyone has any suggestions that would be great thank you.
// fetchTweets.ts
export const fetchTweets = async () => {
const res = await fetch(`http://localhost:3001/api/getTweets`)
const data = await res?.json()
const tweets: Tweet[] = data.tweets
console.log('fetching', tweets)
return tweets
}
// index.tsx
export const getServerSideProps: GetServerSideProps = async (context) => {
const tweets: Tweet[] = await fetchTweets()
return {
props: {
tweets,
},
}
}
That error is typically caused by trying to render HTML as JSON—and particularly, when JSON is expected but instead an API returns an error page. Is your server definitely running on port 3001? Fetching from a non-existent server is likely consistent with this error.
Related
I have a project built on NextJs for the frontend and strapi cms for the backend. I have a collection type called blogs to publish blogs on my website. I have added the blog with all the necessary fields but the blog shows: TypeError: Cannot read properties of undefined type. There is no problem with the API as I am getting the complete object for that blog. For some reason, it is not fetching the blog. I have added many blogs earlier and those blogs are working but now when I am trying to add a new blog I am getting this error and then after like 30 minutes I am getting a 404 page.
Here is the blogs/[slug].js file:
import { useEffect } from "react";
import { fetchAPI, updateViews } from "../../utils/api";
import InsightsSinglePageLayout from "#/components/elements/insights-single-layout";
const Blog = ({ blog, similarBlogs }) => {
useEffect(() => {
// Update the views count
fetchAPI(`/blogs?slug=${blog.slug}`)
.then((latestBlog) => {
updateViews("blogs", latestBlog[0]);
});
}, []);
return (
<section>
<InsightsSinglePageLayout insightsData = {blog}
similarInsight = {similarBlogs}
type={blog.type.title.toLowerCase()}/>
</section>
)
};
export const getStaticProps = async (context) => {
const blog = await fetchAPI(`/blogs?slug=${context.params.slug}`)
const similarBlogs = await fetchAPI(`/solutions?title=${blog[0].solution?.title}`)
return {
props: {
blog : blog[0],
similarBlogs : similarBlogs[0] ? similarBlogs[0].blogs.filter(data => data.id != blog[0].id).slice(0,5) : [] ,
},
};
};
export const getStaticPaths = async () => {
const blogs = await fetchAPI('/blogs')
const slugs = blogs.map(blog => blog.slug)
const paths = slugs.map(slug => ( {params : { slug : slug.toString() }} ))
return{
paths,
fallback:false
}
};
export default Blog;
I have restarted the staging server hoping to get a better error and try to debug it but I am getting the same error.
thank you for your responses. I have got the solution for it. This issue was causing because of getStaticProps.
The number of blogs in my backend crossed 100 blogs and getstaticprops was not able to fetch the recent blogs for me.
For it to work I had to simply make fallback = true, though this is not a correct solution for it as it will cause some performance issues, I will have to write my query in such a way that it fetches the blogs in descending order, so I will get my recent blogs without any error.
I have a bug, i'm trying to make his tutorial for twitter clone in nextjs+tailwindcss+typescript
https://www.youtube.com/watch?v=rCselwxbUgA&t=1357s&ab_channel=SonnySangha
1:42:05 / 3:17:52
I did exactly the same but i feel like my IDE or my nextJS version is making things different
import { Tweet } from "../typings"
export const fetchTweets = async () => {
const res = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/getTweets/`)
const data = await res.json();
const tweets: Tweet[] = data.tweets;
return tweets
}
FetchError: request to https://localhost:3000/api/getTweets/ failed,
reason: write EPROTO 140020696905664:error:1408F10B:SSL
routines:ssl3_get_record:wrong version
number:../deps/openssl/openssl/ssl/record/ssl3_record.c:332:
This error happened while generating the page. Any console logs >will be displayed in the terminal window.
import { Tweet } from "../typings"
export const fetchTweets = async () => {
if(global.window) {
const res = await
fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/getTweets/`)
const data = await res.json();
const tweets: Tweet[] = data.tweets;
return tweets
}
}
Server Error Error: Error serializing .tweets returned from
getServerSideProps in "/". Reason: undefined cannot be serialized
as JSON. Please use null or omit this value.
If someone can help me <3 thanks
FIXED :
.env.local
i writed
NEXT_PUBLIC_BASE_URL=https://localhost:3000/
change https:// by http:// and yarn run dev again
NEXT_PUBLIC_BASE_URL=http://localhost:3000/
This question already has answers here:
Internal API fetch with getServerSideProps? (Next.js)
(3 answers)
Closed 8 months ago.
I'm developing a website for a college class, followed a tutorial on YouTube since I have no real experience with this level of coding. The site "works" locally...when I execute it, at first the screen is just white, but if I refresh the page it comes up, and everything functions (it's a pizza website, the products and ordering and everything works locally). But, when I inspect while the screen is white, I see that I'm getting an internal server error:
I believe the issue is somewhere in my api/products/index file, but I'm not sure
Here is the code for that file:
import dbConnect from "../../../utilities/mongo"
import Product from "../../../models/Product"
export default async function handler(req, res) {
const {method, cookies} = req;
const token = cookies.token
dbConnect()
if(method === "GET"){
try {
const product = await Product.find();
res.status(200).json(product);
} catch (err) {
res.status(500).json(err)
}
}
if(method === "POST"){
if(!token || token !== process.env.TOKEN){
return res.status(401).json("Not Authorized")
}
try{
const product = await Product.create(req.body);
res.status(201).json(product)
}catch(err){
res.status(500).json(err);
}
}
}
Here is a link to my github with all code:
https://github.com/InvisibleH3R0/mellowyellowpizzaria
Any assistance on what is wrong would be highly appreciated!
EDIT:
Here are screenshots of my terminal:
Looking at your repo, I can see you are calling your API endpoint inside your getServerSideProps function in your index.js page. You should be writing your DB logic inside getServerSideProps directly since calling your endpoint in this function is considered inefficient and could give you some problems. You can read more about this here.
Try this:
export const getServerSideProps = async (ctx) => {
const myCookie = ctx.req?.cookies || "";
let admin = false;
if (myCookie.token === process.env.TOKEN) {
admin = true;
}
await dbConnect();
const res = await Product.find();
return {
props: {
pizzaList: JSON.parse(JSON.stringify(res)),
admin,
},
};
};
I'm learning Next.js and run into a problem. I was following a tutorial on youtube to make a google clone with the next.js + tailwind. So the problem is when I add export async function getServerSideProps() I get an error invalid JSON response body. Reason: Unexpected token < in JSON at position 0
Seems I am doing everything exactly as the instructor but he doesn't get any error.
export async function getServerSideProps(context) {
const useDummyData = false;
const data = await fetch(
`https://developers.google.com/custom-search/v1?
key=${API_KEY}&cx=${CONTEXT_KEY}&q=${context.query.term}`
).then((response) => response.json());
return {
props: {
results: data,
},
};
}
I am trying to create dynamic pages that show individual book details (.i.e. title/author) on a separate page based on a query string of the "id" for each book. In a previous question I asked, answers from users were very helpful and I have a much better understanding of how to use getStaticPaths and getStaticProps correctly. However, I am not quite there in my code for how to do this.
Here is the basic setup and context.
I am running NextJS 9.4 and would like to use a API endpoint instead of querying the database directly.
The book data is being pulled from a MongoDB Atlas Database and uses Mongoose
Documents in the MongoDB have a "_id" as a unique ID.
I have tried to incorporate and learn from existing Github examples and NextJS documentation but I still get the following error.
Error: A required parameter (id) was not provided as a string in getStaticPaths for /book/[id]
Here is the code I have so far. I have tried to keep the code as clean as possible for now.
export default function Book({ book }) {
return (
<article>
<h1>Book Details Page</h1>
<p>{book.title}</p>
<p>{book.author}</p>
</article>
)
}
export async function getStaticPaths() {
const url = `${baseUrl}/api/books/books`
const response = await axios.get(url);
const books = response.data
const paths = books.map((book) => ({
params: { id: book.id },
}))
return { paths, fallback: false }
}
export async function getStaticProps({ params }) {
const url = `${baseUrl}/api/books/books/${params.id}`
const res = await axios.get(url)
const book = await res.json()
return { props: { book }}
}
The API endpoint looks like this:
import Book from '../../../models/Book';
import dbConnect from '../../../utils/dbConnect';
// conects to the database
dbConnect();
// This gets all the book from the database
export default async (req, res) => {
const books = await Book.find()
res.status(200).json(books)
}
Any support or feedback would be greatly appreciated. Once I get this working, I can hopefully be able to understand and help assist others in creating dynamic routes with NextJs. Thank you.
You can't make calls to Next.js API routes inside getStaticProps or getStaticPaths. These functions are executed at build time, so there is no server is running to handle requests. You need to make request to DB directly.
If you want to keep it clean you could create a helper module like allBooksIds() and keep DB query in a separate file.
See the same issue - API call in NextJS getStaticProps
Simply add toString() method in getStaticPaths because the book id is of type ObjectID("ID") if you do params: { id: book._id.toString() } it will convert ObjectID("ID") to type string which is accepted by getStaticPaths().The complete code for the nextjs part is below also update your API route as follows :-
The upper one is the API route the bellow one is Nextjs Page
import Book from '../../../models/Book';
import dbConnect from '../../../utils/dbConnect';
// conects to the database
dbConnect();
// This gets all the book from the database
export default async (req, res) => {
const books = await Book.find({})
res.status(200).json(books)
}
export default function Book({ book }) {
return (
<article>
<h1>Book Details Page</h1>
<p>{book.title}</p>
<p>{book.author}</p>
</article>
)
}
export async function getStaticPaths() {
const url = `${baseUrl}/api/books/books`
const response = await axios.get(url);
const books = response.data
const paths = books.map((book) => ({
params: { id: book._id.toString() },
}))
return { paths, fallback: false }
}
export async function getStaticProps({ params }) {
const url = `${baseUrl}/api/books/books/${params.id}`
const res = await axios.get(url)
const book = await res.json()
return { props: { book }}
}
Hope this is helpful