# How to Add Weather Forecast Integration to Your App — Copy-Paste Prompts Inside

- Tool: App Features
- Last updated: July 2026

## TL;DR

A weather integration needs three pieces: a location input (browser geolocation or city search), a server-side proxy that keeps your API key secret, and a UI layer for current conditions plus a 7-day forecast. With V0 or Lovable you can ship a working weather widget in 1–3 hours for $0/month using Open-Meteo (free, no key needed) or within OpenWeatherMap's 1,000 calls/day free tier.

## What a Weather Forecast Integration Actually Is

A weather integration connects your app to a third-party weather API — OpenWeatherMap, Open-Meteo, or Tomorrow.io — and displays conditions for a location the user specifies or their browser detects automatically. The feature appears in travel apps, outdoor event planners, agriculture dashboards, food delivery apps (courier routing), and any product where conditions affect what users do next. The challenge isn't displaying temperature — AI tools do that in minutes. The real decisions are: which API to use (free vs. paid, accuracy vs. cost), how to cache responses so you don't burn your quota on repeated page loads, and where to keep the API key so it's never visible in the browser network tab.

## Anatomy of the Feature

Six components — the API proxy is the one AI tools most often skip, and skipping it is the security failure mode for this feature.

- **Location input and geocoding layer** (service): Converts a city name or postcode to latitude/longitude coordinates so the weather API can return accurate data. Uses the browser's navigator.geolocation.getCurrentPosition() for automatic detection, or the Mapbox Geocoding API / OpenWeatherMap Geocoding API for city name searches. Geocoding result is held in component state — no database needed.
- **Server-side API proxy** (backend): A Next.js API route (app/api/weather/route.ts) or Supabase Edge Function that receives a lat/long from the frontend, appends the secret API key from environment variables, calls the weather API, and returns the cleaned JSON. This is the only place the key exists — it never touches the browser.
- **Caching layer** (backend): Cache-Control headers on the API route response (s-maxage=900, stale-while-revalidate=1800) tell Vercel's Edge Cache to serve cached weather data for 15 minutes before re-fetching. For multi-region or high-traffic apps, Upstash Redis stores cached responses keyed by rounded coordinates (1 decimal place) to avoid blowing the API quota.
- **Current conditions card** (ui): A shadcn/ui Card component showing temperature, condition description, humidity percentage, wind speed, and feels-like temperature. Animated or static SVG weather icons from the Meteocons package or animated-weather-icons npm package provide instant visual context. Light/dark mode variants should swap icon colors automatically via Tailwind dark: classes.
- **Forecast timeline** (ui): Hourly forecast displayed as a horizontally scrollable row using shadcn/ui ScrollArea — each item shows time, icon, and temperature. 7-day forecast shown as a vertical list or CSS grid with min/max temps and precipitation probability percentage. A Recharts AreaChart or LineChart overlays the temperature trend for the next 48 hours.
- **Unit preference store** (data): User preference for temperature unit (°C or °F) and wind speed unit stored in localStorage on the client. A React context or Zustand store exposes the current unit preference to all components. No database or authentication required — unit preference is purely local.

## Build paths

### V0 — fit 5/10, 1–3 hours

Best path for weather integration — V0 naturally generates a Next.js API route that keeps the key server-side, and Recharts temperature charts are a V0 strength. Vercel Edge Cache handles caching automatically on deploy.

1. Paste the prompt below into V0 and let it generate the weather page, API route, and Recharts chart components
2. Open the Vars panel in V0 and add OPENWEATHERMAP_API_KEY (or leave blank if using Open-Meteo which needs no key)
3. Publish to Vercel — test geolocation and the unit toggle on the live HTTPS URL from your phone
4. In Vercel Dashboard, confirm the API key is set as an environment variable and not in any client-side file

Starter prompt:

```
Build a weather forecast page for a Next.js app using the OpenWeatherMap One Call API 3.0 (or Open-Meteo as a fallback if no key is available). The API key must be stored in OPENWEATHERMAP_API_KEY server-side — never in client code. Create a Next.js API route at app/api/weather/route.ts that accepts lat and lon query params, fetches the weather data server-side, adds Cache-Control: s-maxage=900, stale-while-revalidate=1800 to the response headers, and returns current conditions plus 7-day and hourly forecast. On the frontend: use navigator.geolocation.getCurrentPosition() to detect location on page load; if denied or unavailable, show a city search input that uses OpenWeatherMap Geocoding API to resolve lat/long. Display: (1) a current conditions card with temperature, condition description, humidity, wind speed, and a weather icon using Meteocons SVGs; (2) a horizontally scrollable hourly row for the next 24 hours using shadcn/ui ScrollArea; (3) a 7-day forecast grid with daily high/low and precipitation probability; (4) a Recharts AreaChart for 48-hour temperature trend. Include a unit toggle (Celsius/Fahrenheit, km/h / mph) stored in localStorage via a useEffect hook — never access localStorage during SSR. Show three distinct states: loading skeleton, data loaded, error with retry button. Handle geolocation denied gracefully with a fallback city search input.
```

