Next Js Bangla Tutorial: API Routes
Fundamentals of API Routes in Next js | Part 7
Next.js is a popular open-source React framework that enables functionality such as server-side rendering and generating static websites for React-based web applications. In this tutorial, we will focus on API routes in Next.js, which allow you to create server-side logic within your Next.js application.
What are API Routes?
API routes in Next.js are special endpoints that allow you to create server-side logic in your Next.js application. These endpoints can be used to fetch data from an external API, perform server-side computations, or handle form submissions. API routes in Next.js are defined in files inside the pages/api
directory in your Next.js project.
Creating an API Route
To create an API route in Next.js, you simply need to create a new file inside the pages/api
directory with the desired endpoint name. For example, if you want to create an API route to fetch user data, you can create a file called user.js
inside the pages/api
directory. Within this file, you can define the server-side logic for handling requests to this endpoint.
Example of an API Route
Here is an example of a simple API route in Next.js that returns a list of users:
// pages/api/users.js
export default function handler(req, res) {
const users = [
{ id: 1, name: 'John Doe' },
{ id: 2, name: 'Jane Doe' },
{ id: 3, name: 'Bob Smith' }
];
res.status(200).json(users);
}
In this example, we define a function called handler
that takes req
and res
as parameters, and returns a list of users in JSON format using the res.status(200).json(users)
method.
Usage of API Routes
Once you have created an API route in Next.js, you can use it in your client-side code by making a HTTP request to the endpoint. For example, you can use the fetch
method in JavaScript to make a GET request to your API route:
fetch('/api/users')
.then((response) => response.json())
.then((data) => {
console.log(data);
});
Conclusion
API routes in Next.js are a powerful feature that allow you to create server-side logic within your Next.js application. They can be used to fetch data from an external API, perform server-side computations, or handle form submissions. In this tutorial, we covered the fundamentals of API routes in Next.js and how to create and use them in your Next.js projects.
হটাৎ গতকাল nextJs এর UI পরিবর্তন করে ফেলছে, সেখানে Pages ডিরেক্টরির পাশাপাশি app ডিরেক্টরিটা যুক্ত করছে | এখনকার ডুকুমেন্টেশনটা আরো ক্লিয়ার এবং স্ট্রেইটফরওয়ার্ড | এই সিরিজটা শেষ হওয়ার পরেই আমি app ডিরেক্টরি নিয়ে ফুল একটা ক্রাশ কোর্স দিবো |
আর ভিডিও ডেস্ক্রিপশনে docs লিংক দেয়া আছে