Skip to content
jshacks.dev
Browser

Build a Weather App With fetch in Vanilla JavaScript

Build a weather app with fetch in vanilla JavaScript: geocode a city, request a forecast, handle loading and errors, convert units and render the result safely.

8 min read
Summarize in AI
Flat illustration of a browser and a server trading a request and a response, with the JavaScript, Google Chrome, NGINX and GraphQL logos.

A weather app is the classic way to learn fetch against a real API, because it has everything a small client needs: user input, a network request, a JSON response, loading and error states and a result to render. This post builds a weather app with fetch in vanilla JavaScript using the free Open-Meteo service, which needs no API key for non-commercial use. The app takes a city name, looks up its coordinates with the geocoding endpoint, requests the current weather and a short forecast, and displays them with a unit toggle. Along the way you will see how to build query strings safely with URLSearchParams, check response.ok, handle failure, cancel an outdated request with AbortController, turn weather codes into words and avoid injecting data as HTML. The fetch API is documented on MDN.

The page

The markup is a search form, a status line and a result area.

index.htmlHTML
<main>
  <h1>Weather</h1>
  <form id="search">
    <label for="city">City</label>
    <input id="city" name="city" required autocomplete="off" placeholder="Lisbon">
    <button type="submit">Search</button>
  </form>

  <fieldset>
    <legend>Units</legend>
    <label><input type="radio" name="units" value="metric" checked> °C, km/h</label>
    <label><input type="radio" name="units" value="imperial"> °F, mph</label>
  </fieldset>

  <p id="status" role="status" aria-live="polite"></p>
  <section id="result" hidden>
    <h2 id="place"></h2>
    <p id="current"></p>
    <ul id="forecast"></ul>
  </section>
</main>
<script type="module" src="weather.js"></script>
Text
(a city field, a units choice, a status line and a hidden result section)

The status line is a live region so that "Loading…" and error messages are announced. The result stays hidden until there is something to show.

A small request helper

Every call needs the same things: build a URL with parameters, send it, check the status and parse JSON. Wrap that once.

api.jsJavaScript
export async function getJson(base, params, { signal } = {}) {
  const url = new URL(base);
  url.search = new URLSearchParams(params).toString();

  const response = await fetch(url, { signal });
  if (!response.ok) {
    throw new Error(`Request failed with status ${response.status}`);
  }
  return response.json();
}

const url = new URL("https://geocoding-api.open-meteo.com/v1/search");
url.search = new URLSearchParams({ name: "São Paulo", count: 1 }).toString();
console.log(url.href);
Text
https://geocoding-api.open-meteo.com/v1/search?name=S%C3%A3o+Paulo&count=1

URLSearchParams encodes the accent and the space for you, which concatenating strings by hand would not. The helper checks response.ok, because fetch only rejects on network failure, never on a 404 or 500 response. Forgetting that check is the most common fetch bug: the code happily parses an error page as data.

Find the city

The geocoding endpoint turns a name into latitude and longitude. It returns a results array, which is missing entirely when nothing matches.

geocode.jsJavaScript
import { getJson } from "./api.js";

export async function findCity(name, options) {
  const data = await getJson(
    "https://geocoding-api.open-meteo.com/v1/search",
    { name, count: 1, language: "en", format: "json" },
    options
  );
  const place = data.results?.[0];
  if (!place) throw new Error(`No city found for "${name}"`);
  return {
    name: place.name,
    country: place.country,
    latitude: place.latitude,
    longitude: place.longitude,
  };
}

const city = await findCity("Lisbon");
console.log(city.name, city.country);
Text
Lisbon Portugal

The optional chaining data.results?.[0] handles the missing array, and the function converts "nothing found" into a clear error the interface can show. The returned object contains only the four fields the app needs, which keeps the rest of the code independent of the API's response shape.

Get the weather

The forecast endpoint takes the coordinates and a list of the variables you want. Ask only for what you will display.

forecast.jsJavaScript
import { getJson } from "./api.js";

export async function getWeather({ latitude, longitude }, units, options) {
  const metric = units === "metric";
  return getJson(
    "https://api.open-meteo.com/v1/forecast",
    {
      latitude,
      longitude,
      current: "temperature_2m,weather_code,wind_speed_10m",
      daily: "weather_code,temperature_2m_max,temperature_2m_min",
      timezone: "auto",
      forecast_days: 4,
      temperature_unit: metric ? "celsius" : "fahrenheit",
      wind_speed_unit: metric ? "kmh" : "mph",
    },
    options
  );
}

const weather = await getWeather({ latitude: 38.72, longitude: -9.14 }, "metric");
console.log(weather.current.temperature_2m, weather.current_units.temperature_2m);
Text
18.4 °C

The temperature value is an example because it depends on the moment you call it. The response has a current object with the values and a current_units object with the labels, which means you do not hard-code the unit text. The daily object holds parallel arrays: time, temperature_2m_max and so on, where index 0 is today.

Turn codes into words

The API reports conditions as WMO weather codes. Map them to short descriptions.

codes.jsJavaScript
const DESCRIPTIONS = new Map([
  [0, "Clear sky"],
  [1, "Mainly clear"],
  [2, "Partly cloudy"],
  [3, "Overcast"],
  [45, "Fog"],
  [51, "Light drizzle"],
  [61, "Light rain"],
  [63, "Rain"],
  [65, "Heavy rain"],
  [71, "Light snow"],
  [73, "Snow"],
  [80, "Rain showers"],
  [95, "Thunderstorm"],
]);

export function describe(code) {
  return DESCRIPTIONS.get(code) ?? "Unknown conditions";
}

