MCPcopy Create free account
hub / github.com/vercel/vercel / withApiHandler

Function withApiHandler

api/_lib/util/with-api-handler.ts:6–44  ·  view source on GitHub ↗
(handler: Handler)

Source from the content-addressed store, hash-verified

4type Handler = (req: VercelRequest, res: VercelResponse) => Promise<any>;
5
6export function withApiHandler(handler: Handler): Handler {
7 return async (req: VercelRequest, res: VercelResponse) => {
8 res.setHeader('Access-Control-Allow-Origin', '*');
9 res.setHeader('Access-Control-Allow-Methods', 'GET');
10 res.setHeader(
11 'Access-Control-Allow-Headers',
12 'Authorization, Accept, Content-Type'
13 );
14
15 if (req.method === 'OPTIONS') {
16 return res.status(200).json({});
17 }
18
19 if (req.method !== 'GET') {
20 return res.status(405).json({
21 error: {
22 code: 'method_not_allowed',
23 message: 'Only GET requests are supported for this endpoint.',
24 },
25 });
26 }
27
28 try {
29 const result = await handler(req, res);
30 return result;
31 } catch (error) {
32 errorHandler(error, {
33 url: req.url,
34 });
35
36 return res.status(500).json({
37 error: {
38 code: 'unexpected_error',
39 message: 'An unexpected error occurred.',
40 },
41 });
42 }
43 };
44}

Callers 2

frameworks.tsFile · 0.90
info.tsFile · 0.90

Calls 4

errorHandlerFunction · 0.90
statusMethod · 0.80
jsonMethod · 0.65
handlerFunction · 0.50

Tested by

no test coverage detected