I'm new to Next.js. I just finished the tutorial and had a question about API's.
This page in the docs seems to suggest that API routes should be defined in a subfolder/route for each page where they will be used.
For instance, let's say I have a page /app/dashboard/page.tsx
and I want to make a call to a 3rd party API. I could create /app/dashboard/api/route.ts
and define a GET request:
export async function GET() {
const res = await fetch('https://random-api.com/...')
const data = await res.json()
return Response.json({ data })
}
I don't understand why this logic would be nested inside the route instead of at the top level of the project. With the above logic, wouldn't you have to redefine the logic in every page that you want to use it in?
I'm very likely misunderstanding the documentation and would appreciate if someone could help clarify.
What is the best project structure for defining API logic so that I can use the logic globally inside of server components? Also, is it possible to use the same API functions in client components as well?
API can be in any directory you want when using the app Router. In pages Router, they need to be inside /pages/api/<any structure you want from here>
and can be named something else than route
Seeing that you are using the app Router, the only requirement is that the file is called route.ts
(or js) and it probably won't work if you have a page.tsx (or jsx) in the same folder.
Coming from earlier version of Next, I usually have my APIs in /app/api/...
but that's just me. As I said, you put it wherever you want.
Just remember that the folders are mapped to the URL path so /app/dashboard/api/route.ts
will have another url than /app/api/dashboard/route.ts