DEV Community

Cover image for Nuxt Server-Side Proxy for Open Weather Api
Hasibul Alam Ratul
Hasibul Alam Ratul

Posted on

Nuxt Server-Side Proxy for Open Weather Api

Intro

A common problem when using open weather api is Cross-Origin Resource Sharing (CORS) issues. This typically happens when you're trying to make an API call from a web application running in a browser, and the browser blocks the request because the API server does not include the necessary CORS headers in its response. The quickest fix is to add a cors header however, as we do not control the api server we can not add a cors header even if we wanted too.

Solutions

There are many ways of resolving this issue but below two are the ones I tested and have worked for me.

CORS Anywhere

One service I found that worked for me was CORS Anywhere which adds CORS headers to the proxied request. To use it, we will need to append the hosted NodeJs server url before the api url. Keep in mind that the public instance has a limited number of requests, so it's a good idea to host your own using the CORS Anywhere repository.

For example:

https://cors-anywhere.herokuapp.com/http://api.openweathermap.org/data/2.5/weather?q=london&APPID={apikey}

Enter fullscreen mode Exit fullscreen mode

Personally, for small projects, I prefer not to juggle multiple codebases (maybe I'm just a bit lazy 🀣). With NuxtJs, you can get everything done with less fuss and even add some extra features. I'm sure you can do the same with NextJs and serverless functions.

Nuxt Server-Side Proxy

To start create a file in the api folder on nuxt server directory. I named it weather.js. As nuxt has a file based routing the endpoint will be /api/weather

File structure

root
β”œβ”€ server
β”‚  β”œβ”€ api
β”‚  β”‚  └─ weather.js
Enter fullscreen mode Exit fullscreen mode

Server Side

In the code snippet below, I'm setting up a basic API handler to get weather data using the fetch function. If you're more into axios, feel free to swap it in instead.

import { getQuery } from 'h3';

export default defineEventHandler(async (event) => {
  // Extract query parameters from the event using getQuery
  const { query } = getQuery(event);

  // Access runtime configuration to retrieve the API key for OpenWeatherMap
  const config = useRuntimeConfig();
  const apiKey = config.private.openWeatherApiKey;

  // Construct the API URL for the weather request
  const apiUrl = `https://api.openweathermap.org/data/2.5/${query}&units=metric&appid=${apiKey}`;

  try {
    const response = await fetch(apiUrl);
    if (!response.ok) {
      return {
        statusCode: response.status,
        body: { message: response.statusText },
      };
    }
    const data = await response.json();
    return {
      status: 200,
      message: 'Weather fetched successfully',
      data,
    };
  } catch (error) {
    return {
      statusCode: 500,
      body: { message: 'Internal Server Error' },
    };
  }
});
Enter fullscreen mode Exit fullscreen mode

One cool thing I noticed about using this setup is that it hides both the API URL and the API key.

Original URL: https://api.openweathermap.org/data/2.5/weather?q=London&units=metric&appid=${apiKey}
Masked URL: https://atmosdev.netlify.app/api/weather?query=weather?q=London
Enter fullscreen mode Exit fullscreen mode

So, not only does it simplify the URL, but it also keeps your API key under wraps.

Client Side

Now, all you need to do is pass in the query and fetch the data on the client side, and you're good to go!

const getWeather = async (event) => {
  try {
    const response = await $fetch(`/api/weather?query=London`);
    if (response.status === 200) {
      weather.value = response.data;
    } else {
      console.error("No data returned from the API");
    }
  } catch (error) {
    console.error("Error fetching weather data:", error);
  }
};
Enter fullscreen mode Exit fullscreen mode

Here is the API response data
API response

Deployed App

https://atmosapp.netlify.app/

Top comments (0)