Limitations:

- V0 does not auto-provision Vercel env vars — you must add OPENWEATHERMAP_API_KEY manually in the Vercel Dashboard before the API route will return data
- The V0 sandbox cannot access the browser geolocation API — test the full location flow on the deployed Vercel URL
- Recharts may need a follow-up prompt to fix ResponsiveContainer height collapse inside flex layouts

### Lovable — fit 3/10, 2–4 hours

Lovable can scaffold the weather UI and Supabase Edge Function proxy quickly, but requires extra prompting to prevent it from calling the weather API directly from the React component — which would expose the API key.

1. Paste the prompt below and let Lovable build the weather widget and Edge Function proxy
2. Go to Cloud tab in Lovable → Secrets and add OPENWEATHERMAP_API_KEY (or OPEN_METEO_BASE_URL if using the free API)
3. Open the published URL on your phone to test geolocation — it will not work in the Lovable preview iframe
4. In the published app, open DevTools → Network tab and confirm no weather API calls appear with a key in the URL — all calls should go to your Edge Function

Starter prompt:

```
Build a weather forecast feature in Lovable backed by a Supabase Edge Function as an API proxy. Create a Supabase Edge Function at supabase/functions/weather/index.ts that accepts a GET request with lat and lon query params, reads the OpenWeatherMap API key from Deno.env.get('OPENWEATHERMAP_API_KEY'), calls the OpenWeatherMap One Call API 3.0 endpoint, and returns the JSON response with CORS headers. The React component calls this Edge Function — never the weather API directly. Display: (1) a current conditions card with temperature, humidity, wind speed, and condition text; (2) a 7-day forecast row with each day's high/low and precipitation probability; (3) an hourly timeline for the next 24 hours. Use navigator.geolocation.getCurrentPosition() with a city name search fallback input for users who deny permission. Include a Celsius/Fahrenheit toggle stored in React state (not localStorage, to avoid SSR issues). Show loading, data, and error states. Weather icons: use emoji fallbacks (sun emoji, cloud emoji, rain emoji) mapped from OpenWeatherMap condition codes — no external icon CDN dependency.
```

Limitations:

- Lovable's preview iframe blocks both navigator.geolocation and camera APIs — geolocation only works on the published URL
- Lovable AI frequently generates the fetch call in the React component rather than routing through the Edge Function — audit the generated code before publishing
- No built-in edge caching in Lovable's Edge Functions — API calls fire on every page load unless you add Supabase caching logic manually
- The Edge Function adds ~200ms cold start latency on first request per region

### Custom — fit 4/10, 2–5 days

Custom development is the right path when weather is a core product feature — agricultural dashboards needing field-level accuracy, multi-location fleet monitoring, or apps that trigger push notifications based on weather thresholds.

1. Next.js API route with Upstash Redis caching (10-minute TTL keyed by rounded coordinates to 1 decimal place) — reduces API calls by 95% for apps with geographic clustering of users
2. Tomorrow.io or OpenWeatherMap subscription for minute-level and hyper-local data not available on free tiers
3. Background job (Vercel Cron or Supabase pg_cron) that pre-fetches weather for user-configured locations so the UI loads instantly from cache
4. Weather-based notification logic: compare forecast against user-defined thresholds and trigger Resend emails or web push via a separate notification service

Limitations:

- Pre-fetching and threshold alerts require a persistent user location store and a notification delivery pipeline that AI tools don't auto-generate
- Hyper-local agricultural data (Tomorrow.io Historical API, soil moisture) requires paid tiers and custom data models beyond what a brief prompt session produces

## Gotchas

- **Weather API key is visible in the browser Network tab** — Lovable AI frequently generates the weather fetch call directly inside the React component — the API key appears in the request URL visible to any user who opens DevTools. This is the most common and most dangerous mistake for this feature. The key can then be scraped and used to exhaust your API quota. Fix: Move every weather API call to a Next.js API route (V0) or Supabase Edge Function (Lovable). Store the key in OPENWEATHERMAP_API_KEY server-side. After any AI generation session, open the published app's Network tab and verify no calls go directly to api.openweathermap.org — all calls should hit your own /api/weather endpoint.
- **Geolocation prompt never fires in preview** — navigator.geolocation.getCurrentPosition() is blocked inside Lovable's preview iframe and V0's sandbox environment. The call returns silently with no error, leaving location as null. Builders assume geolocation is broken in their code when it's actually the environment blocking it. Fix: Test geolocation exclusively on the published Lovable URL or deployed Vercel URL opened in a real mobile or desktop browser. Always include a city name search input as the non-permission fallback — a significant share of real users deny location access.
- **localStorage unit toggle causes hydration mismatch in Next.js** — When V0 generates the Celsius/Fahrenheit toggle, it often accesses localStorage to read the saved preference during the initial render. Next.js runs components server-side where localStorage doesn't exist, so the server renders one state and the client hydrates with a different value — React throws a hydration error. Fix: Initialize the unit state as a static default ('celsius') and read localStorage only inside a useEffect hook: useEffect(() => { setUnit(localStorage.getItem('tempUnit') || 'celsius') }, []). Alternatively, wrap the entire unit toggle component in a 'use client' boundary with useEffect initialization.
- **Weather data is stale — showing yesterday's forecast** — Without explicit cache invalidation, Vercel's CDN may serve the same cached API response indefinitely once it's been cached. Users see forecast data hours or even a day old, which destroys trust in the feature instantly. Fix: Set Cache-Control headers on every weather API route response: Cache-Control: s-maxage=900, stale-while-revalidate=1800. This tells Vercel's Edge Cache to serve fresh data after 15 minutes and treat data up to 30 minutes old as stale-while-revalidating. Explicitly include this header in your prompt — V0 does not add it by default.

