It's All About (The) Next.js api routes
When you create the Next.js application, you can see the "api" folder. Before proceedings, a few things about the API folder:
- It is to write the server-side code for our application.
- All the files created in this folder must be javascript files.
- All the routes inside the folder have "api" as a prefix.
- It must return data in JSON format.
How to add API routes?
Adding the API routes in Next.js is simple. We need to add the javascript file under the api folder.
Let's say we need an api that returns the list of users. To accomplish this, create a getuser.js file under the api directory.
Add the following code:
function getUsers(req, res) {
const users = [
{
id: 1,
name: 'Michael Foo',
email: 'michael@foo.com'
},
{
id: 2,
name: 'John Cena',
email: 'john@example.com'
},
{
id: 3,
name: 'Zoho S',
email: 'zoho@example.com'
}
];
res.status(200).json({ users: users })
}
export default getUsers;
When you visit http://localhost:3000/api/getuser
And you see the JSON data in the browser.
Dynamic API Routes
What we have learned so far are the static routes that return the JSON data. Sometimes, it's required to pass the dynamic variable or parameters (in the URL) and then get the data according to the variable. If we want to get the data for the individual user, we need to pass a dynamic variable (let's say id) in the URL and, the backend returns the data based on the id variable.
Create a new folder 'user' under the api and create [userId].js under the user folder.
Add the following code to the new file:
const users = [
{
id: 1,
name: 'Michael Foo',
email: 'michael@foo.com'
},
{
id: 2,
name: 'John Cena',
email: 'john@example.com'
},
{
id: 3,
name: 'Zoho S',
email: 'zoho@example.com'
}
];
function getUserDetails(req, res) {
const userId = req.query.userId
const userDetails = users.filter( user => user.id === Number(userId) )
res.status(200).json({ users: userDetails })
}
export default getUserDetails;
Go to the browser and visit
http://localhost:3000/api/user/2. You will see the details of the user having id equals 2.
In the above example, we created (copied from earlier instances) a user object. We return the response to the browser where user id equals 2.
The api routes are used to write the backend code but one still can argue, we (hardcode the object) and didn't use the database to get the user information. How can we say that it's a Full Stack Framework or it is to write the backend code? Right in this article, we haven't covered the database part. This article aims to get an understanding of the basics of the api routes in Next.js.
We'll cover the database in the following article.