Deploy Vercel Serverless Function

Deploy express POST method using axios

ยท

2 min read

I had to create a webhook demo recently and decided to use Node.js to develop a POST route quickly. However, I was then faced with where to deploy this route. Given the nature of the project, a serverless function seemed like the best option. Since I'm currently learning Next.js and enjoying using Vercel, I decided to challenge myself to deploy the function on Vercel. However, I soon realized deploying a serverless function is not a one-click process.

I deployed the function on Vercel. Set up a Postman POST request

Oops! It took me some time to figure it out through trial and error, but here's what ultimately did the trick.

  1. Rename app.js to index.js

  2. Create "api" folder. Move index.js inside /api folder

  3. Convert the post request into an async handler function

  4. create vercel.json and add following

    { "version": 2, "functions": { "api/*.js":{ "maxDuration":10 } } }

Please find github reference for the code.

In Postman, I retried my request and got another error

A server error has occurred

FUNCTION_INVOCATION_FAILED

This one was persistent ๐Ÿ˜ญ . On the server, the log message was -"Cannot find module '/var/task/node_modules/axios/dist/node/axios.cjs'".

Although I confirmed that axios was correctly added to package.json and imported with the proper case, it turned out that the solution was actually in the package.json file.

"type":"module"

After adding this line in package.json everything seems to be working for me!! Happy ME ๐ŸŒŸ

The lack of descriptive error messages for debugging is becoming more pressing. However, I suppose that's what makes the process of debugging so intriguing.๐Ÿ˜…

If you're in the same situation as me and wondering why all the blog posts are exclusively focused on setting up serverless functions on Vercel using GET methods, perhaps this will give you some hope.

Happy deploying!

ย