Next Js project getServerSideProps - reactjs

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,
},
};
}

Related

Axios API call returns a 404 on page render, but still returns api objects in terminal

I am using axios to make an api call to an api found on Apihub for a next JS app.
here is the code for the function to make the call to provide a list of property JSON objects.
export const baseUrl = "https://zillow56.p.rapidapi.com"
export const fetchApiListsingsCustom = async (url) => {
const { data } = await axios.get((url), {
method: 'GET',
headers: {
'X-RapidAPI-Key': '328713ab01msh862a3ad609011efp17e6b4jsn0e7112d5ee9a',
'X-RapidAPI-Host': 'zillow56.p.rapidapi.com'
}
});
data.then((res) => {
console.log(res);
})
.catch((error) => {
console.error(error);
});
return data.json();
}
When rendering the page I'm attempting to inject the response's data to dynamically create a list of apartment listings.
I'm trying to use getServerSideProps so that the data is already available by the time a user requests the page. After fetching the data, I want to also print them in the terminal to validate it's success.
export default function Home({ propertiesCustomdata })
export async function getServerSideProps() {
const propertiesCustom = await fetchApiListsingsCustom(`${baseUrl}`)
const propertiesCustomdata = propertiesCustom.json()
return {
props: {
propertiesCustomdata
}
}
}
The problem is, I seem to be getting a 404 error from the axios call, before the page gets a chance to load. When I access this I get a 404 error but I also manage to receive some contents of the call the API was to make.
My apologies if this is unclear, but this is all I know to report on this so far.
Studying async and await, fetch, and axios. Very confusing.

FetchError: request failed

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/

React & Sanity - Fetch Error: invalid JSON response body

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.

Why use use axios.post request in getInitialProps in NextJS

Hello Guys I am learning NextJs from a tutorial. There is a link to update categories in which the instructor is using axios.post request in getInitialProps. I am confused why not use axios.get request because aren't we using getting the initial props to populate the page. Here is the code
Update.getInitialProps = async ({ req, query, token }) => {
const response = await axios.post(`${API}/category/${query.slug}`);
return { oldCategory: response.data.category, token };
};
export default withAdmin(Update);
I get this error if I use axios.get enter image description here

Creating Dynamic Routes using 'getStaticPaths' and 'getStaticProps' in NextJS

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

Resources