-1

Nodejs frameworks like express and fastify allow user to declare routes like so

  fastify.get("/:id/projects", async (request: GetProjectRequest, reply) => {})

which ties particular routes to particular types of requests.

The vercel docs suggest making functions like so:

export default async function handler(request, event) {
  return Response.json({
    success: true,
  });
}

What's the canonical way of expressing what request method is allowed for a given vercel serverless endpoint?

Danila
  • 15,606
  • 2
  • 35
  • 67
Paymahn Moghadasian
  • 9,301
  • 13
  • 56
  • 94

1 Answers1

1

Basically it's up to you to decide what do you want to return when some method is not allowed. Your function will be executed for every method:

export default function handler(req, res) {
  if (req.method === 'POST') {
    // Process a POST request
  } else {
    // Handle any other HTTP method
  }
}

You can also use something like this https://github.com/Howard86/next-api-handler (or any other similar library or helper) which allows you to make similar interface as express, fastify etc:

// in /pages/api/users.ts
import { RouterBuilder, ForbiddenException } from 'next-api-handler';
import { createUser, type User } from '@/services/user';

const router = new RouterBuilder();

router
  .get<string>(() => 'Hello World!')
  .post<User>(async (req) => createUser(req.body))
  .delete(() => {
    throw new ForbiddenException();
  });

export default router.build();
Danila
  • 15,606
  • 2
  • 35
  • 67