Next.js API Routes ගැන සරලව සිංහලෙන් ඉගෙන ගන්න | Sinhala Tutorial

Next.js API Routes ගැන සරලව සිංහලෙන් ඉගෙන ගන්න | Sinhala Tutorial

ආයුබෝවන් යාළුවනේ! Next.js API Routes ගැන කතා කරමු

අද කාලේ web development field එකේ ඉන්න කෙනෙක්ට Next.js කියන්නේ නැතුවම බැරි framework එකක්. විශේෂයෙන්ම React එක්ක වැඩ කරනවා නම් Next.js වල තියෙන server-side rendering, static site generation වගේ features නිසා project එකක performance එකයි, SEO එකයි ගොඩක් වැඩි කරගන්න පුළුවන්. ඒත් Next.js කියන්නේ வெறும் frontend framework එකක් විතරක් නෙවෙයි. Backend logic ටිකක් ලියන්න ඕන වුණාම ඒකට වෙනම Node.js server එකක්, Express server එකක් හදාගන්නේ නැතුව Next.js project එක ඇතුලෙම backend code ලියන්න අපිට පුළුවන් Next.js API Routes හරහා.

අද අපි බලමු මේ Next.js API Routes කියන්නේ මොනවද කියලා, කොහොමද ඒවා හදාගන්නේ, සහ practical උදාහරණ දෙකක් එක්ක මේක simplify කරගමු. මේ tutorial එක ඉවර වෙනකොට ඔයාට පුළුවන් වෙයි ඔයාගේ Next.js project එක ඇතුලෙම සරල API endpoints හදාගන්න. ඉතින්, තව දුරටත් වෙලාව නාස්ති නොකර අපි වැඩේට බහිමු!

Next.js API Routes කියන්නේ මොනවද?

සරලවම කිව්වොත්, Next.js API Routes කියන්නේ ඔයාගේ Next.js application එක ඇතුලෙම ක්‍රියාත්මක වෙන serverless functions වගේ දෙයක්. මේවා Node.js backend code. සාමාන්‍යයෙන් ඔයා frontend එකට React වගේ එකක් පාවිච්චි කරනවා නම්, backend එකට Express, Koa, NestJS වගේ framework එකක් පාවිච්චි කරනවා. ඒත් Next.js API Routes වලින් වෙන්නේ ඒ backend logic ටිකත් Next.js project එක ඇතුලෙම, pages/api folder එක ඇතුලෙම ලියාගන්න පුළුවන් වීම.

මේකේ වාසි ගොඩයි:

  • සරල බව: ඔයාගේ frontend code එකයි backend code එකයි එකම project එකක, එකම තැනක තියෙන නිසා project structure එක ගොඩක් සරලයි.
  • Deployment පහසුයි: Vercel වගේ platform එකක deploy කරනකොට Next.js project එක deploy කරනවා වගේම මේ API Routes ටිකත් automatically deploy වෙනවා. වෙනම server එකක් configure කරන්න ඕන නෑ.
  • Performance: Serverless functions විදියට ක්‍රියාත්මක වෙන නිසා request එකක් ආවම විතරයි function එක run වෙන්නේ. ඒක performance එකටත්, resource management එකටත් වාසිදායකයි.

ඔයාට මතක තියාගන්න ඕන වැදගත්ම දේ තමයි මේ API Routes තියෙන්න ඕනේ pages/api කියන directory එක ඇතුළේ. මේ directory එක ඇතුළේ ඔයා හදන හැම JavaScript (හෝ TypeScript) file එකක්ම /api/<filename> කියන path එකෙන් access කරන්න පුළුවන් වෙනවා.

සරල "Hello World" API එකක් හදමු

හරි, දැන් අපි theory ඇති. අපි practical වැඩේට බහිමු. මුලින්ම "Hello World" කියලා return කරන සරලම API Route එකක් හදාගමු.

පියවර 1: `pages/api` directory එක හදාගන්න (නැත්නම්)

සාමාන්‍යයෙන් Next.js project එකක් හදනකොට මේ directory එක automatically හැදෙනවා. නැත්නම් ඔයාගේ project root එකේ pages folder එක ඇතුලේ api කියලා folder එකක් හදාගන්න.

පියවර 2: `pages/api/hello.js` file එක හදමු

දැන් pages/api folder එක ඇතුලේ hello.js කියලා අලුත් file එකක් හදන්න. මේ file එක ඇතුලට පහත code එක add කරන්න:


// pages/api/hello.js

export default function handler(req, res) {
  // `req` object එකට request එකේ data තියෙනවා (query params, body, headers)
  // `res` object එක response එක handle කරන්න පාවිච්චි කරනවා

  res.status(200).json({ message: 'ආයුබෝවන්, Next.js API Routes ලෝකයට!' });
}

