We now have a youtube channel. Subscribe!

Next.js | API Routes

Next.js Api Routes


Hello folks! welcome back to a new section of our tutorial on Next.js. In this tutorial, we will be studying about Next.js API Routes.

API Routes is a way to create rest API using Next.js. Next.js maps any file that is present in /pages/api folder and is treated as an API end point.

Syntax

Following is the syntax to use this API -

export default (req, res) => {
   ...
}

Parameter Details

Below is the description of the parameters used -

  • req - The parameter req is an instance of http.IncomingMessage and is used to get data from request.
  • res - The parameter res is an instance of http.ServerResponse and is used to send data as response.

Example

Let's create an example to demonstrate the same.

In this example, we will create an user.js in pages/api directory.

Let us update the nextjs project which was used in Global CSS Support tutorial.

Create user.js file in pages/api directory with the following content -

export default (req, res) => {
   res.statusCode = 200
   res.setHeader('Content-Type', 'application/json')
   res.end(JSON.stringify({ name: 'Kennedy' }))
}


Start Next.js Server

Run the following command below to start the server -

npm run dev

> nextjs@1.0.0 dev D:\Node\nextjs
> next

ready - started server on http://localhost:3000
info  - Loaded env from D:\Node\nextjs\.env.local
event - compiled successfully
event - build page: /api/user
wait  - compiling...
event - compiled successfully
event - build page: /next/dist/pages/_error
wait  - compiling...
event - compiled successfully

Output

Open localhost:3000/api/user in a browser and you will see the following result -

{"name":"Kennedy"}


Alright guys! This is where we are going to be rounding up for this tutorial. In our next tutorial, we are going to be studying about Next.js Api MiddleWares.

Feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.

Post a Comment

Hello dear readers! Please kindly try your best to make sure your comments comply with our comment policy guidelines. You can visit our comment policy page to view these guidelines which are clearly stated. Thank you.
© 2023 ‧ WebDesignTutorialz. All rights reserved. Developed by Jago Desain