Building a newsapi.org client with SvelteKit

Enda Lee 2022

Quick Start

  1. Download the code from this repository
  2. Open in VS Code
  3. Rename.env.example to .env, then edit with your newsapi.org api key
  4. In a terminal run npm install
  5. Start the application using npm run dev

Introduction

This example rebuilds the News API app, covered in a previous lab, using SvelteKit. Hopefully it will demonstrate some of the advantages of using the framework over plain JavaScript.

The home page of the site will display the latest news from The Irish Times and the other links will show news from Ireland including Top Headlines, Business, and Sport.

1. Getting started

You should start by creating a new SvelteKit application by running npm create svelte@latest. See the previous lab for more details.

Here is the complete site structure, add all the routes, pages, and other files shown here to your new app. The files can be left empty for now.

2. The default route/ home page.

This page will display the top headlines from the Irish Times. As before, an api key is required from http://newapi.org.

1. Add an environment variable named VITE_NEWS_API_KEY to the .env file.

The variable name is important. SvelteKit makes variables with names starting with VITE_ available on the SvelteKit server and also in the browser - this will be important later.

2. Generating Home Page content

When the page is loaded, news articles will be fetched from newsapi.org and used to build the content. The default page src\routes\+page.svelte should already exist. We also need to add a companion +page.server.js script to the the same location. This purpose of this script is to fetch news articles for the page in a load() function.

SvelteKit can run run scripts server-side (for pre rendering pages) as well as in the browser. Including .server. in the file name ensures that it will not execute in the browser, for example to keep an api key private.

Here is the code for +page.server.js

// add dependency using npm install dotenv first
import 'dotenv/config'

// The load function executes before the page is displayed
export const load = async () => {


    // This async function will fetch and return articles from the Irish Times
    const fetchNews = async () => {
        
        const source = 'the-irish-times';
        const api_key = process.env.VITE_NEWS_API_KEY

        const response = await fetch(`https://newsapi.org/v2/top-headlines?sources=${source}&apiKey=${api_key}`);
        const data = await response.json();
        console.log(data);
        return data.articles;

    }

    // Return articles - which calls fetchNews()
    return {
        articles: fetchNews(),
    }
}

The load() function will execute before the page is displayed, making its data available. The data can then be accessed in +page.svelte for display (source code below).

  1. The