# Weather — real forecasts from Open-Meteo, with no key

> Live weather for any app that shows weather (a dashboard, a trip planner, a garden or event page), with no key and no setup, from Open-Meteo: a place name to coordinates, current conditions, an hourly strip and a daily forecast for one or several places in one call, °C/°F and wind units, weather codes in plain words, refresh and errors that keep the last forecast, and the data credit

Source: https://good.vibes.diy/docs/reference/weather

Current conditions, an hourly strip and a several-day forecast for any place on
Earth come from **Open-Meteo**: free, no account, no key, and open to any
origin, so the page calls it directly with a plain `fetch`. There is no setup
item, no secret and no backend in this recipe, and the app works the moment it
opens.

Open-Meteo's free tier is for non-commercial apps (no ads, no subscriptions)
and fewer than 10,000 calls a day. An app that sells something needs Open-Meteo's
commercial plan and a key; say that to the person in one sentence and build the
free version.

## 1. A place name becomes coordinates

The forecast takes a latitude and longitude, so a typed place goes through
Open-Meteo's geocoder first:

```
GET https://geocoding-api.open-meteo.com/v1/search?name=<typed>&count=5&language=en&format=json
```

Each entry of `results` carries `name`, `latitude`, `longitude`, `timezone`,
`country`, `country_code` and `admin1` (the region), with empty fields left
out. **When nothing matches, the answer has no `results` key at all**, so read
`data.results ?? []` and say "No place called Springfeld" with the typed name
kept on screen. Several towns share a name: list the matches as
`name, admin1, country` and let the person pick one, never silently take the
first. Keep the pick as `{ name, latitude, longitude, timezone }`, which is all
the forecast needs.

