Forget checking the skyโtoday, every Indian developer needs to know how to fetch real-time weather data. Whether you're a student building your portfolio or a professional looking to add a modern full-stack project, creating a weather app with Next.js is a perfect, practical challenge. It combines a sleek frontend with real API integration, a skill highly valued by tech companies from TCS to Flipkart. This guide is your hands-on tutorial to build a fully functional, India-focused weather application.
Why Build a Weather App with Next.js?
In India's competitive job market, a static resume is no longer enough. Recruiters at companies like Accenture, HCL, and Zerodha look for candidates who can demonstrate practical skills with in-demand technologies. A weather app project checks multiple boxes:
- Showcases Full-Stack Ability: It involves frontend UI, backend API routes, and external service integration.
- Uses Industry-Standard Tech: Next.js is rapidly becoming the go-to React framework for its performance, SEO benefits, and simplified development.
- Solves a Real Problem: Providing accurate, localized weather information is universally useful, making your project relatable and impressive.
Building this project will give you concrete experience with asynchronous data fetching, environment variables, and responsive designโskills that can help you command a higher starting salary, often in the range of โน6-12 LPA for entry-level full-stack roles.
Prerequisites & Setup
Before we start coding, let's ensure your development environment is ready. You don't need to be an expert, but a basic understanding of JavaScript and React will be helpful.
- Install Node.js: Ensure you have Node.js (version 18 or later) installed. You can download it from the official website.
- Create a Next.js App: Open your terminal and run the following command to create a new Next.js project. We'll use the official
create-next-appwith TypeScript and Tailwind CSS for rapid styling.npx create-next-app@latest weather-app --typescript --tailwind --app - Navigate to Your Project: Move into your project directory and start the development server.
cd weather-app npm run dev - Get a Free Weather API Key: We'll use a free tier from OpenWeatherMap. Sign up at their website to get your API key. You'll use this to fetch live data.
Your basic setup is complete. Visit http://localhost:3000 to see your new Next.js app running.
Fetching Data: Integrating the Weather API
The core of our app is fetching data from an external service. We'll use OpenWeatherMap's "Current Weather Data" API. It's reliable and has a generous free tier perfect for learning.
Securing Your API Key
Never expose your API key in client-side code. In Next.js, we can securely use it in a server component or via an API route. For this tutorial, we'll fetch data directly in a Server Component.
- Create a
.env.localfile in your project root. - Add your API key to this file:
OPENWEATHER_API_KEY=your_actual_key_here - In your main page file (
app/page.tsx), you can now access this key securely viaprocess.env.OPENWEATHER_API_KEY.
Building the API Request Function
Create a utility function to handle the API call. You can make a new file lib/weather.ts.
// lib/weather.ts
export async function getWeatherData(city: string) {
const apiKey = process.env.OPENWEATHER_API_KEY;
const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${apiKey}`;
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`City not found: ${city}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error("Failed to fetch weather:", error);
return null;
}
}
This function takes a city name, makes a request to the API, and returns the data in metric units (Celsius). The error handling is crucial for a good user experience.
Building the User Interface
Now, let's create a clean, responsive UI that will display the weather information. We'll use Tailwind CSS for styling, which was included in our setup.
Creating the Search Component
Users need a way to input their city. We'll create a simple search bar. In app/page.tsx, replace the default content with a stateful client component (using "use client" directive) or manage search via URL parameters for a more SEO-friendly approach. For simplicity, we'll build a client component.
// app/components/SearchBar.tsx
"use client";
import { useState } from 'react';
export default function SearchBar({ onSearch }: { onSearch: (city: string) => void }) {
const [city, setCity] = useState('');
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (city.trim()) {
onSearch(city.trim());
setCity('');
}
};
return (
<form onSubmit={handleSubmit} className="flex gap-2 mb-8">
<input
type="text"
value={city}
onChange={(e) => setCity(e.target.value)}
placeholder="Enter city name (e.g., Mumbai, Delhi)"
className="flex-grow px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
<button
type="submit"
className="px-6 py-2 bg-blue-600 text-white font-semibold rounded-lg hover:bg-blue-700 transition"
>
Get Weather
</button>
</form>
);
}
Displaying the Weather Data
Create a component to beautifully display the data returned from our API.
// app/components/WeatherDisplay.tsx
interface WeatherDisplayProps {
data: any; // For simplicity, define a proper interface in a real project
}
export default function WeatherDisplay({ data }: WeatherDisplayProps) {
if (!data) return <p className="text-center text-gray-500">Search for a city to see weather.</p>;
return (
<div className="bg-white p-8 rounded-2xl shadow-xl max-w-md mx-auto">
<div className="text-center">
<h2 className="text-3xl font-bold text-gray-800">{data.name}, {data.sys.country}</h2>
<div className="my-6">
<img
src={`https://openweathermap.org/img/wn/${data.weather[0].icon}@4x.png`}
alt={data.weather[0].description}
className="w-32 h-32 mx-auto"
/>
<p className="text-xl text-gray-600 capitalize">{data.weather[0].description}</p>
</div>
<p className="text-6xl font-bold my-4">{Math.round(data.main.temp)}ยฐC</p>
<div className="grid grid-cols-2 gap-4 mt-6 text-gray-700">
<div className="text-center p-4 bg-gray-50 rounded-lg">
<p className="font-semibold">Feels Like</p>
<p>{Math.round(data.main.feels_like)}ยฐC</p>
</div>
<div className="text-center p-4 bg-gray-50 rounded-lg">
<p className="font-semibold">Humidity</p>
<p>{data.main.humidity}%</p>
</div>
<div className="text-center p-4 bg-gray-50 rounded-lg">
<p className="font-semibold">Wind Speed</p>
<p>{data.wind.speed} m/s</p>
</div>
<div className="text-center p-4 bg-gray-50 rounded-lg">
<p className="font-semibold">Pressure</p>
<p>{data.main.pressure} hPa</p>
</div>
</div>
</div>
</div>
);
}
Making It Production Ready
A tutorial project becomes portfolio-worthy when you add polish and essential features.
Error Handling & Loading States
Always inform the user what's happening. Add a useState for loading and error in your page component.
// Example state in your page.tsx
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
// Update your search handler to set these states before and after the API call.
Storing Favorite Cities (Optional Advanced Feature)
Use the browser's localStorage to let users save their frequently checked cities. This demonstrates state persistence and more complex client-side logic.
Deployment for Free
You can deploy this app for free and share the live link in your resume.
- Vercel: The creators of Next.js offer seamless, free deployment. Connect your GitHub repository.
- Netlify: Another excellent platform with a free tier suitable for this project.
Having a live project link is far more impactful than just describing the code.
Next Steps
You've just built a core full-stack feature. To deepen your skills and make your portfolio stand out to recruiters at Wipro or Paytm, explore more. Browse our curated list of free web development courses from platforms like freeCodeCamp and Coursera. To understand the backend concepts even better, check out our guides on Node.js and API design. Ready for your next project? Learn how to integrate payment gateways like Razorpay, a highly sought-after skill in India's startup ecosystem.
Share this article
Keep learning on UnboxCareer
Explore free courses, certificates, and career roadmaps curated for Indian students.