මේ code එක පැහැදිලි කරමු:

  • export default function handler(req, res) { ... }: මේක තමයි Next.js API Route එකක standard structure එක. හැම API Route file එකක්ම මේ වගේ default exported function එකක් විය යුතුයි.
  • req (Request): මේ object එකේ client එකෙන් එවන request එකේ හැම information එකක්ම තියෙනවා. (headers, query parameters, request body වගේ දේවල්)
  • res (Response): මේ object එක පාවිච්චි කරලා අපිට client එකට response එක යවන්න පුළුවන්.
  • res.status(200): මේකෙන් අපි client එකට කියනවා request එක successful වුණා කියලා. 200 OK කියන්නේ standard HTTP status code එකක්.
  • .json({ message: 'ආයුබෝවන්, Next.js API Routes ලෝකයට!' }): මේකෙන් අපි JSON format එකෙන් data එකක් client එකට යවනවා.

පියවර 3: API Route එක Test කරමු

දැන් ඔයාගේ Next.js dev server එක run කරන්න (නැත්නම් දැනටමත් run වෙනවා නම් refresh කරන්න):


npm run dev
# or
yarn dev

දැන් ඔයාගේ browser එකේ ගිහින් http://localhost:3000/api/hello කියන URL එකට යන්න. (port number එක වෙනස් වෙන්න පුළුවන්). ඔයාට පෙනෙයි {"message":"ආයුබෝවන්, Next.js API Routes ලෝකයට!"} කියලා JSON response එකක්.

ඔයාට Postman, Insomnia වගේ tools පාවිච්චි කරන්නත් පුළුවන් API එක test කරන්න.

JSON Data Return කරන API එකක් (GET Request)

හරි, දැන් අපි පොඩ්ඩක් සංකීර්ණ වෙමු. users ලා කීප දෙනෙක්ගේ details JSON format එකෙන් return කරන API එකක් හදමු.

පියවර 1: `pages/api/users.js` file එක හදමු

pages/api folder එක ඇතුලේ users.js කියලා අලුත් file එකක් හදන්න. මේ file එක ඇතුලට පහත code එක add කරන්න:


// pages/api/users.js

export default function handler(req, res) {
  // API Route එක GET request එකක්ද කියලා බලමු
  if (req.method === 'GET') {
    const users = [
      {
        id: 1,
        name: 'කසුන් පෙරේරා',
        email: '[email protected]',
        city: 'කොළඹ'
      },
      {
        id: 2,
        name: 'නිරෝෂා සිල්වා',
        email: '[email protected]',
        city: 'ගාල්ල'
      },
      {
        id: 3,
        name: 'සුමිත් බණ්ඩාර',
        email: '[email protected]',
        city: 'මහනුවර'
      }
    ];
    res.status(200).json(users);
  } else {
    // GET request එකක් නැත්නම් වෙන method එකකට වැරදි status code එකක් දෙමු
    res.setHeader('Allow', ['GET']);
    res.status(405).end(`Method ${req.method} Not Allowed`);
  }
}

මේ code එකෙන් අපි කරන්නේ:

  • if (req.method === 'GET') { ... }: මේක ගොඩක් වැදගත්. Next.js API Routes වලදී, එකම file එකකදී වුණත් විවිධ HTTP methods (GET, POST, PUT, DELETE) handle කරන්න පුළුවන්. මෙතන අපි check කරන්නේ request එක GET method එකකින්ද ආවේ කියලා.
  • const users = [...]: මේක simulated database එකක් වගේ. අපි hardcoded user data ටිකක් තියාගත්තා. Real world application එකකදී මේක database එකකින් එන data වෙන්න පුළුවන්.
  • res.status(200).json(users): successful වුණා නම් user array එක JSON format එකෙන් යවනවා.
  • else { ... } block එක: මේකෙන් අපි කියන්නේ GET method එකක් නැතුව වෙන method එකකින් (උදාහරණයක් විදියට POST) මේ API එකට ආවොත් 405 Method Not Allowed කියලා response එකක් යවන්න කියලා. res.setHeader('Allow', ['GET']) එකෙන් අපි client එකට කියනවා මේ API එකට GET methods විතරයි support කරන්නේ කියලා.

පියවර 2: API Route එක Test කරමු

ඔයාගේ browser එකේ ගිහින් http://localhost:3000/api/users කියන URL එකට යන්න. ඔයාට user data array එක JSON format එකෙන් පෙනෙයි.


[
  {
    "id": 1,
    "name": "කසුන් පෙරේරා",
    "email": "[email protected]",
    "city": "කොළඹ"
  },
  {
    "id": 2,
    "name": "නිරෝෂා සිල්වා",
    "email": "[email protected]",
    "city": "ගාල්ල"
  },
  {
    "id": 3,
    "name": "සුමිත් බණ්ඩාර",
    "email": "[email protected]",
    "city": "මහනුවර"
  }
]

