Skip to content
Tutorials Center
My learning

Topics

Lesson 131 of 156 ยท Projects

Project: GitHub Profile Search

Build a GitHub profile search in plain JavaScript: a validated search form, fetch with loading and error states, rate limits, profile cards and repo lists.

Searching an API and showing what comes back is one of the most common jobs in front-end work. In this project you will build a GitHub profile search: type a username, and the app shows the person's avatar, bio, follower counts and latest repositories. Along the way you will handle every state such an app can be in โ€” waiting, found, not found, too many requests, offline โ€” and render untrusted data safely.

The TryIt sandbox has no network access, so the app talks to a mock GitHub API: a function shaped exactly like fetch() that returns real Response objects filled with made-up users. The mock copies the shape of GitHub's real REST API, including its error responses and rate-limit headers. At the end of the lesson you will see the few lines that change to use the real API in your own project.

What you'll build

The finished app:

  • validates the username before sending anything;
  • shows a loading placeholder, then a profile card with an avatar, bio, links and stats;
  • lists the user's five most recently updated repositories;
  • gives clear messages for unknown users, rate limits and lost connections;
  • cancels a slow search when you start a new one, and remembers recent results;
  • displays how many API calls you have left.

This project builds on Fetching Data with fetch(), async and await, Promise.all and friends, Cancelling with AbortController, Formatting with Intl and Throwing and Custom Errors. If you built the weather dashboard, the loading and cancelling parts will feel familiar. This project adds what is special about public APIs: rate limits, quotas and data you don't control.

Step 1: A mock GitHub API

GitHub's REST API has two endpoints you need:

Request Returns
GET https://api.github.com/users/{username} One user: login, name, avatar_url, html_url, bio, location, company, blog, public_repos, followers, following, created_at, โ€ฆ
GET https://api.github.com/users/{username}/repos?sort=updated&per_page=5 An array of repositories: name, html_url, description, language, stargazers_count, forks_count, updated_at, โ€ฆ

An unknown user gets a 404 with a JSON body like { "message": "Not Found" }. Every response carries headers such as x-ratelimit-remaining, because anonymous callers get only 60 requests per hour per IP address. When those run out, GitHub answers with a 403 (or 429) and x-ratelimit-remaining: 0, plus x-ratelimit-reset, the time in Unix seconds when the quota refills.

The mock below imitates all of that. It knows three made-up users, plus three special names for testing: ratelimit (quota used up), offline (no connection, so it throws a TypeError like fetch() does) and anything else (404). Run it and read the console:

JS Step 1: A mock GitHub API

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first line prints 200 59: one call used, 59 left. Then you see Ada's details, a table of her three most recently updated repositories (sheet-diff, tiny-charts, dotfiles), a 404 with ok: false and GitHub's Not Found body, a 403 with no calls left, and finally TypeError: Failed to fetch.

Two lessons from the real API are already visible:

  • A 404 doesn't throw. fetch() only rejects when no response arrives at all. Any HTTP status, including 404 and 500, resolves normally, and you must check response.ok or response.status yourself.
  • Not every field is filled in. quiet-coder has null for name, bio, location and company, and an empty string for blog. Real API data is full of gaps like these, and the app must handle each one.

Step 2: Validating and formatting

Before you write any page code, build the small pure functions the app needs. Pure functions take values and return values, so you can test them in the console without a page or a network.

GitHub usernames follow strict rules: letters, digits and single hyphens, no hyphen at the start or end, and at most 39 characters. Checking that before sending a request saves a call from your hourly quota and gives instant feedback.

JS Step 2: Pure helper functions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The output shows that only ada-example, Sam-Sample and x are valid usernames. The compact numbers come out as 0, 954, 12.8K and 1.5M. The dates read just now, yesterday, 2 weeks ago and 3 years ago. The URLs become https://ada.example.com/, https://sam.example.org/ and three nulls.

