Next.js API Routes Sinhala | NodeJS Backend NextJS | REST API Tutorial

ආයුබෝවන්, Developers! Next.js API Routes වලට සාදරයෙන් පිළිගනිමු!
Software Development ලෝකයේදී, අපි හැමෝටම Front-end එකයි Back-end එකයි දෙකම handle කරන්න වෙන අවස්ථා ඕන තරම් එනවා. Front-end එකට React, Vue, Angular වගේ frameworks පාවිච්චි කරලා, Back-end එකට Node.js, Python, Java වගේ දේවල් යොදාගෙන, API Calls වලින් මේ දෙක සම්බන්ධ කරන එක තමයි සාමාන්ය ක්රමය.
හැබැයි, ඔයා Next.js පාවිච්චි කරනවා නම්, මේ දෙගොල්ලන්ව එකම වහලක් යටට ගන්න පුළුවන් හරිම පහසු ක්රමයක් තියෙනවා. ඒ තමයි Next.js API Routes! 🚀
මේ tutorial එකෙන් අපි Next.js API Routes කියන්නේ මොකක්ද, ඒවා කොහොමද හදන්නේ, ඒවා test කරන්නේ සහ production ready API Routes ලියන්න වැදගත් වන best practices මොනවද කියලා සරලව සිංහලෙන් කතා කරමු. මොකද, තමන්ගේම custom backend එකක් හදාගන්න එක Next.js එක්ක හරිම ලේසියි.
අවසානයේදී, ඔයාට පුළුවන් වෙයි ඔයාගේ Next.js project එක ඇතුලෙම server-side code ලියලා, Front-end එකට අවශ්ය data ලබාදෙන API endpoints හදන්න. සූදානම්ද?
1. Next.js API Routes කියන්නේ මොකක්ද?
සරලවම කිව්වොත්, Next.js API Routes කියන්නේ Next.js project එකක් ඇතුළත, server-side code ලියන්න පුළුවන් ක්රමයක්. ඒ කියන්නේ, ඔයාට Front-end Application එකටම අමතරව, ඒකටම අදාළ Back-end API එකක් හදන්න පුළුවන්.
මේක විශේෂ වෙන්නේ, සාමාන්යයෙන් අපිට Front-end Application එකට වෙනම Backend Server එකක් දාන්න වෙන නිසා. හැබැයි Next.js API Routes එක්ක, ඔයාට පුළුවන් ඒ සියල්ලම එකම Project එකක් විදිහට maintain කරන්න.
Serverless Functions වගේ වැඩ කරන හැටි
Next.js API Routes වල තියෙන සුපිරිම feature එකක් තමයි, ඒවා Serverless Functions විදිහට deploy කරන්න පුළුවන් වීම. Vercel වගේ platforms වලට ඔයාගේ Next.js project එක deploy කරාම, API Routes automatically serverless functions බවට පත්වෙනවා.
- On-demand Execution: මේවා call කරන වෙලාවට විතරයි run වෙන්නේ.
- Automatic Scaling: Requests වැඩි වුණොත්, platform එක auto scale වෙනවා.
- Cost-effective: ඔයා ගෙවන්නේ function එක run වෙන වෙලාවට විතරයි.
මේකෙන් ඔයාට Infrastructure manage කරන එකේ බරක් නැතුව, code ලියන එකටම focus කරන්න පුළුවන්.
pages/api
Folder එකේ වැදගත්කම
Next.js වල, ඔයාගේ API Routes තියෙන්න ඕනේ pages
directory එක ඇතුළත තියෙන api
folder එකේ. Next.js එකෙන් මේ api
folder එකේ තියෙන හැම .js
, .ts
, .jsx
, .tsx
file එකක්ම API endpoint එකක් විදිහට handle කරනවා.
උදාහරණයක් විදිහට:
pages/api/hello.js
කියන file එක/api/hello
කියන endpoint එකට map වෙනවා.pages/api/users/index.js
කියන file එක/api/users
කියන endpoint එකට map වෙනවා.pages/api/products/[id].js
කියන file එක/api/products/1
,/api/products/2
වගේ dynamic endpoints වලට map වෙනවා.
මේ system එක Next.js Pages System එකට ගොඩක් සමානයි, ඒ නිසා හඳුනාගන්න හරිම ලේසියි.
2. සරල "Hello World" API Route එකක් හදමු
හරි, දැන් අපි theory ඇති, practical එකට බහිමු! මුලින්ම Next.js project එකක් නැත්නම්, මේ command එකෙන් හදාගන්න:
npx create-next-app my-nextjs-app
cd my-nextjs-app
npm run dev
දැන් ඔයාගේ project එකේ pages
folder එක ඇතුළට ගිහින්, api
කියලා අලුත් folder එකක් හදන්න. ඒ api
folder එක ඇතුළේ hello.js
කියලා අලුත් file එකක් හදලා, පහත code එක add කරන්න.
// pages/api/hello.js
export default function handler(req, res) {
// status 200 කියන්නේ request එක සාර්ථකයි කියන එකයි.
// json() method එකෙන් JavaScript object එකක් JSON string එකක් බවට පත් කරලා response එකක් විදිහට යවනවා.
res.status(200).json({ text: 'Hello World!' });
}
Code එක පැහැදිලි කිරීම:
export default function handler(req, res)
: හැම API Route file එකකමexport default
කරන function එකක් තියෙන්න ඕනේ. Next.js එකෙන් මේ function එකට parameters දෙකක් automatic provide කරනවා:req
(request) සහres
(response).req
(request object): Incoming request එක පිළිබඳ විස්තර අඩංගු වෙනවා. (HTTP method, headers, body, query parameters, etc.)res
(response object): outgoing response එක manage කරන්න භාවිතා කරනවා. (status codes, headers, sending data, etc.)res.status(200)
: HTTP status code 200 (OK) ලෙස සකසනවා. සාර්ථක requests වලට 200 return කරන එක standard practice එකක්.res.json({ text: 'Hello World!' })
: JSON format එකෙන්{ "text": "Hello World!" }
කියන object එක response එකක් විදිහට යවනවා.
Test කරමු!
දැන් ඔයාගේ browser එකේ http://localhost:3000/api/hello
කියන URL එකට යන්න. ඔයාට මෙන්න මේ වගේ output එකක් බලාගන්න පුළුවන් වෙයි:
{"text":"Hello World!"}
ඒ කියන්නේ, ඔයාගේ පළවෙනි Next.js API Route එක සාර්ථකව වැඩ! සුභ පැතුම්! 🎉
3. JSON Data එක්ක GET Request එකක් Handle කරමු
සාමාන්යයෙන් API Routes වලින් කරන්නේ Front-end එකට අවශ්ය data ලබා දෙන එකනේ. අපි දැන් users ලා ටිකකගේ list එකක් return කරන API Route එකක් හදමු.
pages/api
folder එක ඇතුළේ users.js
කියලා අලුත් file එකක් හදලා, පහත code එක add කරන්න:
// pages/api/users.js
export default function handler(req, res) {
// request එක GET method එකකින් ආවද කියලා check කරනවා.
if (req.method === 'GET') {
const users = [
{ id: 1, name: 'Kamal Perera', email: '[email protected]' },
{ id: 2, name: 'Nimal Bandara', email: '[email protected]' },
{ id: 3, name: 'Sunil Silva', email: '[email protected]' },
];
// Status 200 එක්ක users array එක JSON විදිහට යවනවා.
res.status(200).json(users);
} else {
// GET හැර වෙනත් method එකකින් ආවොත්, 405 Method Not Allowed error එකක් return කරනවා.
res.setHeader('Allow', ['GET']); // මේ endpoint එකෙන් support කරන methods මොනවද කියලා කියනවා.
res.status(405).end(`Method ${req.method} Not Allowed`);
}
}
Code එක පැහැදිලි කිරීම:
if (req.method === 'GET')
: මේක ගොඩක් වැදගත්. Next.js API Routes වලදීreq.method
පාවිච්චි කරලා, request එක ආපු HTTP method එක (GET, POST, PUT, DELETE, etc.) මොකක්ද කියලා දැනගන්න පුළුවන්. ඒ අනුව අපිට වෙනස් operations කරන්න පුළුවන්.const users = [...]
: මේක තමයි අපේ dummy data set එක. Production applications වලදී මේ data database එකකින් එනවා.res.status(200).json(users)
: කලින් වගේම, status 200 එක්ක users array එක JSON format එකෙන් response එකක් විදිහට යවනවා.else { res.setHeader('Allow', ['GET']); res.status(405).end(...) }
: මේelse
block එක හරිම වැදගත්. මොකද, අපේ API Route එක GET requests වලට විතරයි respond කරන්නේ. POST, PUT, DELETE වගේ requests ආවොත්, අපි 405 (Method Not Allowed) status code එකක් return කරන්න ඕනේ.res.setHeader('Allow', ['GET'])
එකෙන් client ට කියනවා මොන methods ද මේ endpoint එකෙන් support කරන්නේ කියලා.
Dynamic Routes
අපි හිතමු අපිට තනි user කෙනෙක්ගේ data ගන්න API එකක් ඕනේ කියලා. ඒකට අපිට Dynamic API Routes පාවිච්චි කරන්න පුළුවන්. pages/api/users/[id].js
කියලා file එකක් හදන්න:
// pages/api/users/[id].js
export default function handler(req, res) {
const { id } = req.query; // URL එකේ තියෙන id එක ගන්නවා
const users = [
{ id: 1, name: 'Kamal Perera', email: '[email protected]' },
{ id: 2, name: 'Nimal Bandara', email: '[email protected]' },
{ id: 3, name: 'Sunil Silva', email: '[email protected]' },
];
const user = users.find(u => u.id === parseInt(id)); // id එකට අදාළ user ව හොයනවා
if (user) {
res.status(200).json(user);
} else {
res.status(404).json({ message: 'User not found' }); // User ව හම්බුනේ නැත්නම් 404 error එකක් දෙනවා.
}
}
දැන් http://localhost:3000/api/users/1
කියලා ගියාම Kamal ගේ data එකත්, http://localhost:3000/api/users/99
කියලා ගියාම "User not found" message එකත් ලැබෙනවා.
4. API Routes Test කරමු සහ Debug කරමු
API Routes හැදුවට විතරක් මදි, ඒවා හරියට වැඩ කරනවද කියලා test කරන්නත්, මොනවා හරි අවුලක් ආවොත් debug කරන්නත් දැනගන්න ඕනේ.
Postman/Insomnia හෝ Browser Fetch
GET requests නම් browser එකේ URL එක type කරලා test කරන්න පුළුවන්. හැබැයි POST, PUT, DELETE වගේ requests test කරන්න Postman, Insomnia වගේ API testing tools පාවිච්චි කරන එක ගොඩක් හොඳයි.
Postman/Insomnia පාවිච්චි කරන හැටි:
- Tool එක open කරන්න.
- New Request එකක් හදන්න.
- Method එක (GET, POST, etc.) තෝරන්න.
- URL එක (උදා:
http://localhost:3000/api/users
) add කරන්න. - Body එකට data යවන්න ඕනේ නම්, Body tab එකට ගිහින් JSON format එකෙන් data add කරන්න.
- Send button එක click කරන්න. Response එක පහලින් බලාගන්න පුළුවන්.
Front-end එකෙන් fetch කරද්දී, fetch
API එක පාවිච්චි කරන්න පුළුවන්:
// Front-end එකේදී (උදා: React Component එකක)
async function getUsers() {
try {
const response = await fetch('/api/users'); // Same origin නිසා full URL එක දෙන්න ඕනේ නෑ
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Fetching users failed:', error);
}
}
getUsers();
Errors Debug කරන හැටි
API Routes වලදී errors එන එක සාමාන්ය දෙයක්. ඒවා debug කරගන්න මේ Tips පාවිච්චි කරන්න:
console.log()
: Server-side code එකේදීconsole.log()
භාවිතා කරන්න. මේවා ඔයාගේ Next.js dev server එක run වෙන terminal එකේ print වෙනවා. Client-side console එකේ print වෙන්නේ නෑ, මතක තියාගන්න.- Next.js Terminal Output: Next.js development server එකේ terminal එකේ errors පෙන්නනවා. Stack trace එක බලලා error එක ආපු තැන හොයාගන්න පුළුවන්.
- Browser Network Tab: F12 (Developer Tools) open කරලා Network tab එකට ගිහින්, ඔයාගේ API call එක තෝරලා, Response, Headers, Preview tabs බලන්න. Error messages, status codes, සහ server එකෙන් එන data මේකෙන් බලාගන්න පුළුවන්.
- Use
try...catch
blocks: Database calls, external API calls වගේ asynchronous operations වලදීtry...catch
block එකක් පාවිච්චි කරන්න. මේකෙන් unexpected errors අල්ලගෙන client ට friendly error message එකක් දෙන්න පුළුවන්.
// pages/api/data.js
export default async function handler(req, res) {
try {
// Simulate a database call or external API call
const data = await new Promise((resolve, reject) => {
setTimeout(() => {
// throw new Error('Something went wrong with the database!'); // uncomment to test error
resolve({ message: 'Data fetched successfully' });
}, 1000);
});
res.status(200).json(data);
} catch (error) {
console.error('API Error:', error); // Server-side console log
res.status(500).json({ message: 'Internal Server Error', error: error.message });
}
}
5. Best Practices සහ පොදු ගැටළු
හොඳ API Routes ලියන්න නම්, මේ best practices follow කරන එක වැදගත්.
Single Responsibility Principle
හැම API Route එකක්ම එක් දෙයක් පමණක්, හොඳින් කරන්න ඕනේ. උදාහරණයක් විදිහට:
/api/users
: Users manage කරන්න./api/products
: Products manage කරන්න./api/auth/login
: User login කරන්න.
එකම API Route එකක් ඇතුළේ users, products, orders වගේ හැම දෙයක්ම කරන්න හදන්න එපා. ඒකෙන් code එක maintain කරන්න අමාරු වෙනවා, errors හොයන්න අමාරු වෙනවා.
HTTP Status Codes වල වැදගත්කම
ඔයාගේ API එකෙන් දෙන response එකේ status code එක හරිම වැදගත්. Client ට දැනගන්න පුළුවන් request එක සාර්ථකද, නැත්නම් මොකක් හරි අවුලක්ද කියලා.
200 OK
: Request එක සාර්ථකයි. (GET, PUT, PATCH සාමාන්යයෙන්)201 Created
: Resource එකක් සාර්ථකව හදලා තියෙනවා. (POST)204 No Content
: Request එක සාර්ථකයි, හැබැයි response body එකක් නෑ. (DELETE)400 Bad Request
: Client request එකේ මොකක් හරි වැරැද්දක්. (නැති fields, වැරදි data type)401 Unauthorized
: Client ට authentication credential නෑ.403 Forbidden
: Client ට access කරන්න අවසර නෑ.404 Not Found
: Resource එක හොයාගන්න බෑ.405 Method Not Allowed
: Request එක ආපු HTTP method එක මේ endpoint එකෙන් support කරන්නේ නෑ.500 Internal Server Error
: Server එකේ මොකක් හරි අවුලක්. (Server-side exception)
මේ status codes නිවැරදිව පාවිච්චි කරන එකෙන් API එක client-friendly වෙනවා.
Data Validation
Client එකෙන් එවන data validate කරන එක ගොඩක් වැදගත්. උදාහරණයක් විදිහට, user register කරන POST request එකකට email
එකක් එවනවා නම්, ඒක valid email format එකක්ද කියලා check කරන්න ඕනේ. මේකට yup
, joi
වගේ libraries පාවිච්චි කරන්න පුළුවන්.
// pages/api/register.js
import * as Yup from 'yup'; // npm install yup
const userSchema = Yup.object().shape({
name: Yup.string().required('Name is required'),
email: Yup.string().email('Invalid email').required('Email is required'),
password: Yup.string().min(6, 'Password must be at least 6 characters').required('Password is required'),
});
export default async function handler(req, res) {
if (req.method === 'POST') {
try {
const userData = await userSchema.validate(req.body, { abortEarly: false });
// Database operations or further logic here
res.status(201).json({ message: 'User registered successfully', user: userData });
} catch (error) {
if (error instanceof Yup.ValidationError) {
// Validation errors
return res.status(400).json({ message: 'Validation failed', errors: error.errors });
}
console.error('Registration Error:', error);
res.status(500).json({ message: 'Internal Server Error' });
}
} else {
res.setHeader('Allow', ['POST']);
res.status(405).end(`Method ${req.method} Not Allowed`);
}
}
Error Handling
API routes වලදී මොනවා හරි අවුලක් ආවොත්, ඒක client ට friendly විදිහට පෙන්නන්න ඕනේ. Database එකේ error එකක් ආවොත් ඒක client ට කෙලින්ම යවන්නේ නැතුව, Internal Server Error
වගේ generic message එකක් එක්ක status 500 return කරන එක තමයි හොඳ.
Security
ඔයාගේ API routes වල sensitive information direct return කරන්නේ නැති වෙන්න වග බලාගන්න. (උදා: user passwords, API keys). Input sanitization සහ validation හරියට කරන්න. Production environments වලදී Rate Limiting, CORS settings වගේ දේවල් ගැනත් හිතන්න ඕනේ.
අවසන් වශයෙන්
Next.js API Routes කියන්නේ Front-end Developers ලාට තමන්ගේ applications වලට අවශ්ය backend functionalities හදාගන්න පුළුවන්, හරිම බලවත් සහ පහසු tool එකක්. Serverless functions විදිහට deploy කරන්න පුළුවන් වීම නිසා, ඔයාට infrastructure ගැන හිතන්නේ නැතුව, code එකටම focus කරන්න පුළුවන්.
අපි මේ tutorial එකෙන්, සරල "Hello World" API Route එකක් හදන හැටි, JSON data handle කරන හැටි, test කරන හැටි සහ debug කරන හැටි ඉගෙන ගත්තා. ඒ වගේම, හොඳ API Routes ලියන්න වැදගත් වන best practices (Single Responsibility, HTTP Status Codes, Data Validation) ගැනත් කතා කරා.
දැන් ඔයාට හොඳ අවබෝධයක් තියෙනවා Next.js API Routes ගැන. මේ knowledge එක පාවිච්චි කරලා, ඔයාගේ Next.js projects වලට අලුත් functionalities add කරන්න උත්සාහ කරන්න. Database එකක් එක්ක connect වෙලා real data manage කරන්න උත්සාහ කරන්න.
මතක තියාගන්න, practice makes perfect! 💪
ඔයාගේ අත්දැකීම් මොන වගේද? මේ tutorial එක ප්රයෝජනවත් වුණාද? පහලින් comment එකක් දාලා කියන්න. ඔයා හදන project එකක API Routes පාවිච්චි කරලා මොන වගේ දෙයක්ද හැදුවේ?
Happy coding! 😊