How to Configure Weather Forecasts Using Open-Meteo Integration in TREK
TREK automatically configures weather forecasts using the free Open-Meteo API without requiring API keys, implementing intelligent data source selection and caching in the NestJS backend service layer.
TREK is an open-source travel planning application that leverages the Open-Meteo weather service to provide free, accurate forecasts without API credentials. The integration resides in the backend NestJS service layer and surfaces weather data through REST endpoints consumed by the React frontend. This guide explains how to configure and extend the weather forecast functionality using the Open-Meteo integration as implemented in the mauriceboe/TREK repository.
Architecture Overview
The weather system spans three layers: the backend service handling Open-Meteo API communication, the controller exposing HTTP endpoints, and the React UI components rendering the data.
Backend Service Layer
In server/src/services/weatherService.ts, the core logic determines which Open-Meteo endpoint to call based on the requested date. The service implements getWeather() for daily summaries and getDetailedWeather() for hourly data. It maps numeric WMO weather codes to human-readable strings using WMO_MAP and language-specific description tables such as WMO_DESCRIPTION_EN and WMO_DESCRIPTION_DE.
REST API Endpoints
The weather.controller.ts file (located in server/src/nest/weather/) exposes two endpoints:
/weather– Returns a single-day summary viagetWeather()/weather/detailed– Returns hourly forecast data viagetDetailedWeather()
Both endpoints accept lat, lng, date, and language parameters.
Client-Side Integration
The React frontend calls these endpoints when users open a day in the Day Detail panel. The weather widget displays at the top of this panel and as a badge in the sidebar, showing icons, min/max temperatures, precipitation probability, wind speed, and sunrise/sunset times.
How TREK Selects Weather Data Sources
TREK automatically selects one of three Open-Meteo endpoints based on the date difference from today, implemented in the _getWeatherImpl function:
// From server/src/services/weatherService.ts
if (diffDays >= -1 && diffDays <= 16) {
// Forecast window: ±16 days from today
url = `https://api.open-meteo.com/v1/forecast?...`;
} else if (diffDays < -1) {
// Historical data: past dates
url = `https://archive-api.open-meteo.com/v1/archive?...`;
} else {
// Climate estimate: >16 days in the future
// Uses prior year data for the same calendar day
url = `https://archive-api.open-meteo.com/v1/archive?...`;
}
Forecast data (within ±16 days) uses the forecast API. Archive data (past dates) uses the archive API. Climate estimates (beyond 16 days) approximate conditions using historical data from the previous year.
Caching Strategy for Performance
The service implements an in-memory cache using a JavaScript Map to minimize API calls and improve UI responsiveness. The cache stores results keyed by (lat,lng,date) with time-to-live (TTL) values defined in weatherService.ts:
- Forecast data: Cached for 1 hour (
TTL_FORECAST_MS = 60 * 60 * 1000) - Current weather: Cached for 15 minutes (
TTL_CURRENT_MS = 15 * 60 * 1000) - Climate and archival data: Cached for 24 hours (
TTL_CLIMATE_MS = 24 * 60 * 60 * 1000)
A cleanup routine runs every 5 minutes to prune expired entries and prevent memory leaks.
Display Unit Configuration
While no API keys or environment variables are required for Open-Meteo integration, users can configure display units through the Display Settings page:
- Temperature units: Toggle between Celsius (°C) and Fahrenheit (°F)
- Wind speed units: Automatically follows temperature selection (km/h for °C, mph for °F)
These settings are stored in the user profile and read by frontend components when rendering the weather widget.
Implementation Examples
Fetching Daily Weather Summary
To retrieve a single-day forecast from the backend service:
import { getWeather } from '@/services/weatherService';
async function fetchSummary() {
const lat = '48.8566'; // Paris coordinates
const lng = '2.3522';
const date = '2024-08-15'; // ISO date string
const lang = 'en'; // Supported: 'en', 'de', etc.
const result = await getWeather(lat, lng, date, lang);
console.log(result);
// Returns: { temp: 22, temp_max: 24, temp_min: 18,
// main: 'Clear', description: 'Clear sky',
// type: 'forecast', ... }
}
Fetching Detailed Hourly Data
For hourly breakdowns including precipitation and wind:
import { getDetailedWeather } from '@/services/weatherService';
async function fetchDetail() {
const lat = '48.8566';
const lng = '2.3522';
const date = '2024-08-15';
const lang = 'en';
const data = await getDetailedWeather(lat, lng, date, lang);
console.log(data.hourly?.slice(0, 5)); // First 5 hourly entries
}
React Component Integration
Consume the REST API from the frontend:
import { useEffect, useState } from 'react';
interface WeatherResult {
temp: number;
main: string;
description: string;
}
export function WeatherWidget({ lat, lng, date }:
{ lat: string; lng: string; date: string }) {
const [weather, setWeather] = useState<WeatherResult | null>(null);
useEffect(() => {
fetch(`/api/weather?lat=${lat}&lng=${lng}&date=${date}&lang=en`)
.then(r => r.json())
.then(setWeather);
}, [lat, lng, date]);
if (!weather) return <div>Loading…</div>;
return (
<div className="weather-widget">
<span>{weather.main}</span>
<span>{weather.temp}°C</span>
</div>
);
}
Summary
- TREK uses Open-Meteo exclusively for weather data, requiring no API keys or authentication credentials.
- Three data windows are automatically selected: forecast API for ±16 days, archive API for past dates, and climate estimates for dates beyond 16 days.
- Intelligent caching in
weatherService.tsstores forecast data for 1 hour, current conditions for 15 minutes, and historical data for 24 hours. - REST endpoints at
/weatherand/weather/detailedprovide daily summaries and hourly data respectively. - Configuration is limited to display units (temperature and wind) managed via the Display Settings page, while the widget appears in the Day Detail panel and sidebar.
Frequently Asked Questions
Do I need an API key to use Open-Meteo with TREK?
No. TREK uses Open-Meteo's free, open-source public endpoints directly without requiring API keys or additional credentials. The integration is ready to use immediately after deployment.
How does TREK handle dates far in the future?
For dates more than 16 days in the future, TREK falls back to the climate estimate approach. It queries the Open-Meteo archive API for historical data from the prior year around the same calendar day, providing approximate conditions based on past observations.
Can I change how long weather data is cached?
The cache TTL values are defined as constants in server/src/services/weatherService.ts (TTL_FORECAST_MS, TTL_CURRENT_MS, TTL_CLIMATE_MS). To modify caching duration, you must edit these constants and redeploy the backend service. The default values optimize for Open-Meteo's rate limits and data freshness requirements.
Where does the weather widget appear in the UI?
The weather widget displays automatically at the top of the Day Detail panel when users click a day header, and as a badge in the sidebar. Visibility can be toggled via the Display Settings page without requiring code changes.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →