How do I reduce the bundle size of a vercel serverless function?
Been messing around with next-auth and nextjs app dir inside nx monorepo and I've hit a wall when it comes to deploying the app with email provider auth. For some reason the dependencies get blown up in size and exceed the limit.
// logs from vercel dashboard
Serverless Function's page: api/auth/[...nextauth].js
Large Dependencies Uncompressed size Compressed size
node_modules/@swc/core-linux-x64-gnu 49.75 MB 16.52 MB
node_modules/@swc/core-linux-x64-musl 49.36 MB 16.39 MB
node_modules/.prisma/client 16.25 MB 7.23 MB
node_modules/next/dist 19.67 MB 4.87 MB
node_modules/@esbuild/linux-x64 8.68 MB 3.64 MB
node_modules/webpack/lib 3.31 MB 871.18 KB
node_modules/sass/sass.dart.js 4.27 MB 669.82 KB
node_modules/react-dom/cjs 1.64 MB 404.02 KB
node_modules/caniuse-lite/data 882.5 KB 316.5 KB
dist/apps/manager-dashboard 1.48 MB 253.23 KB
node_modules/terser/dist 957.25 KB 183.23 KB
node_modules/uglify-js/lib 972.25 KB 166.19 KB
node_modules/webpack/schemas 606.81 KB 93.78 KB
All dependencies 161.46 MB 52.47 MB
I've tried using vercel.json
to exclude the biggest offenders but it didn't work.
// apps/my-app/vercel.json
{
"functions": {
"app/api/auth/[...nextauth].js": {
"excludeFiles": "**/node_modules/{@swc,@esbuild}/**"
}
}
}
The code in nextauth is basically following the documentation:
// apps/my-app/app/api/auth/[...nextauth]/route.ts
import NextAuth from 'next-auth';
import { PrismaAdapter } from '@next-auth/prisma-adapter';
import { PrismaClient } from '@prisma/client';
import EmailProvider from 'next-auth/providers/email';
const emailProvider = EmailProvider({
from: 'no-reply@exanubes.com',
type: 'email',
server: {
host: process.env.EMAIL_SERVER_HOST,
port: process.env.EMAIL_SERVER_PORT,
maxAge: 24 * 60 * 60, // 24 hours
auth: {
user: process.env.EMAIL_SERVER_USER,
pass: process.env.EMAIL_SERVER_PASSWORD,
},
},
});
const prisma = new PrismaClient();
const handler = NextAuth({
secret: process.env.NEXTAUTH_SECRET,
session: {
strategy: 'jwt',
},
adapter: PrismaAdapter(prisma),
providers: [emailProvider],
});
export { handler as GET, handler as POST };
I was able to fix this issue by deleting the lock file and moving all my dependencies to devDependencies. Interestingly, in vercel deployment logs, it noticed swc linux deps missing but it compiled just fine without them.
- info Downloading WASM swc package...
- warn Found lockfile missing swc dependencies, run next locally to automatically patch
- info Using wasm build of next-swc
- warn Attempted to load @next/swc-linux-x64-gnu, but it was not installed
- warn Attempted to load @next/swc-linux-x64-gnux32, but it was not installed
- warn Attempted to load @next/swc-linux-x64-musl, but it was not installed