Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To create two Post End Points in the same file using Next.js, you can follow the steps below:

  1. Import NextApiRequest and NextApiResponse from next.
import type { NextApiRequest, NextApiResponse } from 'next'
  1. Define two functions that will handle the two Post End Points. For example, let's say we want to create "createUser" and "createPost" End Points.
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
}
  1. Use the 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
  1. Verify that both End Points are working as expected.