Notes on each helper:

  • The username pattern. -(?=[a-z\d]) allows a hyphen only when a letter or digit follows it (a lookahead). That one rule blocks double hyphens and a trailing hyphen. The first [a-z\d] blocks a leading one, and {0,38} plus that first character caps the length at 39.
  • timeAgo() walks from the biggest unit down and uses the first one that fits. With numeric: "auto", Intl.RelativeTimeFormat writes "yesterday" instead of "1 day ago". Months and years are approximate (30 and 365 days), which is fine for "updated 3 weeks ago". Taking now as a parameter makes the function testable with fixed dates.
  • safeUrl() matters for security. The blog field is whatever the user typed into their profile. Without the check, a value like javascript:alert(1) placed in an href would run code when someone clicks it. Only http: and https: URLs survive. See JavaScript Security Basics.

Step 3: Search, states and a profile card

Now the page. The app is always in exactly one of four states, and render() draws whichever one is current:

State What the user sees
idle A prompt and example usernames to try
loading A grey placeholder card, and aria-busy="true" on the results
error A message that says what went wrong and what to do
ready The profile card

Keeping the state in one object (view) and drawing everything from it means impossible combinations, such as an error message and a spinner, simply can't happen.

getJSON() turns every failure into an ApiError with a useful message: a 404 keeps its status so the caller can say "No GitHub user called โ€ฆ", a rate limit says when to try again, and a network failure says to check the connection. In this step, the search button is disabled while a request runs, so two searches can never race. Step 4 replaces that with something better.

Step 3: Search with loading and error states

Try every example button. quiet-coder shows how the card copes with missing data: the heading falls back to the login, and the bio, location, company and blog lines simply don't appear. nobody-here gives the 404 message, offline the connection message, and ratelimit uses up the quota, so every search after it fails until you press Run again. Typing -bad- shows the validation message without spending an API call.

Some details that are easy to miss:

  • el() and filter(Boolean). The tiny element builder sets properties with Object.assign() and skips null, "" and false children. That's what makes user.bio && el("p", โ€ฆ) work: when there is no bio, the expression is null and nothing is added. Every piece of API text goes in through textContent, never innerHTML, because profile fields are typed by strangers.
  • encodeURIComponent(login) is a habit even though validation already rejects odd characters: anything you put into a URL path should be encoded.
  • aria-live="polite" and aria-busy. The results region announces new content to screen readers, and aria-busy="true" while loading asks them to wait for the final result instead of reading the placeholder.
  • Errors keep their cause. The connection error wraps the original TypeError as its cause, and console.error(error) logs both, so the console still shows what really happened while the user sees a friendly sentence.
  • The skeleton respects reduced motion. The pulsing placeholder stops animating for users who ask their system for less motion.

Step 4: Repositories, cancelling and caching: the finished app

The final version adds three features:

  1. Repositories. The profile and the repo list come from two endpoints. Promise.all() requests both at the same time, so the wait is the slower of the two rather than their sum. If either fails, the whole search fails, which is right here: half a profile would be confusing.
  2. Cancelling. Disabling the button in step 3 was safe but annoying. Now every search creates an AbortController and aborts the previous one. A slow answer for an old search can never overwrite a newer one, and an aborted search doesn't show an error.
  3. A cache. Results are kept in a Map for five minutes, keyed by the lower-case login. Searching the same user again is instant and costs no API calls. With only 60 calls an hour, that matters.
Step 4: The complete GitHub profile search

Search for ada-example, then sam-sample, then ada-example again. The third search appears instantly, the console logs a cache hit, and the "API calls left" counter doesn't move. Now type ada-example and press Enter twice quickly: the first search is aborted and only the second one renders.

Here is how the cancelling works:

  • search() starts by calling controller?.abort() on whatever search is still running. The mock's wait() listens to the signal and rejects with an AbortError, exactly as a real fetch() would.
  • Both requests in Promise.all() share one signal, so one abort() stops them both.
  • In the catch, an AbortError makes the function return quietly. The newer search owns the screen now, and the old one must not draw anything, not even an error.
  • getJSON() rethrows AbortError unchanged instead of wrapping it as "Can't reach GitHub", because cancelling isn't a connection problem.
  • The finally block clears controller only if it still belongs to this search. A newer search may already have replaced it.

