In this tutorial, you'll learn how to securely use an external API key stored in the Secrets Manager to call the OpenWeatherMap API. By keeping API keys safe and confidential with the Secrets Manager, you can make secure API requests without exposing sensitive information in your code.
At the end of this tutorial, you'll have a working web method that securely retrieves weather data for any city, using a stored API key.
We'll use the following steps to build this functionality:
It's important to note the following before doing this tutorial:
The code in this article was written using the following module versions:
Learn how to install npm packages in the editor or using the CLI.
This step stores your OpenWeatherMap API key securely in the Secrets Manager. At the end of this step, your API key will be safely stored and ready to use in your code.
To set up your API key:
Access the Secrets Manager using one of these methods:
Add and save the API key for the OpenWeatherMap API. For purposes of this tutorial, name this key "WeatherApiKey".
This step creates a backend web method that retrieves your API key from the Secrets Manager and uses it to call the OpenWeatherMap API. At the end of this step, you'll have a working function that can fetch weather data for any city.
To create the web method:
Create a new file called serviceModule.web.js in the site's backend folder.
Add the import statements at the top of the file:
Create an elevated function to access site secrets with proper permissions:
Create a web method function that accepts a city parameter and retrieves the API key you stored in a site secret:
Continue the function by constructing the full URL for the fetch request:
Finish the function by making the API call and returning the temperature data:
You've now successfully created a secure weather API integration using the Wix JavaScript SDK and the Secrets Manager.
You can extend this example to retrieve additional weather data or integrate it into your site's user interface.
Tip: You can test backend code in the editor without developing a frontend using Wix's functional testing feature.
Here's the complete code for your serviceModule.web.js file: