I've been exploring the most effective method for calling an external API within a Next.js application recently. Given my experience in developing MERN stack applications, I typically rely on axios for handling API requests and utilize it within a useEffect hook. Venturing into the world of Next.js, I encountered various concepts such as server components which led to some confusion. Despite this, I attempted the following approach which seems to function correctly, but I am left wondering: is this truly the recommended practice?
my-next-app>app>api>hello>route.ts
import axios from "axios";
export async function GET() {
const response = await axios.get("http://localhost:5000");
return Response.json(response.data);
}
my-next-app>hello>page.tsx
"use client";
import axios from "axios";
import * as React from "react";
export default function page() {
const [msg, setMsg] = React.useState("");
React.useEffect(() => {
axios.get("api/hello").then((res) => {
// { msg: "Hello World!" }
setMsg(res.data.msg);
});
}, []);
return <div>{msg}</div>;
}