Next.js Discord

Discord Forum

Can I get an example on how to make APIs with nextjs?

Answered
Barbary Lion posted this in #help-forum
Open in Discord
Barbary LionOP
I've been trying all day trying to search up tutorials documentation but it never works. Can someone show me an example from both the back and front end so I can see if I'm doing something wrong? Thank you.
Answered by LuisLl
View full answer

21 Replies

Barbary LionOP
I just went to localhost:3000/api and I saw the correct data being displayed. So the problem is with the front end.
If you need to fetch data in Server Components just move the data fetching logic to the Server Component body.

If you need a Client Component to fetch data, you need to do it via fetch ( something like fetch("/api/your-route/etc") ), inside useEffect, or using a library like React Query.

You could also fetch data directly in Server Components, no need to fetch from your Route Handlers, and pass the data down as props to Client Components if needed (preferred way)
@LuisLl Can I ask what are you trying to achieve? Have you ever fetched data from the frontend via `fetch(url)`?
Barbary LionOP
Nope, this is my first time and it's not working
Are you calling a Route Handler from your server component to fetch data? I need more context to be able to help you properly
Can you show me the code that's not working?
Barbary LionOP
''' import { useState } from "react";

export default function MyComponent() {
const [print, setPrint] = useState("Click me to fetch data");

async function fetchData() {
try {
const response = await fetch("/api/hello"); // Ensure this matches your API route
if (!response.ok) {
throw new Error(HTTP error! Status: ${response.status});
}
const data = await response.json();
setPrint(data.message);
} catch (error) {
console.error("Error fetching API:", error);
setPrint("Error fetching data");
}
}

return (
<p onClick={fetchData} style={{ cursor: "pointer", color: "blue" }}>
{print}
</p>
);
}
'''
@LuisLl Can I ask what are you trying to achieve? Have you ever fetched data from the frontend via `fetch(url)`?
Barbary LionOP
Im just testing out the api right now. Currently, if you go to localhost:3000/api/hello, it has data
I just got off the code before you started answering
Thanks for your help I'll just look at it tommorow
I'm not getting errors
Can you show me an example of how you would use the api on the front end?
Barbary LionOP
What does fetch return? An object?
What do I do after I do this const e = await fetch('/api/route');
What do I do to get the data?
Blood cockle
hey dude. it might be worth checking out a tutorial or documentation to get a more comprehensive understanding of what's happening and what to expect. nextjs has a "learn" series that might give you more context.
https://nextjs.org/learn/pages-router/api-routes-creating-api-routes
Answer
@Barbary Lion What does fetch return? An object?
Fetch returns a promise with the data you return from the endpoint, either it's a string, or an object or whatever your endpoint returns. That's why you need to await it, in order to access that value.
Barbary LionOP
Thanks guys