Sounav Saha
Sounav Saha

Reputation: 85

Node-Canvas on Vercel Serverless Function - Serverless Function exceeds the maximum size of 50mb

In my Next.js project, I am using fabric and fabricjs-react as a wrapper over fabric to allow users to drop images into my canvas. Now one of fabric's dependency happens to be node_modules/canvas/build which has a compressed size of 42.82 MB. I have tried using @napi-rs/canvas to replace the canvas package in my package.json but it lead to Error: Cannot find module '../build/Release/canvas.node'. I am trying to use getServerSideProps in my concerned page. But it only leads to a build error on Vercel. I am using 12.3.1 version of next along with 5.3.0 version of fabric and 2.11.2 version of canvas package. Hereby attached is a screenshot of what I get in my Vercel logs while building the project

Is there any way I can trim down this dependency size or only import the parts of the package I need in this API route? If using @napi-rs/canvas is a workaround, how do I solve the Error: Cannot find module '../build/Release/canvas.node'. given by fabric ?

Upvotes: 2

Views: 1376

Answers (1)

Madauy
Madauy

Reputation: 11

I encountered a similar issue and found a workaround that doesn't break the fabricjs functionalities in my case.

Update your next.config.js with the following:

/** @type {import('next').NextConfig} */
const nextConfig = {
  images: {
    remotePatterns: [
      {
        protocol: "https",
        hostname: "**",
      },
    ],
  },
  experimental: {
    legacyBrowsers: false,
    outputFileTracingExcludes: ['**canvas**']
  },
  webpack: (config) => {
    config.externals = [...config.externals, "canvas", "jsdom"]
    return config
  }
}

module.exports = nextConfig

The key addition here is the outputFileTracingExcludes: ['**canvas**'] which excludes the canvas dependency during the build. In my tests, this didn't break any fabricjs functionalities. Make sure to test it thoroughly in your use case. I hope this helps.

Upvotes: 1

Related Questions