console.log(describe(3));
console.log(describe(99));
Text
Overcast
Unknown conditions

The map covers the common codes and falls back for the rest, so an unexpected value never shows undefined on screen. The full list is in the Open-Meteo documentation, and you can extend the map with it.

Render safely

Render with DOM methods and textContent. The city name comes from an external service, so treat it like any other untrusted text.

render.jsJavaScript
import { describe } from "./codes.js";

const place = document.querySelector("#place");
const current = document.querySelector("#current");
const forecast = document.querySelector("#forecast");
const result = document.querySelector("#result");

export function show(city, weather) {
  place.textContent = `${city.name}, ${city.country}`;

  const { temperature_2m: t, weather_code: code, wind_speed_10m: wind } = weather.current;
  const units = weather.current_units;
  current.textContent = `${describe(code)}, ${t}${units.temperature_2m}, wind ${wind} ${units.wind_speed_10m}`;

  forecast.replaceChildren();
  weather.daily.time.forEach((day, i) => {
    const li = document.createElement("li");
    const label = new Date(`${day}T12:00`).toLocaleDateString("en", { weekday: "short" });
    const max = weather.daily.temperature_2m_max[i];
    const min = weather.daily.temperature_2m_min[i];
    li.textContent = `${label}: ${describe(weather.daily.weather_code[i])}, ${min} to ${max}${units.temperature_2m}`;
    forecast.append(li);
  });

  result.hidden = false;
}
Text
Lisbon, Portugal
Partly cloudy, 18.4 °C, wind 11.2 km/h
Thu: Partly cloudy, 14.1 to 19.3 °C

The numbers are examples. Appending T12:00 to the date string gives a local noon time, which avoids the off-by-one-day error that new Date("2026-11-20") can produce because a date-only string is parsed as UTC midnight and may display as the previous day in time zones west of Greenwich.

Connect it: loading, errors and cancellation

The controller ties the pieces together. It shows a loading message, cancels any request still running and reports errors in the status line.

weather.jsJavaScript
import { findCity } from "./geocode.js";
import { getWeather } from "./forecast.js";
import { show } from "./render.js";

const form = document.querySelector("#search");
const status = document.querySelector("#status");
let controller = null;
let lastCity = null;

function units() {
  return document.querySelector('input[name="units"]:checked').value;
}

async function load(name) {
  controller?.abort();
  controller = new AbortController();
  const { signal } = controller;

  status.textContent = "Loading…";
  try {
    const city = name ? await findCity(name, { signal }) : lastCity;
    const weather = await getWeather(city, units(), { signal });
    lastCity = city;
    show(city, weather);
    status.textContent = "";
  } catch (error) {
    if (error.name === "AbortError") return;
    status.textContent = error.message;
  }
}

form.addEventListener("submit", (event) => {
  event.preventDefault();
  load(new FormData(form).get("city").trim());
});

document.querySelectorAll('input[name="units"]').forEach((radio) => {
  radio.addEventListener("change", () => lastCity && load(null));
});
Text
Loading…
(then the result appears, or a message such as "No city found for "Xyzzy"")

Aborting the previous request prevents a slow first search from overwriting the second. Changing the units reuses the stored city, so it makes one request instead of two. An AbortError is ignored, since it is not a failure.

Practical notes

Never put a secret API key in client code, because anyone can read it. This example uses a keyless API for that reason; for a service that requires a key, call it from your own server. Cache the last result in localStorage with a timestamp so a reload shows something instantly while the fresh request runs, and note that weather changes slowly, so a ten-minute cache is reasonable. Respect the provider's terms, which for Open-Meteo's free tier limit commercial use and the request rate. Add a timeout with AbortSignal.timeout(8000) combined with your controller using AbortSignal.any([signal, AbortSignal.timeout(8000)]), so a hung connection does not leave the status stuck on Loading. Offer geolocation behind a button, never on page load, since an unexpected permission prompt makes people leave.

Testing and failure modes

Test the happy path and then the unhappy ones, because a weather app is mostly about what happens when the network misbehaves. Search for a real city and check the result against another source. Search for a nonsense word and confirm the message reads "No city found". Turn on the offline mode in the developer tools and search again: fetch rejects with a TypeError, and your catch block should show a friendly line instead of the raw message "Failed to fetch". Throttle the connection to a slow profile, search for two cities in quick succession and confirm that the second result wins.

Think about what the data can look like. A city with a very long name should not break the layout. Some places have no country field, so the title should not print undefined. A forecast array may be shorter than you asked for, so loop over the data that exists rather than a fixed count. Dates need care in time zones: the API returns local dates for the requested place because you passed timezone: "auto", which is why the code builds them from the date string and does not convert from UTC.

Finally, keep the units and the labels together. The response carries its own unit strings, so switching to imperial changes the labels for free, and you avoid the common bug of showing a Fahrenheit number with a Celsius symbol.

Extending the app

Once the basic version works, the extensions are small. Remember the last city in localStorage and load it on startup, so the app opens with useful content. Add a button that uses navigator.geolocation.getCurrentPosition to get coordinates and skips the geocoding step, and call it only from a click. Show an hourly strip by adding the hourly parameter and rendering the next 12 values. Each of these reuses the same helper, which is the benefit of wrapping fetch in one function with one error path.

Share

Keep reading

Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, Swagger, Postman and NGINX logos.
Browser

The DOM Tree: Nodes, Elements and Text

Understand the DOM tree: node types, the difference between nodes and elements, text and comment nodes, tree navigation properties and how whitespace shows up.

6 min read
Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.