Next.js API Routes: External Services Integration | Sinhala Guide

ආයුබෝවන් Developer යාළුවනේ!
අද අපි කතා කරන්න යන්නේ Next.js ecosystem එකේ තියෙන හරිම වැදගත්, ඒ වගේම ගොඩක් දෙනෙක්ට ප්රයෝජනවත් වෙන topic එකක් ගැන. ඒ තමයි Next.js API Routes භාවිතයෙන් external services එහෙමත් නැත්නම් පිටතින් තියෙන APIs, databases වගේ දේවල් එක්ක connect වෙන්නේ කොහොමද කියන එක. ගොඩක් වෙලාවට අපිට client-side එකෙන් කෙලින්ම third-party APIs call කරන්න බැරි අවස්ථා එනවා. සමහර වෙලාවට sensitive data, API keys වගේ දේවල් client-side එකට expose කරන්න බැරි නිසා.
හොඳයි එහෙනම්, අපි බලමු මේ Next.js API Routes කියන්නේ මොකක්ද, ඒවා කොහොමද external services එක්ක සම්බන්ධ වෙන්නේ, security එකට අපි මොනවද කරන්න ඕනේ, ඒ වගේම හොඳම practice (best practices) මොනවද කියන එක.
මේ guide එකෙන් ඔයාට මොනවද ඉගෙන ගන්න පුළුවන්?
- Next.js API Routes වල මූලිකාංග සහ ඒවා භාවිත කරන ආකාරය.
- Third-party APIs (උදා: Weather API) Next.js API Route එකක් ඇතුලෙන් call කරලා data fetch කරන හැටි.
- API Keys සහ වෙනත් sensitive information environment variables හරහා ආරක්ෂිතව කළමනාකරණය කරන හැටි.
- External API calls වලදී ඇතිවන errors හසුරුවන (error handling) සහ troubleshoot කරන ආකාරය.
- Next.js API Routes භාවිතයේදී අනුගමනය කළ යුතු best practices සහ පොදු ගැටළු වලට විසඳුම්.
එහෙනම්, වැඩි වෙලා යවන්නේ නැතුව අපි වැඩේට බහිමු!
Next.js API Routes වල මූලිකාංග (Fundamentals of Next.js API Routes)
Next.js කියන්නේ React framework එකක් වුණත්, ඒක client-side rendering වලට විතරක් සීමා වෙන්නේ නැහැ. Next.js අපිට server-side logic ලියන්න පුළුල් හැකියාවක් දෙනවා, ඒකට තමයි API Routes යොදා ගන්නේ. ඔයාට React වලින් frontend එක හදාගෙනම, ඒ project එකේම පොඩි backend එකකුත් හදාගන්න පුළුවන් මේ API Routes භාවිතයෙන්.
API Routes කියන්නේ මොනවද?
සරලවම කියනවා නම්, Next.js API Route එකක් කියන්නේ server-side JavaScript function එකක්. මේවා files විදියට pages/api
directory එක ඇතුලේ define කරනවා. උදාහරණයක් විදියට, pages/api/hello.js
කියලා file එකක් හදුවොත්, ඔයාට ඒක /api/hello
කියන endpoint එකෙන් access කරන්න පුළුවන්.
මේ API Routes වලට incoming HTTP requests (GET, POST, etc.) handle කරන්නත්, database එකක් එක්ක interact වෙන්නත්, external APIs call කරන්නත්, ඒ වගේම responses (JSON, XML, text) return කරන්නත් පුළුවන්.
ඇයි API Routes භාවිතා කරන්නේ?
- Backend Logic: client-side එකට කරන්න බැරි (හෝ නොකළ යුතු) operations (e.g., database queries, sending emails, processing payments) කරන්න.
- API Key Hiding: sensitive API keys client-side JavaScript එකට expose නොකර, server-side එකේ තියාගෙන external APIs call කරන්න.
- Data Fetching & Transformation: external API එකකින් data අරගෙන, frontend එකට අවශ්ය විදියට transform කරලා යවන්න.
- Simplicity: සම්පූර්ණ වෙනම backend project එකක් හදන්නේ නැතුව, Next.js project එක ඇතුලෙන්ම API endpoints හදාගන්න පුළුවන්.
මූලික API Route එකක ව්යුහය
pages/api
ෆෝල්ඩර් එක ඇතුලේ තියෙන හැම JavaScript file එකක්ම API endpoint එකක් විදියට serve වෙනවා. ඒ file එකේ export default
කරන function එකට request (req
) සහ response (res
) objects දෙකක් ලැබෙනවා.
මෙන්න සරල pages/api/hello.js
API Route එකක්:
// pages/api/hello.js
export default function handler(req, res) {
res.status(200).json({ name: 'Hello from Next.js API Route!' });
}
මේක /api/hello
කියන URL එකට GET request එකක් යැව්වම { "name": "Hello from Next.js API Route!" }
කියන JSON response එක දෙනවා. Request methods (GET, POST, PUT, DELETE) handle කරන්නත් req.method
භාවිත කරන්න පුළුවන්.
External Services Connect කිරීම (Connecting External Services)
හොඳයි, දැන් අපි Next.js API Route එකක් ඇතුලෙන් external service එකක්, විශේෂයෙන්ම third-party API එකක්, call කරන්නේ කොහොමද කියලා බලමු. මේ සඳහා අපි ජනප්රිය OpenWeatherMap API එක උදාහරණයට ගමු.
මුලින්ම ඔයාට OpenWeatherMap API key එකක් අවශ්යයි. ඔයාට openweathermap.org/api එකට ගිහින් නොමිලේම account එකක් හදාගෙන API key එකක් ලබාගන්න පුළුවන්.
අපේ වැඩේ තමයි, Next.js API Route එකක් හදලා ඒකෙන් user කෙනෙක් දෙන city එකකට අදාල weather data ටික OpenWeatherMap API එකෙන් fetch කරලා, ඒ data frontend එකට return කරන එක.
පියවර 1: API Route එක හදමු
pages/api
directory එක ඇතුලේ weather.js
කියලා අලුත් file එකක් හදන්න.
පියවර 2: External API එකට Request එක යවමු
අපි මේකට JavaScript වල built-in fetch
API එක හෝ axios
වගේ library එකක් use කරන්න පුළුවන්. මේ example එකට අපි fetch
use කරමු.
මෙන්න pages/api/weather.js
file එකේ code එක:
// pages/api/weather.js
export default async function handler(req, res) {
// HTTP GET request එකක්ද කියලා check කරමු
if (req.method !== 'GET') {
return res.status(405).json({ message: 'Method Not Allowed' });
}
// Query parameters වලින් city එක ලබාගමු (උදා: /api/weather?city=Colombo)
const { city } = req.query;
if (!city) {
return res.status(400).json({ message: 'City parameter is required' });
}
// **සැ.යු.:** මේ API_KEY එක දැන් මෙහෙම hardcode කරන එක හොඳ නැහැ.
// ඊළඟ section එකේදී අපි මේක environment variables වලට දාන හැටි බලමු.
const OPENWEATHER_API_KEY = 'YOUR_OPENWEATHER_API_KEY'; // **මේක ඔයාගේම key එකෙන් replace කරන්න**
const OPENWEATHER_BASE_URL = 'http://api.openweathermap.org/data/2.5/weather';
try {
const response = await fetch(
`${OPENWEATHER_BASE_URL}?q=${city}&appid=${OPENWEATHER_API_KEY}&units=metric`
);
if (!response.ok) {
// External API එකෙන් error එකක් ආවොත්
const errorData = await response.json();
return res.status(response.status).json({ message: errorData.message || 'Error fetching weather data' });
}
const weatherData = await response.json();
// Frontend එකට අවශ්ය විදියට data transform කරන්න පුළුවන්
const formattedWeatherData = {
city: weatherData.name,
temperature: weatherData.main.temp,
description: weatherData.weather[0].description,
icon: weatherData.weather[0].icon,
humidity: weatherData.main.humidity,
windSpeed: weatherData.wind.speed,
};
res.status(200).json(formattedWeatherData);
} catch (error) {
console.error('Error in API Route:', error);
res.status(500).json({ message: 'Internal Server Error', error: error.message });
}
}
මේ code එකේ වෙන්නේ මොකක්ද?
if (req.method !== 'GET')
: මේකෙන් බලන්නේ request එක GET එකක්ද කියලා. නැත්නම් 405 Method Not Allowed error එකක් return කරනවා.const { city } = req.query;
: URL එකේ?city=Colombo
වගේ query parameter එකෙන්city
එක ලබාගන්නවා.if (!city)
:city
parameter එක නැත්නම් 400 Bad Request error එකක් return කරනවා.fetch(...)
: OpenWeatherMap API URL එකට request එකක් යවනවා. ඒකටcity
එක සහAPI_KEY
එක join කරනවා.&units=metric
දාලා temperature එක Celsius වලින් ගන්නවා.if (!response.ok)
: External API එකෙන් successful response (2xx status) එකක් නොලැබුණොත්, error message එක අරගෙන ඒක client එකට යවනවා.const weatherData = await response.json();
: Successful response එක JSON format එකට parse කරනවා.const formattedWeatherData = {...};
: අපි මේ data ටික frontend එකට display කරන්න අවශ්ය විදියට restructure කරනවා.res.status(200).json(formattedWeatherData);
: සාර්ථකව format කරපු weather data එක client එකට JSON විදියට යවනවා.catch (error)
: Network errors හෝ වෙනත් නොසිතූ දේවල් සිදුවුණොත්, ඒවා handle කරලා 500 Internal Server Error එකක් client එකට යවනවා.
දැන් ඔයාට Postman, Insomnia වගේ tool එකකින් හරි, browser එකෙන් හරි http://localhost:3000/api/weather?city=Colombo
(ඔයාගේ Next.js app එක running නම්) වගේ call එකක් යවලා මේක test කරන්න පුළුවන්.
API Key Management සහ Security (API Key Management and Security)
අපේ කලින් example එකේදී අපි API key එක code එක ඇතුලේ කෙලින්ම ලිව්වා (hardcoded). මේක කිසිසේත්ම හොඳ පුරුද්දක් නෙමෙයි! ඔයාගේ code එක public repository එකකට ගියොත්, ඔයාගේ API key එකත් expose වෙනවා. ඒකෙන් security අවදානම් ගොඩක් ඇතිවෙන්න පුළුවන්. API key එකක් කියන්නේ ඔයාගේ account එකට access එකක් වගේ දෙයක්, ඒක ආරක්ෂා කරගන්න එක අනිවාර්යයි.
Next.js වලදී මේ වගේ sensitive information ආරක්ෂිතව තියාගන්න අපි Environment Variables භාවිතා කරනවා.
Environment Variables කියන්නේ මොනවද?
මේවා කියන්නේ ඔයාගේ application එක run වෙන environment එකට අදාලව define කරන variables. Next.js වලදී මේවාට .env.local
කියන file එක භාවිතා කරන්න පුළුවන්.
පියවර 1: .env.local
file එක හදමු
ඔයාගේ Next.js project එකේ root directory එකේ (package.json
තියෙන තැන) .env.local
කියලා file එකක් හදන්න.
පියවර 2: API key එක .env.local
එකට දාමු
ඒ file එක ඇතුලට ඔයාගේ OpenWeatherMap API key එක මේ විදියට එකතු කරන්න:
OPENWEATHER_API_KEY=ඔයාගේ_ඇත්ත_API_KEY_එක_මෙතන_දාන්න
වැදගත්: .env.local
file එක .gitignore
file එකට එකතු කරන්න, එතකොට ඔයාගේ API key එක Git repository එකට upload වෙන්නේ නැහැ. .gitignore
එකේ මේ line එක තියෙනවද කියලා බලන්න:
.env.local
පියවර 3: API Route එකේ Environment Variable එක access කරමු
දැන් අපේ pages/api/weather.js
file එකේ, අපි hardcode කරපු API key එක වෙනුවට process.env.OPENWEATHER_API_KEY
කියන එක භාවිතා කරන්න පුළුවන්:
// pages/api/weather.js
// ... අනෙකුත් code ...
export default async function handler(req, res) {
// ... අනෙකුත් validations ...
// Environment variable එකෙන් API key එක ලබාගනිමු
const OPENWEATHER_API_KEY = process.env.OPENWEATHER_API_KEY;
const OPENWEATHER_BASE_URL = 'http://api.openweathermap.org/data/2.5/weather';
if (!OPENWEATHER_API_KEY) {
return res.status(500).json({ message: 'API key not configured' });
}
try {
const response = await fetch(
`${OPENWEATHER_BASE_URL}?q=${city}&appid=${OPENWEATHER_API_KEY}&units=metric`
);
// ... අනෙකුත් code ...
} catch (error) {
// ... error handling ...
}
}
දැන් ඔයාගේ API key එක ආරක්ෂිතයි! Next.js server-side code එක ඇතුලෙන් process.env.YOUR_VARIABLE_NAME
විදියට environment variables වලට access කරන්න පුළුවන්. Client-side එකෙන් access කරන්න ඕනේ නම් NEXT_PUBLIC_
prefix එක භාවිතා කරන්න ඕනේ, හැබැයි sensitive data client-side එකට කිසිම හේතුවකට යවන්න එපා!
Error Handling සහ Troubleshooting (Error Handling and Troubleshooting)
External APIs එක්ක වැඩ කරනකොට errors එන එක සාමාන්ය දෙයක්. Network issues, incorrect API keys, rate limits, invalid parameters වගේ දේවල් නිසා errors එන්න පුළුවන්. මේවා නිවැරදිව handle කරන එක application එකේ robustness එකට (කිසිම බාධාවකින් තොරව වැඩ කිරීමට ඇති හැකියාවට) ඉතාම වැදගත්.
Error Handling strategies
- Meaningful Error Messages: Client එකට යන error messages වල වැඩි sensitive details නොයවා, හැබැයි ප්රශ්නේ මොකක්ද කියලා තේරෙන විදියට දෙන්න. Console එකට complete error details log කරන්න.
Check HTTP Status Codes: External API response එකේ HTTP status code එක check කරන්න. 200 OK
කියන්නේ සාර්ථකයි, හැබැයි 400 Bad Request
, 401 Unauthorized
, 403 Forbidden
, 404 Not Found
, 429 Too Many Requests
, 500 Internal Server Error
වගේ codes ගැන අවධානය යොමු කරන්න.
const response = await fetch(url);
if (!response.ok) { // response.ok කියන්නේ status code එක 200-299 අතර නම් true
const errorData = await response.json();
console.error(`External API error: ${response.status} - ${errorData.message}`);
return res.status(response.status).json({ message: errorData.message || 'External service error' });
}
Try-Catch Blocks: JavaScript වල asynchronous operations වලදී ඇතිවන exceptions අල්ලගන්න try...catch
block එක අනිවාර්යයි. Network failures වගේ දේවල් මෙයින් handle වෙනවා.
try {
// external API call එක මෙතන
} catch (error) {
console.error('API call failed:', error);
res.status(500).json({ message: 'Failed to fetch data' });
}
Troubleshooting Tips
- Console Logs: API Route එක ඇතුලේ
console.log()
statements දාලා request parameters, API response, errors වගේ දේවල් බලන්න. - External Tools: Postman, Insomnia, curl වගේ tools වලින් external API එකට කෙලින්ම request යවලා බලන්න. ඒකෙන් ඔයාගේ API Route එකේ ප්රශ්නයක්ද, නැත්නම් external API එකේ ප්රශ්නයක්ද කියලා තේරුම් ගන්න පුළුවන්.
- Next.js Dev Server Console: Next.js development server එක run වෙන terminal එකේ ඔයාගේ
console.log()
outputs ටික බලාගන්න පුළුවන්.
Retries for Transient Failures
සමහර වෙලාවට network glitches, momentary service outages වගේ දේවල් නිසා external API calls fail වෙන්න පුළුවන්. මේවා transient failures කියලා හඳුන්වනවා. මේ වගේ අවස්ථාවලදී, පොඩි වෙලාවක් ඉඳලා call එක ආයෙත් කරන්න උත්සාහ කරන එක (retry) හොඳ practice එකක්. අපි exponential backoff
එක්ක retry logic එකක් implement කරමු.
// pages/api/weather.js (Error Handling සහ Retries සමඟ)
export default async function handler(req, res) {
if (req.method !== 'GET') {
return res.status(405).json({ message: 'Method Not Allowed' });
}
const { city } = req.query;
if (!city) {
return res.status(400).json({ message: 'City parameter is required' });
}
const OPENWEATHER_API_KEY = process.env.OPENWEATHER_API_KEY;
const OPENWEATHER_BASE_URL = 'http://api.openweathermap.org/data/2.5/weather';
if (!OPENWEATHER_API_KEY) {
console.error('OPENWEATHER_API_KEY is not set in environment variables.');
return res.status(500).json({ message: 'API key not configured' });
}
const MAX_RETRIES = 3;
let attempts = 0;
while (attempts < MAX_RETRIES) {
try {
const response = await fetch(
`${OPENWEATHER_BASE_URL}?q=${city}&appid=${OPENWEATHER_API_KEY}&units=metric`
);
if (!response.ok) {
// 5xx errors (server errors) හෝ 429 (rate limit) වගේ errors retry කරන්න පුළුවන්.
// 400, 401, 404 වගේ errors retry කරන එක තේරුමක් නැහැ.
if (response.status >= 500 || response.status === 429) {
console.warn(`Attempt ${attempts + 1} failed for ${city}. Retrying...`);
attempts++;
const delay = Math.pow(2, attempts) * 1000; // Exponential backoff: 2s, 4s, 8s
await new Promise(resolve => setTimeout(resolve, delay));
continue; // ඊළඟ attempt එකට යන්න
}
// Other client errors (4xx) should not be retried
const errorData = await response.json();
console.error(`External API error: ${response.status} - ${errorData.message}`);
return res.status(response.status).json({ message: errorData.message || 'Error fetching weather data' });
}
const weatherData = await response.json();
const formattedWeatherData = {
city: weatherData.name,
temperature: weatherData.main.temp,
description: weatherData.weather[0].description,
icon: weatherData.weather[0].icon,
humidity: weatherData.main.humidity,
windSpeed: weatherData.wind.speed,
};
return res.status(200).json(formattedWeatherData);
} catch (error) {
console.error(`Attempt ${attempts + 1} failed for ${city} due to network/fetch error:`, error);
attempts++;
if (attempts < MAX_RETRIES) {
const delay = Math.pow(2, attempts) * 1000;
await new Promise(resolve => setTimeout(resolve, delay));
} else {
return res.status(500).json({ message: 'Internal Server Error after multiple retries', error: error.message });
}
}
}
// Max retries exhausted
return res.status(500).json({ message: 'Failed to fetch data after multiple retries.' });
}
මේ code එකේ while (attempts < MAX_RETRIES)
loop එකක් භාවිතා කරලා, error එකක් ආවොත්, ඒක retry කරන්න පුළුවන් වර්ගයේ error එකක්ද කියලා බලලා, setTimeout
එකක් දාලා පොඩි වෙලාවක් ඉඳලා ආයෙත් call එක කරනවා. Math.pow(2, attempts) * 1000
කියන්නේ exponential backoff එකක්, ඒ කියන්නේ හැම retry එකකදීම ප්රමාද වන කාලය දෙගුණ වෙනවා. මේක server එකට එකපාරටම overload නොවෙන්න උදව් වෙනවා.
Best Practices සහ පොදු ගැටළු (Best Practices and Common Issues)
Next.js API Routes වලින් external services එක්ක වැඩ කරනකොට ඔයාගේ application එක efficient, reliable, සහ secure විදියට තියාගන්න පුළුවන් best practices කීපයක් තියෙනවා.
Best Practices
- Environment Variables භාවිතය: API keys, database credentials, third-party service URLs වගේ sensitive දේවල් හැමවිටම
.env.local
(development වලට) සහ deployment environment variables (production වලට) වල තියන්න. ඒවා code repository එකට යවන්න එපා! - Data Validation: External API එකකට යවන request body/query parameters validate කරන්න. ඒ වගේම external API එකකින් එන response data එකත් validate කරන්න. මේකට Zod වගේ library එකක් use කරන්න පුළුවන්. මේකෙන් අනවශ්ය data හෝ unexpected data types නිසා ඇතිවන errors වළක්වා ගන්න පුළුවන්.
- Caching: External API එකකින් නිතරම ඉල්ලන, හැබැයි නිතරම update නොවන data තියෙනවා නම්, ඒ data cache කරන්න. මේකෙන් external API එකට යන request ප්රමාණය අඩු කරලා, response time එක වැඩි කරගන්න පුළුවන්. Redis වගේ in-memory cache එකක් හෝ Next.js වලම තියෙන
stale-while-revalidate
(SWR) වගේ strategies යොදා ගන්න පුළුවන්. - Rate Limiting: ගොඩක් external APIs වල request limit එකක් තියෙනවා (e.g., requests per minute/hour). ඔයා මේ limits වලට අනුකූලව වැඩ කරන්න ඕනේ. එහෙම නැත්නම් ඔයාගේ API key එක block වෙන්න පුළුවන්. API documentation එක බලලා මේ limits ගැන දැනුවත් වෙන්න.
- Abstraction: External API calls ටික separate utility functions හෝ service files වලට දාලා තියන්න (e.g.,
lib/openweather.js
). මේකෙන් code එක clean වෙනවා වගේම, test කරන්නත් පහසු වෙනවා.
Timeouts: External API එකකින් response එකක් එන්න වැඩි වෙලාවක් ගත්තොත්, ඔයාගේ server එකත් block වෙන්න පුළුවන්. ඒ නිසා fetch
request වලට timeout එකක් සෙට් කරන්න. AbortController
භාවිතයෙන් මේක කරන්න පුළුවන්.
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 5000); // 5 seconds timeout
try {
const response = await fetch(url, { signal: controller.signal });
clearTimeout(timeoutId);
// ... handle response
} catch (error) {
if (error.name === 'AbortError') {
console.error('Request timed out');
// ... handle timeout error
}
// ... handle other errors
}
පොදු ගැටළු (Common Issues)
- CORS Errors: සමහර වෙලාවට ඔයාගේ frontend එකෙන් කෙලින්ම external API එකකට call කරාම Cross-Origin Resource Sharing (CORS) error එන්න පුළුවන්. Next.js API Routes වලදී මේක ප්රශ්නයක් වෙන්නේ නැහැ, මොකද API Route එක server-side run වෙන නිසා. හැබැයි ඔයාගේ API Route එකේ තියෙන data client-side එකට access කරන්න ඕනේ නම්, Next.js API Route එකෙන් CORS headers send කරන්න වෙනවා. (
res.setHeader('Access-Control-Allow-Origin', '*')
වගේ). - Misconfigured Environment Variables:
.env.local
file එක වැරදි තැනක තියෙනවා නම්, variable name එකේ spelling mistake එකක් තියෙනවා නම්, නැත්නම් Next.js dev server එක restart කරලා නැත්නම්,process.env
එකෙන් key එකට access කරන්න බැරිවෙන්න පුළුවන්. - Asynchronous Logic Issues:
async/await
හරියට භාවිතා නොකිරීම, Promises handle නොකිරීම වගේ දේවල් නිසා code එක බිඳ වැටෙන්න පුළුවන්. හැමවිටමawait
keyword එකasync
function ඇතුලේදී Promises එක්ක භාවිතා කරන්න.
නිගමනය (Conclusion)
හොඳයි Developer යාළුවනේ, අපි Next.js API Routes භාවිතයෙන් external services connect කරන ආකාරය, API keys ආරක්ෂිතව කළමනාකරණය කරන හැටි, errors handle කරන හැටි, ඒ වගේම application එක robust කරගන්න අවශ්ය best practices ගැන විස්තරාත්මකව කතා කළා.
Next.js API Routes කියන්නේ ඔයාගේ frontend-focused project වලට server-side capabilities එකතු කරන්න තියෙන ඉතාම ප්රබල මෙවලමක්. මේවා හරියට භාවිතා කිරීමෙන් ඔයාගේ application වල ආරක්ෂාව, කාර්ය සාධනය (performance), සහ නඩත්තුව (maintainability) සැලකිය යුතු ලෙස වැඩි දියුණු කරගන්න පුළුවන්.
දැන් ඔයාට පුළුවන් මේ concepts ඔයාගේම Next.js project වලට apply කරලා බලන්න. Weather API එක වෙනුවට වෙනත් public API (උදා: Chuck Norris Jokes API, public currency converter API) එකක් call කරලා බලන්න. Caching, advanced error handling, හෝ data validation libraries වගේ දේවල් explore කරන්න.
ඔයාගේ අත්දැකීම් කොහොමද? ඔයා මේ concepts implement කරනකොට මුහුණ දුන් ගැටළු මොනවද? පහලින් comment section එකේ ඔයාගේ අදහස් බෙදාගන්න. ඔයාගේ project වලට සුබ පැතුම්!