Building a News Site - Fetching Articles
Fetch and render articles from the newsapi.org API
Get the project source code below, and follow along with the lesson material.
Download Project Source CodeTo set up the project on your local machine, please follow the directions provided in the README.md
file. If you run into any issues with running the project source code, then feel free to reach out to the author in the course's Discord channel.
In this lesson, you are going to use the newsapi.org API to fetch the articles you'll display on your site.
There's a quick registration process on their site (the API is free to use)
Step 1 - Register for newsapi.org#
You need to register and get an API key to use the API.
Navigate here and fill in your details, then copy the API key from the site.
Return to the editor, create a new .env
file in the root folder, and add the following environment variables to it:
xxxxxxxxxx
NEWS_API_KEY=<YOUR_API_KEY>
NEWS_API_URL=https://newsapi.org/v2/
Remember to replace YOUR_API_KEY with the API key you've copied from the site.
Environment variables are used to store configuration outside the code, like API keys or database URLs, ensuring they're secure and adaptable to different deployment environments.
Adding Types#
You are going to use the top-headlines
endpoint to fetch the articles.
You can grab the article type from there. Create a new file at types/article.ts
and add the following code:
xxxxxxxxxx
export type Article = {
source: {
name: string
}
author: string
title: string
description: string
url: string
urlToImage: string
publishedAt: string
content: string
}
Then, add the category type in types/category.ts
:
xxxxxxxxxx
export type Category =
| "general"
| "business"
| "entertainment"
| "health"
| "science"
| "sports"
| "technology"
This lesson preview is part of the Sleek Next.JS Applications with shadcn/ui course and can be unlocked immediately with a \newline Pro subscription or a single-time purchase. Already have access to this course? Log in here.
Get unlimited access to Sleek Next.JS Applications with shadcn/ui, plus 70+ \newline books, guides and courses with the \newline Pro subscription.