"Use my location" reads `navigator.geolocation.getCurrentPosition` from the
press handler (the app's frame is allowed to ask), names the place
"My location", and falls back to the search with the person's answer kept when
they decline.

## 2. One forecast call

```
GET https://api.open-meteo.com/v1/forecast?latitude=38.72&longitude=-9.15
  &current=temperature_2m,apparent_temperature,relative_humidity_2m,weather_code,wind_speed_10m,is_day
  &hourly=temperature_2m,weather_code,precipitation_probability&forecast_hours=12
  &daily=weather_code,temperature_2m_max,temperature_2m_min,precipitation_probability_max,uv_index_max,sunrise,sunset
  &timezone=auto&forecast_days=5
```

- **`timezone=auto` is required for `daily`**, and it makes every `time` the
  place's own local time, so "Tuesday" and "14:00" mean the place's Tuesday.
- `hourly` and `daily` are **parallel arrays**: `daily.time[i]` is the date of
  `daily.temperature_2m_max[i]`. Zip them by index into one object per day.
- `forecast_hours=12` starts the hourly arrays at the current hour, so the strip
  needs no slicing. `forecast_days` runs from 1 to 16.
- **Units go in the request, and change together**: `temperature_unit=fahrenheit`
  with `wind_speed_unit=mph` (and `precipitation_unit=inch`), or the defaults
  °C, km/h and mm. Label each figure from the response's `current_units`,
  `hourly_units` and `daily_units`, which echo what was asked, and refetch when
  the person switches units rather than converting by hand. Keep each response
  beside the units it was asked in and label from those, so figures still on
  screen while the new ones load (or after that refetch fails) keep their own
  units, and let only the newest request land.
- **Several places, one call**: comma-separated `latitude=38.72,59.91` and
  `longitude=-9.15,10.75` answer with an array, one forecast per place in the
  order asked. A single place answers with one object, so wrap it.

## 3. Weather codes become words

`weather_code` is a WMO code. Map it to words in one table, pick any icon from
those words, and show the words: a code number means nothing to anyone.

```js
const WEATHER_CODES = {
  0: "Clear", 1: "Mostly clear", 2: "Partly cloudy", 3: "Overcast", 45: "Fog", 48: "Freezing fog",
  51: "Light drizzle", 53: "Drizzle", 55: "Heavy drizzle", 56: "Freezing drizzle", 57: "Freezing drizzle",
  61: "Light rain", 63: "Rain", 65: "Heavy rain", 66: "Freezing rain", 67: "Freezing rain",
  71: "Light snow", 73: "Snow", 75: "Heavy snow", 77: "Snow grains",
  80: "Showers", 81: "Showers", 82: "Heavy showers", 85: "Snow showers", 86: "Heavy snow showers",
  95: "Thunderstorm", 96: "Thunderstorm with hail", 99: "Thunderstorm with hail",
};
function weatherWords(code) {
  return WEATHER_CODES[code] ?? "Unsettled";
}
```

`current.is_day` is `1` by day and `0` by night, so a clear night can show a
moon instead of a sun.

## 4. When to call

Fetch when the person picks a place or units, and when the app opens with
places already chosen: an effect keyed on the place and the units, never a call
from render. Refresh when the page becomes visible again after 15 minutes or
more, and keep the figures
on screen with "Updated 10:40" from the time they arrived. Three places on one
screen are one call (section 2), not three.

## 5. Errors keep their reason

A bad parameter answers HTTP 400 with `{ "error": true, "reason": "…" }`; show
that reason. A network failure (offline, the service down) keeps the last
forecast on screen with its time and a "Couldn't reach the forecast — Try again"
line, rather than blanking the page. "Try again" repeats the step that failed:
a failed place search searches again, a failed forecast fetches again. Never fill a failed day with zeros: a
forecast of 0° is a forecast, so a missing one says it is missing.

## 6. Credit the data

Open-Meteo's data is CC BY 4.0, so the screen carries a small visible line,
"Weather data by Open-Meteo.com", linking `https://open-meteo.com/`.

## 7. Alerts and digests

"Tell me when frost is coming" or "email me the weekend forecast" is a
scheduled job in backend.js (the `backend` skill), which can read the same
forecast URL with `ctx.fetch`. The page's own forecast never needs a backend.

## App.jsx

```jsx app=weather-forecast
import React, { useEffect, useRef, useState } from "react";
import { Button, Field, Input, Row, Stack } from "@vibes.diy/ui";

const UNITS = {
  metric: { query: "", temp: "°C", wind: "km/h" },
  imperial: { query: "&temperature_unit=fahrenheit&wind_speed_unit=mph&precipitation_unit=inch", temp: "°F", wind: "mph" },
};

async function searchPlaces(typed) {
  const r = await fetch(`https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(typed)}&count=5&language=en&format=json`);
  const data = await r.json();
  if (!r.ok) throw new Error(data.reason ?? `The place search answered ${r.status}`);
  return (data.results ?? []).map((p) => ({ name: p.name, region: [p.admin1, p.country].filter(Boolean).join(", "), latitude: p.latitude, longitude: p.longitude }));
}

// Every place in one call; the answer is an array for several places and an object for one.
async function fetchForecast(places, units) {
  const lat = places.map((p) => p.latitude).join(",");
  const lon = places.map((p) => p.longitude).join(",");
  const r = await fetch(
    `https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lon}` +
      "&current=temperature_2m,apparent_temperature,weather_code,wind_speed_10m,is_day" +
      "&daily=weather_code,temperature_2m_max,temperature_2m_min,precipitation_probability_max" +
      `&timezone=auto&forecast_days=5${UNITS[units].query}`
  );
  const data = await r.json();
  if (!r.ok || data.error) throw new Error(data.reason ?? `The forecast answered ${r.status}`);
  const all = Array.isArray(data) ? data : [data];
  return all.map((f, i) => ({
    place: places[i],
    now: { temp: f.current.temperature_2m, feels: f.current.apparent_temperature, code: f.current.weather_code, wind: f.current.wind_speed_10m },
    days: f.daily.time.map((date, d) => ({
      date,
      hi: f.daily.temperature_2m_max[d],
      lo: f.daily.temperature_2m_min[d],
      code: f.daily.weather_code[d],
      rain: f.daily.precipitation_probability_max[d],
    })),
  }));
}

const dayName = (date) => new Date(`${date}T12:00`).toLocaleDateString(undefined, { weekday: "short" });

export default function App() {
  const [places, setPlaces] = useState([{ name: "Lisbon", region: "Portugal", latitude: 38.72, longitude: -9.15 }]);
  const [units, setUnits] = useState("metric");
  // The figures on screen and the units they were asked in, kept together: a toggle changes
  // `units` at once, and the figures it labels arrive later or not at all.
  const [shown, setShown] = useState({ forecasts: [], units: "metric" });
  const latest = useRef(0);
  const [updated, setUpdated] = useState(null);
  // A failure and the step that retries it: search and forecast fail separately, so "Try again"
  // repeats the one that failed. A search that found nothing has no retry, only a message.
  const [problem, setProblem] = useState(null);
  const [typed, setTyped] = useState("");
  const [matches, setMatches] = useState([]);

  const load = () => {
    setProblem(null);
    const n = ++latest.current; // only the newest request may land, or a slow old one restores old units
    const asked = units;
    fetchForecast(places, asked)
      .then((f) => { if (n === latest.current) { setShown({ forecasts: f, units: asked }); setUpdated(new Date()); } })
      .catch((e) => { if (n === latest.current) setProblem({ message: e.message, retry: load }); }); // the last forecast stays on screen, with its own units
  };
  useEffect(load, [places, units]);
  useEffect(() => {
    const onVisible = () => {
      if (document.visibilityState === "visible" && updated && Date.now() - updated.getTime() > 15 * 60 * 1000) load();
    };
    document.addEventListener("visibilitychange", onVisible);
    return () => document.removeEventListener("visibilitychange", onVisible);
  }, [updated, places, units]);

  const search = async () => {
    setProblem(null);
    try {
      const found = await searchPlaces(typed);
      setMatches(found);
      if (found.length === 0) setProblem({ message: `No place called ${typed}.`, retry: null });
    } catch (e) {
      setProblem({ message: e.message, retry: search });
    }
  };

  const u = UNITS[shown.units]; // label the figures in the units they came in
  return (
    <Stack gap={4}>
      <Row gap={2} align="top">
        <Field label="Add a place">{(id, describedBy) => <Input id={id} describedBy={describedBy} value={typed} onChange={setTyped} placeholder="Oslo" />}</Field>
        <Button type="button" onClick={search}>Find</Button>
        <Button type="button" variant="quiet" onClick={() => setUnits(units === "metric" ? "imperial" : "metric")}>
          Show {units === "metric" ? "°F" : "°C"}
        </Button>
      </Row>
      {matches.map((m) => (
        <Button key={`${m.latitude},${m.longitude}`} type="button" variant="quiet" onClick={() => { setPlaces([...places, m]); setMatches([]); setTyped(""); }}>
          {m.name}, {m.region}
        </Button>
      ))}
      {problem && (
        <p role="alert">
          {problem.message} {problem.retry && <Button type="button" variant="quiet" onClick={problem.retry}>Try again</Button>}
        </p>
      )}

      {shown.forecasts.map((f) => {
        const words = weatherWords(f.now.code);
        return (
          <section key={f.place.name + f.place.latitude}>
            <h2>{f.place.name}</h2>
            <p>{Math.round(f.now.temp)}{u.temp} · {words} · feels like {Math.round(f.now.feels)}{u.temp} · wind {Math.round(f.now.wind)} {u.wind}</p>
            <ol>
              {f.days.map((d) => (
                <li key={d.date}>
                  {dayName(d.date)}: {weatherWords(d.code)}, {Math.round(d.hi)}{u.temp} / {Math.round(d.lo)}{u.temp}, {d.rain}% rain
                </li>
              ))}
            </ol>
          </section>
        );
      })}
      {updated && <small>Updated {updated.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}</small>}
      <small>Weather data by <a href="https://open-meteo.com/" target="_blank" rel="noreferrer">Open-Meteo.com</a></small>
    </Stack>
  );
}
```

`weatherWords` and its table are section 3's, in the same file.