The cache stores the finished result (user plus repos), not the promise, and only after both requests succeed, so a failed search is never cached. Keys are lower-case because GitHub logins ignore case: Ada-Example and ada-example are the same account.

Search on submit, not on every keystroke. With 60 calls an hour, an "instant" search that fires on each key press would burn through the quota in a few searches. If you want search-as-you-type, wait until the user pauses for 300โ€“500 ms (debouncing, see Timers) and keep the cache.

Using the real GitHub API

In your own project, delete the mock and change one line in getJSON(). Everything else, including the error handling, already matches GitHub's real behavior:

JavaScript
const API = "https://api.github.com";

async function getJSON(path, { signal } = {}) {
  let response;
  try {
    response = await fetch(API + path, {
      signal,
      headers: { Accept: "application/vnd.github+json" },
    });
  } catch (error) {
    if (error.name === "AbortError") throw error;
    throw new ApiError("Can't reach GitHub. Check your connection and try again.", { cause: error });
  }
  showQuota(response.headers);
  if (response.ok) return response.json();
  // ...the same 403/429 and other status handling as above
}

A few things to know before you publish it:

  • CORS is allowed. GitHub's API sends the headers that let a web page on any site call it, so this works straight from the browser. Run it from a local web server rather than a file:// page.
  • The Accept header asks for GitHub's current JSON format. GitHub also supports an X-GitHub-Api-Version header to pin a version of the REST API. Check GitHub's REST API documentation for the current values.
  • Rate limits are per IP address for anonymous calls: 60 per hour. Logged-in calls get far more, but they need a token, and a token must never be put in browser code, where anyone can read it. If you need more calls, send requests through your own small server that adds the token, and cache results there too.
  • Avatars are normal image URLs on GitHub's servers, so the <img> tag works as is.
  • Shareable searches. Put the username in the address bar with history.replaceState() and ?user=โ€ฆ, and read it back on load, so a search can be bookmarked (see URLs, Location and History).

More ideas to try

  • Add a "Load more repositories" button using page=2 on the repos endpoint.
  • Show a language breakdown: count the language of each repository and draw a small CSS bar chart, as in the expense tracker.
  • Keep a list of recent searches as clickable chips under the form.
  • Compare two users side by side with Promise.allSettled(), so one missing user doesn't hide the other.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. fetch() gets a 404 response for an unknown user. What happens?

    fetch() only rejects when no response arrives, such as when the network is down. HTTP errors are normal responses, and you check response.ok or response.status.
  2. 2. Why does the app validate the username with a regular expression before searching?

    Validation gives immediate feedback and saves quota. The server still has the final word, so a valid-looking name can still return 404.
  3. 3. Why is the blog field passed through safeUrl() before it becomes a link's href?

    Profile fields are typed by strangers. Allowing only http: and https: URLs stops script URLs from reaching your page.
  4. 4. What happens in the finished app if you start a new search while the previous one is still loading?

    controller?.abort() cancels the old requests, and the catch returns quietly on AbortError, so a stale answer can never overwrite a newer one.
  5. 5. Why are the profile and repository requests wrapped in Promise.all()?

    Both requests start immediately and run in parallel. They still count as two API calls, and if either fails, the whole search fails.

Summary

  • A mock that returns real Response objects lets you build and test API code without a network. Swapping in fetch() later changes one line.
  • fetch() rejects only on network failure. Check response.ok, and turn statuses into clear messages: 404 โ†’ "no such user", 403/429 with x-ratelimit-remaining: 0 โ†’ "try again after โ€ฆ".
  • Model the screen as one state at a time (idle, loading, error, ready) and draw it with a single render() function.
  • Treat API data as untrusted: insert text with textContent, allow only http(s) links, and expect null in any optional field.
  • Validate input before calling a rate-limited API, cache results, and search on submit rather than on every key press.
  • Use Promise.all() for parallel requests and an AbortController per search, so stale answers never overwrite new ones.
  • Never put access tokens in browser code; call authenticated APIs through your own server.

Next: Project: Sortable, Filterable Table