Dynamic Weather Widget
Follow these steps to integrate a dynamic weather widget into your Next.js project.
Step 1: Create an API Route
- Inside your
appfolder, create a new folder namedapi. - Inside the
apifolder, create a subfolder for your weather route (e.g.,weather). - Add a file named
route.jsinside theweatherfolder.
You can find the code for route.js here.
Make sure to change the name of the city in the code as needed:
Step 2: Add the Environment Variable
- Go to the OpenWeatherMap website, create an account, and navigate to the My API keys section in your profile to generate an API key.
It might take a few minutes for the API key to activate and start working.
- Create a file named
.envin your project folder and add the environment variable with your API key:
If you are hosting the project on Vercel:
Add the environment variable during deployment, or if the project is already deployed, add it through the project dashboard
Step 3: Create a Weather Component
- Create a folder named
componentsin your project folder. - Inside the
componentsfolder, create a file namedWeather.js. - Add the code from here to
Weather.js. - Install the dependencies by running the following command in project folder terminal:
npm install swr framer-motion @fortawesome/react-fontawesome @fortawesome/free-solid-svg-icons @fortawesome/fontawesome-svg-core
Step 4: Import and Use the Weather Component
- Import the
Weathercomponent in the file where you want to display the widget.
import Weather from './components/Weather';
- Add the
Weathercomponent in your JSX:
<Weather />
The weather widget should now be integrated and look similar to this:
It's just straight text, no css around it.


Top comments (3)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.