## Best practices

- Always proxy weather API calls through a server-side route or Edge Function — never call a weather API with a key from frontend code
- Default to Open-Meteo for apps where budget matters — it's completely free for commercial use, no API key required, and the data quality matches OpenWeatherMap for most use cases
- Cache responses for 15 minutes minimum using Cache-Control headers; most users don't need real-time weather data and caching cuts API costs by 90%+
- Round user coordinates to one decimal place (about 11km precision) before using them as cache keys — this collapses nearby users onto the same cached response
- Always ship a city name search fallback alongside geolocation — at least 30% of desktop users and some mobile users deny the location prompt
- Show a loading skeleton for the weather card, not a spinner — weather data takes 200–800ms to arrive and a skeleton reduces perceived wait time
- Test the error state deliberately by temporarily pointing the API route at a bad URL — verify the retry button is visible and functional before shipping

## Frequently asked questions

### Which weather API is most accurate for a small web app?

For most apps, Open-Meteo and OpenWeatherMap produce comparable accuracy for standard current conditions and 7-day forecasts. Open-Meteo is free with no API key and pulls from multiple global models (GFS, ECMWF, DWD), making it the best starting point. If you need minute-level precipitation, air quality, or pollen count, Tomorrow.io has the richer data but starts at $150/mo.

### Do I need an API key to use weather data in my app?

Not always. Open-Meteo is completely free for commercial use with no API key required — just make a GET request to their public endpoint. OpenWeatherMap and Tomorrow.io require a key even on their free tiers. If you use a key, it must live in a server-side environment variable and be called through an API route or Edge Function, never in frontend code.

### How do I avoid exposing my weather API key in the browser?

Create a Next.js API route (app/api/weather/route.ts) or a Supabase Edge Function that receives lat/long from your React component, adds the key from a server environment variable, calls the weather API, and returns the data. The browser only ever sees your own domain in the Network tab — the real API key is never sent to the client. After deploying, open DevTools Network and confirm no calls go directly to api.openweathermap.org.

### How often should I refresh the weather data to balance accuracy and API costs?

A 15-minute cache is the right default for most apps — weather models only update every 1–6 hours anyway, so more frequent fetching wastes API calls without improving accuracy. Set Cache-Control: s-maxage=900, stale-while-revalidate=1800 on your API route response. For real-time rain radar or minute-precision data, you'd need a paid weather API and a shorter 1–5 minute cache.

### Can I show weather for multiple locations on the same page?

Yes, but each location needs its own API call. If you display 5 cities simultaneously, that's 5 calls per page load — multiply by your daily active users and you'll exhaust a free tier quickly. Pre-cache weather for your fixed location set (e.g., your top 10 cities) on a schedule using Vercel Cron or Supabase pg_cron, and serve those cached results to all users.

### How do I handle the case where the user denies location permission?

Always include a city name search input as a fallback. When navigator.geolocation.getCurrentPosition() returns a PermissionDeniedError, show the search input automatically with a short message like 'Location access denied — search for a city instead.' Use the OpenWeatherMap Geocoding API or Mapbox Geocoding API to convert the city name to lat/long before calling your weather proxy.

### What's the difference between OpenWeatherMap, Open-Meteo, and Tomorrow.io?

Open-Meteo is free, open-source, and no-key — best for budget-conscious projects. OpenWeatherMap is the most documented option with a 1,000 call/day free tier and paid tiers from $40/mo — best when you need reliable official docs and a large community. Tomorrow.io has the richest data (air quality, pollen, UV, minute precipitation) and starts at $150/mo — best for vertical apps where weather accuracy directly affects user decisions.

### Can I add weather-based alerts that notify users by email or push notification?

Yes, but this requires more infrastructure than a display widget. You need to store user locations in a database, run a scheduled job (Vercel Cron, Supabase pg_cron) that fetches forecast data and compares it against user-defined thresholds, and a notification delivery service (Resend for email, web push for browser notifications). This is typically where a basic AI-built widget becomes a custom development project.

---

Source: https://www.rapidevelopers.com/app-features/weather-forecast-integration
© RapidDev — https://www.rapidevelopers.com/app-features/weather-forecast-integration