Postman/Insomnia වගේ tools වලින් test කරනකොට request method එක GET වලට තියෙනවාද කියලා confirm කරගන්න.

වැදගත් Tips සහ Best Practices

Next.js API Routes එක්ක වැඩ කරනකොට මතක තියාගන්න ඕන වැදගත් කරුණු කීපයක් තියෙනවා:

1. Single Responsibility Principle (SRP)

හැකි සෑම විටම, ඔයාගේ හැම API Route එකක්ම එක වැඩක් විතරක් කරන්න හදන්න. උදාහරණයක් විදියට, pages/api/users.js කියන එක user list එකක් return කරන්න, user කෙනෙක් add කරන්න, update කරන්න විතරක් use කරන්න. orders manage කරන්න වෙනම API Route එකක් හදන්න.

2. HTTP Status Codes

Client එකට නිවැරදි HTTP status codes යවන එක ගොඩක් වැදගත්. මේකෙන් API එක use කරන client එකට පහසුවෙන් request එකේ තත්ත්වය තේරුම් ගන්න පුළුවන්. සාමාන්‍යයෙන් භාවිතා වෙන ඒවා:

  • 200 OK: Request එක සාර්ථකයි. (GET, PUT, PATCH, DELETE)
  • 201 Created: Resource එක සාර්ථකව නිර්මාණය කළා. (POST)
  • 204 No Content: Request එක සාර්ථකයි, ඒත් return කරන්න data නෑ. (DELETE)
  • 400 Bad Request: Client එකෙන් යැව්වේ වැරදි data.
  • 401 Unauthorized: Authentication අවශ්‍යයි / Authentication fail.
  • 403 Forbidden: Client එකට මේ resource එකට access කරන්න අවසර නෑ.
  • 404 Not Found: Resource එක හොයාගන්න බෑ.
  • 405 Method Not Allowed: Request එකේ method එක (GET, POST වගේ) මේ API එකට support කරන්නේ නෑ.
  • 500 Internal Server Error: Server එකේ පැත්තෙන් වුණු unexpected error එකක්.

3. Error Handling

ඔයාගේ API Routes වල proper error handling කරන්න. Database එකට connect වෙනකොට, third-party API එකක් call කරනකොට errors එන්න පුළුවන්. ඒ වගේ වෙලාවට try...catch blocks පාවිච්චි කරලා errors අල්ලගෙන, res.status(500).json({ error: 'Something went wrong' }); වගේ message එකක් client එකට යවන්න.


// Error Handling Example
export default async function handler(req, res) {
  try {
    // Simulate fetching data from a database or external API
    const data = await fetchDataFromDatabase(); // Hypothetical function
    res.status(200).json(data);
  } catch (error) {
    console.error('API Error:', error);
    res.status(500).json({ message: 'Internal Server Error. Please try again later.' });
  }
}

4. Debugging Server-side Errors

API Routes කියන්නේ server-side code නිසා, browser console එකේ errors බලාගන්න බෑ. Debug කරන්න console.log() statements පාවිච්චි කරන්න. මේවා ඔයාගේ Next.js dev server එක run වෙන terminal එකේ පෙන්වයි. දරුණු errors ආවොත් ඒවාත් terminal එකේ පෙන්වයි.

අවසන් වචන...

ඉතින් යාළුවනේ, Next.js API Routes ගැන ඔයාට හොඳ අවබෝධයක් ලැබෙන්න ඇති කියලා හිතනවා. මේක Next.js වල තියෙන ගොඩක් powerful feature එකක්. සරල frontend applications වලට backend logic ටිකක් අවශ්‍ය වුණාම වෙනම server එකක් configure කර කර ඉන්න ඕන නෑ. ඒ වගේම Jamstack architecture එක එක්ක වැඩ කරනකොටත් මේ API Routes ගොඩක් ප්‍රයෝජනවත් වෙනවා.

දැන් ඔයාට පුළුවන් මේ concepts පාවිච්චි කරලා POST request එකක් handle කරන API එකක් හදන්න උත්සාහ කරන්න. (request body එකෙන් data අරගෙන). ඒ වගේම dynamic API Routes (pages/api/users/[id].js වගේ) ගැනත් හොයලා බලන්න.

මේ tutorial එක ප්‍රයෝජනවත් වුණා නම් අනිවාර්යයෙන්ම comment එකක් දාලා යන්න. ඔයාගේ අත්දැකීම් මොනවද, මොනවා හරි ප්‍රශ්න තියෙනවාද කියලා අපිට කියන්න. අලුත් project එකක මේ API Routes implement කරලා බලන්නත් අමතක කරන්න එපා!

සුබ දවසක්!