How can i fix Serverless Function fail when deploying a Nodejs project on Vercel?

Ân Hưởng - Sep 9 - - Dev Community

Introduction

Deploying a Node.js backend on Vercel for the first time often leads to the frustrating error: "This Serverless Function has crashed." I faced the same issue while trying to deploy my TypeScript backend on Vercel, and it took me two days to figure it out. Even though this is my first time writing a blog, I wanted to share the solution in hopes it can help others avoid the same headache.

Upload Dist folder

push dist folder on github
I’ve been encountering an issue every time i deploy our TypeScript project. It doesn’t run as expected, and I suspect that Vercel’s deployment process might be contributing to the problem. To address this, I resolved the issue by creating a dist directory within the project and deploying that to GitHub. Afterward, i set up a script to read the JavaScript files from the dist folder. This approach seems to have fixed the problem, ensuring a smoother deployment process.

The way I resolved this was by removing dist from .gitignore, allowing it to be included in the deployment. Then, I set up the vercel.json file like this:

{
  "version": 2,
  "builds": [
    {
      "src": "dist/index.js",
      "use": "@vercel/node",
      "config": { "includeFiles": ["dist/**"] }
    }
  ],
  "routes": [
    {

      "src": "/(.*)",
      "dest": "dist/index.js"
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

After setting it the Vercel will got some error like this

log error after deploy dist

Log Error 500 cannot find module /var/*

I’m not entirely sure what caused the issue, but the only solution I found was to remove this code from the tsconfig.json file.

 "paths": {
      "@/*": ["src/*"]
 },
Enter fullscreen mode Exit fullscreen mode

You’ll also need to update all import paths from @/ to ./../../*. I understand that this might be a bit cumbersome, but it does resolve the issue.

Conclusion

While this solution addresses the problem, I believe there may be other ways to resolve this error. I welcome any additional insights or alternative solutions you might have to offer in the comments. As this is my first attempt at sharing solutions through a blog, I appreciate any feedback you can provide. Thank you for reading!
conclusion meme

.
Terabox Video Player