Consuming API routes in Next.js

Next.js provides an amazing feature called API routes where you define server side logic to fetch data from your apis and pass it to client side. In this article, lets see how can we can fetch news from an API route and send the data to the client side using Next.js API routes
Create GET request
Create a get request inside news/route.ts file. Make sure you are inside the app/api folder when creating any api route requests.
// app/api/news/route.ts
import axios from "axios";
import { NextResponse } from "next/server";
const GET_NEWS = "https://newsapi.org/v2/top-headlines?country=us&apiKey=<YOUR_API_KEY>"
export async function GET(){
let data = null;
await axios.get(GET_NEWS)
.then(res=>{
console.log(res)
data = res.data.articles;
})
.catch(err=>{
console.log(err)
})
if(data === null){
return NextResponse.json({ message: "Error fetching news" }, { status: 500 });
}
return NextResponse.json(data, { status: 200 });
}
Create a page called dashboard where you will fetch the api endpoint
The dashboard page is where we will include the news component that will call the API route which fetches news from the endpoint.
import News from "@/app/dashboard/components/News"
const Page = () => {
return (
<>
<News />
</>
);
};
export default Page;
Create News Component that will call the api endpoint and pass the data to the presentation component
The news component will be rendered on the client side by adding “use client” directive on the top of the page which will make the component a client-side component in next.js. A client component can access all the essential APIs from the react library such as useState and useEffect.
"use client";
import FullPageNewsLoading from "@/components/full-page-news-loading";
import NewsCardComponent from "@/components/news-card";
import { Article } from "@/lib/models";
import axios from "axios";
import { useEffect, useState } from "react";
const NewsWrapper = () => {
const [news, setData] = useState<Article[]>([]);
const newsCondition = news !== null && news?.length > 0;
useEffect(() => {
fetchNewsData();
}, []);
const fetchNewsData = async () => {
await axios
.get("/api/news")
.then((res) => {
console.log(res.data);
let filteredData = res.data.filter((item:Article)=> item.content !== "[Removed]");
filteredData = res.data.filter((item: Article)=> item.author !== null);
setData(filteredData);
})
.catch((err) => {
console.log(err);
});
};
return (
<div className="container mx-auto px-4 mt-4">
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
{newsCondition ? (
news.map((item, index) => (
<NewsCardComponent item={item} index={index} key={index} />
))
) : (
null
)}
</div>
</div>
);
};
export default NewsWrapper;
Your Output
If everything works. You can start your development server to see the output.
npm run dev
Conclusion
In this article, we have seen how you can setup API routes in next.js and then consume them in client components inside your next.js application.
Subscribe to my newsletter
Read articles from Mithilesh Tarkar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
