8

Using the pages/api in NextJs to create endpoints

 1 year ago
source link: http://www.js-craft.io/blog/using-the-pages-api-in-nextjs-to-create-endpoints/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Using the pages/api in NextJs to create endpoints

We have seen how one can use the /pages folder to make basic routes and query params routes in NextJs.

But, there is also another special folder called /pages/api. Using it we can create endpoints for our NextJs app. Each file from this folder will be mapped to an endpoint like /api/name_of_the_file. So, if you create the /pages/api/tennis.js your app will get have access to the http://localhost:3000/api/tennis endpoint:

const topPlayers = [
    {"player": "Roger Federer"},
    {"player": "Rafael Nadal"},
    {"player": "Andy Murray"}, 
    {"player": "Novak Djokovic"},
]

export default (req, res) => {
    res.status(200).json(topPlayers)
}
Screen-Shot-2022-09-27-at-11.32.06.png

We can also have query parameters for these APIs routes:

export default (req, res) => {
    const {id} = req.query
    res.status(200).json({ 
        response: `Called the tennis API with the id param of value ${id}`  
    })
}

Actually, having the option to build APIs is one of the main advantages of NextJs over static alternatives like Gatsby.

But what if we want a POST request? Well, the endpoint will be the same, but you can use the req.method to separate the different request types:

export default (req, res) => {
  switch (req.method) {
    case 'GET':
      //code here
      break
    case 'POST':
      //code here
      break
    default:
      res.status(405).end() //unidentified method
  }
}

It will also work for the DELETE or PUT methods.

In the API's folder, you will write node code, instead of React code. So keep in mind this paradigm shift and the fact that you will not have access to client-side objects like window or document.

I hope you have enjoyed this article and if you would like to get more articles about React and frontend development you can always sign up for my email list.

Newsletter subscribe:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK