1 | initial version |
To create two Post End Points in the same file using Next.js, you can follow the steps below:
NextApiRequest
and NextApiResponse
from next
.import type { NextApiRequest, NextApiResponse } from 'next'
export default function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method === 'POST') {
const { type } = req.body
if (type === 'user') {
createUser(req, res)
} else if (type === 'post') {
createPost(req, res)
} else {
return res.status(400).json({ error: 'Unknown type' })
}
} else {
return res.status(400).json({ error: 'Invalid method' })
}
}
async function createUser(req: NextApiRequest, res: NextApiResponse) {
// handle creating user
}
async function createPost(req: NextApiRequest, res: NextApiResponse) {
// handle creating post
}
useRouter
hook to test your endpoints. For example, you can use a tool such as curl
or Postman
to test the End Points. For the "createUser" endpoint, you would send a POST request to /api/myEndpoint
with a type
parameter of user
. Similarly, for the "createPost" endpoint, you would send a POST request to /api/myEndpoint
with a type
parameter of post
.curl -X POST -H "Content-Type: application/json" -d '{"type": "user"}' http://localhost:3000/api/myEndpoint
curl -X POST -H "Content-Type: application/json" -d '{"type": "post"}' http://localhost:3000/api/myEndpoint