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)
}
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
.
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.