This code isn’t working;
this code is written by next js,
the error on the console is:
GET http://localhost:3000/products/porducts.json 404 (not found)
And:
Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
fetch("/products/products.json")
.then((response) => response.json())
.then((data) => console.log(data));
Please, I need solve this problem.
I tried edit this code by a lot of ways and I asked chatGpt but it can’t give me a solution for this problem as I expected and my tries don’t work.
fetch("/products/products.json")
.then((response) => response.json())
.then((data) => console.log(data));
2
Answers
The
products.json
file is a static file. Place theproducts.json
file in the/public
folder. So the path becomes/public/products/products.json
.If you put the
products.json
file in the/app/products/products.json
folder, the file will not be read. Next.js will only read files in theapp
folder such aspage.jsx
,not-found.jsx
, orroute.js
. The error ofUnexpected token '<' is not a valid JSON
is caused because when fetching/products/products.json
it will fetch thenot-found
page.Moaz. Starting from Nextjs 13 going onward, the app router was introduced. It uses a different routing strategy compared to the older router (the pages router).
Of course the developer have the option to use the app router or the pages router or both at the same time. Even though the app router is newer that does not mean the pages router was deprecated or is not good.
To start using the app router, in your project root, or in the src/ directory, create a folder called app/.
And in case you want to use the pages router, you’ll create a folder called pages/ instead. also either in the project root, or in the src/ directory.
Anyway – now based on the screenshot you provided, your nextjs application is based on the app router. This is because your code is placed inside the app/ directory.
In the app router, only certain files are served to the browser. Unlike the pages router where anything you place inside of it becomes a page accessible through the browser URL address bar.
now, you’re placing your JSON file inside the app directory, and – you’re trying to fetch it from a client component (right?). That will not work, this is because the rule I mentioned earlier. Files inside the app directory are not served, only certain files. (only the files called: page.tsx).
Now, in order to fetch this JSON file – move this file from the app directory to the public/ directory.
Now, this file will be accessible through
thus, change your code from:
to: