We regret to inform you that the Serverless Function in NextJs has surpassed the maximum size limit of 50mb

Recently, I've started working with NextJs and encountered an issue while attempting to deploy my project on Vercel. The error message that popped up looked like this:

Error! The Serverless Function "api/auth" exceeds the maximum size limit of 50mb, with its size being 50.55mb.

I've dedicated a substantial amount of time searching for a solution to this problem but unfortunately, no luck so far. Below is the snippet of code responsible for the API request:

const { auth: adminAuth } = require("firebase/admin");

export default async function auth(req, res) {
  const tokenId = req.query.token;
  return new Promise((resolve) => {
    adminAuth
      .verifyIdToken(tokenId)
      .then((user) => {
        res.json(user);
        resolve();
      })
      .catch(() => {
        res.status(302).send("Invalid authentication");
        resolve();
      });
  });
}

I would greatly appreciate any assistance in resolving this issue. Thank you all in advance!

Answer №1

I've encountered a similar issue where bundling the serverless function in Vercel causes all assets in the project to be included, resulting in a larger build size. It seems that your current build size of 50.55MB is due to this inclusion of all assets. I'm currently exploring ways to selectively include files in vercel.json, but have not yet found a solution. In the meantime, you may want to consider removing some files from your public assets to reduce the overall size and stay within the limit.

Answer №2

The issue may be caused by the fact that the firebase/admin package includes everything in the firebase package, not just the "admin" components.

You can confirm this by creating a file with only the import statement and using @vercel/nft to analyze the files.

npm init -y
npm add firebase
echo "const { auth: adminAuth } = require('firebase/admin')" > index.js
npm i -g @vercel/nft
nft print index.js

The complete firebase package is quite large, so it's recommended to heed the advice of the Firebase team and utilize the firebase-admin package specifically for Serverless Functions.

The firebase SDK is designed for end-user client access in environments like the Web, mobile Web (e.g., React Native, Ionic), Node.js desktop (e.g., Electron), or IoT devices running Node.js. If you require admin access from a privileged environment such as a server, consider using the Firebase Admin Node.js SDK (firebase-admin).

source: firebase NPM

Answer №3

As of Next.js 12.3, the build process includes all dependencies listed in your package.json, as well as their dependencies, potentially increasing the overall build size until it reaches the maximum limit of 50MB.

In my experience, I encountered an issue with the pdfjs-dist package, which had a dependency on canvas. Simply having pdfjs-dist listed as a dependency in the package.json caused Vercel builds to fail, even without actually importing any files from the packages.

Error: The Serverless Function "api/***" is 64.75mb which exceeds the maximum size limit of 50mb.

Determining the Problem

The Vercel build logs should display the packages included in the build and their respective sizes. In our case:

All dependencies                                        208.68 MB         57.14 MB
Serverless Function's page: api/***
Large Dependencies                              Uncompressed size  Compressed size
node_modules/canvas/build                               164.01 MB         42.82 MB
node_modules/sharp/vendor                                16.13 MB          6.76 MB
...

Excluding Packages from the Build

In our scenario, the canvas dependency was unnecessary. To exclude a package and reduce the size for serverless functions:

const nextConfig = {
  experimental: {
    outputFileTracingRoot: path.join(__dirname, '../../'),
    outputFileTracingExcludes: {
      '*': [
        'node_modules/canvas',
      ],
    },
  },
}
  • With Next.js 12.3 and Yarn, replacing the dependency with a stub can be done by following this guide in the package.json:
  "resolutions": {
    "canvas": "https://registry.yarnpkg.com/@favware/skip-dependency/-/skip-dependency-1.2.1.tgz"
  }

Similar solutions may exist for NPM users.

Answer №4

Here is the code snippet to include in your next.config file:

 experimental: {
    outputFileTracingIgnores: ["**canvas**"],
  },

Answer №5

If you're facing this issue, it might be due to nextjs including unnecessary swc and esbuild dependencies in your serverless functions. To resolve this, simply add the following code snippet to your next.config.js

 experimental: {
    outputFileTracingExcludes: {
      '*': [
        'node_modules/@swc/core-linux-x64-gnu',
        'node_modules/@swc/core-linux-x64-musl',
        'node_modules/@esbuild/linux-x64',
      ],
    },
  },

Answer №6

For me, the problem stemmed from the dependency on canvas in pdfjs-dist. I was able to resolve this issue by adding a specific override in my package.json file for pnpm.

"pnpm": {
  "overrides": {
    "canvas": "../_EXCLUDED_"
  }
},

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to establish numerous breakpoints on grid items within Material UI when utilizing React?

My Layout HOC has a Grid with 4 Widget components as Grid items. I want them to display differently based on screen size: On large screens: all 4 should be in 1 row On medium screens: 2 in a row, 2 columns On small screens: 1 widget takes full width, spr ...

Tips for storing API data in Reactjs state

Is there a way I can efficiently store fetched API data in state so that it remains available even after page refresh? How can I save the data with parameter names without resorting to local or session storage? This method would be beneficial as it would ...

Eliminate file security error in Meteor by utilizing Filestack

I've been working on integrating the react filestack plugin with meteor, and I'm running into issues when enabling the security settings to remove uploaded files. To delete a file, I need to utilize App Secret, policy, signature, apikey. However, ...

Tips for choosing elements in an application and managing state changes in React

I am looking to create a straightforward app similar to the image provided using react js, but I am struggling to come up with the right concept of: How can I "pick" photos (or items) within the app and make a "cart-like" feature appear at the bottom once ...

Implementing Angular 4 on a Node Express server within Firebase platform

After setting up an angular 4 project using angular cli, I decided to incorporate express into my application. I created a file named app.js with the following content: app.js const express = require('express') const app = express() ...

Incorporate React JS seamlessly into your current webpage

As I delve into learning React and considering migrating existing applications to React, my goal is to incorporate a React component within an established page that already contains its own HTML and JavaScript - similar to how KnockoutJS's `applyBindi ...

Express.js: app.post is failing to establish a connection

Currently, I am in the process of developing an application using NodeJS and have encountered a roadblock. When testing the post request with Postman, the server does not seem to enter the function. However, GET requests function as expected. Do you have a ...

Tapping the image will redirect you to the corresponding component

My React Routes Challenge I've run into a roadblock while trying to implement react routes in my project. Greetings, everyone! This is my first time seeking help here, as I have previously posted about this issue on Codecademy. Below is the summary o ...

Finding the Earliest and Latest Date in Material UI DatePicker Component within a React Application

I am facing an issue with date selection based on the 'access' value in my code. When the 'access' value is 1, there should be no restrictions on selecting dates. However, when the value of 'access' is not 1, users should only ...

The state variable hook fails to increase while in the closure

codesandbox.io/s/github/Tmcerlean/battleship I am currently working on the development of a simple board game and I am facing an issue with updating a state variable when a player clicks on a cell with a valid move. Despite having all the necessary funct ...

Customize Date Display in Material-UI DataGrid

How do I change the date format in MUI DataGrid from mongo's format to moment.js? In addition, I would like to add a new field with an edit icon that, when clicked, will redirect to the edit page. Here is what my code looks like: const columns = [ ...

Is there a way to update the content of both spans within a button component that is styled using styled-components in React?

I am interested in creating a unique button component using HTML code like the following: <button class="button_57" role="button"> <span class="text">Button</span> <span>Alternate text</span> ...

Obtaining connected information in AngularJS with Firebase

After reviewing the example found at the following link: I am curious to know if AngularFire can be used to retrieve and show relational data (referred to as sparks) in a similar manner? ...

Creating a Material UI Dialog with a see-through background color: a step-by-step guide

I'm struggling to create a loading status indicator using Material UI. I want the background color of the dialog box to be transparent and I also need to adjust the height, but I can't seem to achieve this with the provided style options. Any sug ...

TAILWINDCSS: Is there a way to prevent the page from shrinking beyond a certain breakpoint? Take a look at the images provided for visual

Currently, the page can be minimized to a very narrow width as depicted in the image below. https://i.stack.imgur.com/gZqvV.png Is there a way to specify the smallest breakpoint screen size that the page can shrink to this particular width? https://i.sta ...

What steps are involved in importing remark-gfm into next.config.js?

I am interested in incorporating MDX into next.js with the remark-gfm plugin. After discovering the Next.js Docs on MDX, I decided to follow their guidelines and added an import statement. // next.config.js import remarkGfm from 'remark-gfm;' co ...

Creating Redux reducers dynamically

I'm feeling a bit puzzled about how to dynamically generate reducers in Redux. I've come across some Stackoverflow threads discussing this topic, but they seem to address various scenarios and leave me somewhat confused with the proposed solutio ...

React and Express facing CORS header challenge

I'm facing an issue with CORS despite trying various solutions found on Stack Overflow. My app uses Express/NodeJS as an API and React JS for the frontend. During development, the React app at http://localhost:3000 communicates successfully with the ...

Having trouble rendering the React app; encountered an error: JSX contents are unterminated

I am currently facing an issue while trying to fetch data from an API in React using Axios. How can I ensure that useEffect functions properly? My objective is to create a page by fetching data from an API in React through Axios. I have designed a compon ...

Comparing SSR and CSR Approaches to Handling getInitialProps in _app.js with Next JS

I am currently working on developing a Next JS application that manages authentication and initial routing within the getInitialProps function. I have found that this method can be executed either server-side or client-side. My current approach involves ...