Vercel Edge Middleware Hit 1MB: How We Cut It Back Under the Limit
Our Vercel middleware bundle quietly ballooned past the 1MB edge limit and broke a Friday deploy. Here's what was actually in it, what we ripped out, and the patterns we now enforce in CI.
A Friday afternoon deploy failed with Edge Function size of 1.02 MB exceeds the limit of 1 MB. The middleware had been fine on Thursday. Nothing obvious had changed, except two dependency bumps and a feature flag refactor — which, as it turned out, were exactly the problem.
This is the breakdown of what we found, what we cut, and the guardrails we put in so it doesn't happen again.
Why the 1MB limit exists and why it bites you suddenly
Vercel's edge middleware runs on a V8 isolate, not Node. The 1MB gzipped limit (as of our last check — Vercel has nudged these numbers before, so verify in their docs) applies to the final bundled, compressed artifact. That includes every transitive import the bundler couldn't tree-shake.
The reason it bites suddenly: middleware is usually tiny — a few hundred lines at most — so teams stop thinking about its bundle size. Then someone imports a utility from @/lib/auth that transitively pulls in a JWT library, which pulls in a crypto polyfill, which pulls in a base64 helper that ships its own lookup tables. You were at 400KB on Monday and 1.02MB on Friday, and next build gave you no warnings along the way because local builds don't enforce the edge limit the same way production does.
The specific trigger in our case
Two things happened the same week:
- We upgraded
jose(a JWT library) — fine on its own, but we were also importing it from a barrel file that re-exported half of@/lib. - A developer moved feature flag evaluation into middleware so flags could gate routes at the edge. The flag SDK had a bundled analytics client that we didn't need at the edge.
Individually, neither would have tripped the limit. Together, they added about 280KB gzipped.
Step one: actually see what's in the bundle
The first useful move is to stop guessing. Next.js can emit a bundle analysis, and for middleware specifically you want to look at .next/server/middleware.js (or the edge-runtime variant) before and after gzip.
# Build with analyzer enabled
ANALYZE=true pnpm build
# Check the raw and gzipped size of the middleware artifact
ls -lh .next/server/middleware.js
gzip -c .next/server/middleware.js | wc -c
For the analyzer, we wire @next/bundle-analyzer into next.config.js:
const withBundleAnalyzer = require('@next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
});
module.exports = withBundleAnalyzer({
// ...
});
The analyzer's middleware treemap is where the truth lives. In our case, about 42% of the bundle was a single dependency tree we didn't know we were pulling in.
Reading the treemap without fooling yourself
Two traps:
- Parsed vs gzipped sizes. The analyzer shows parsed size by default. Vercel enforces gzipped. A 300KB parsed module might be 60KB gzipped if it's mostly repetitive code. Toggle the view.
- Duplicate modules across chunks. Middleware is its own chunk. If you see
lodashin both middleware and a server route, that's two copies counted separately.
Step two: the cuts that actually moved the needle
Here's what we did, roughly in order of payoff.
Kill barrel file imports
The single biggest win. We had been doing this:
// middleware.ts
import { verifyToken, getUserFromRequest } from '@/lib';
The @/lib/index.ts barrel re-exported about 40 modules. Even with tree-shaking, the edge bundler in some configurations couldn't eliminate everything, especially modules with side effects or dynamic imports.
The fix is boring and effective:
// middleware.ts
import { verifyToken } from '@/lib/auth/verify-token';
import { getUserFromRequest } from '@/lib/auth/request';
That alone dropped us by ~180KB gzipped. We now have an ESLint rule (no-restricted-imports) that forbids importing from @/lib directly in middleware.ts.
Split edge-safe code into its own package
Anything imported by middleware now lives under @/lib/edge/*. Rules for that directory:
- No Node built-ins (
fs,path,crypto— use Web Crypto instead). - No dependencies over ~30KB gzipped without review.
- No side-effectful imports.
We enforce the first rule with a simple check in CI:
# Fail if anything in lib/edge imports a Node builtin
grep -rE "from ['\"](fs|path|os|child_process|crypto)['\"]" src/lib/edge/ && exit 1 || exit 0
Replace the heavy JWT path
jose is well-engineered, but we were only verifying HS256 tokens from our own auth service. We wrote a ~40-line verifier using crypto.subtle (available in the edge runtime) and dropped the dependency from middleware entirely. The same library still ships to Node routes where we do more complex key handling.
This is the tradeoff worth being honest about: rolling your own JWT verification is a security risk if you're doing anything beyond the simplest case. For HS256 with a single symmetric key, it's a dozen lines and well-tested patterns. For RS256 with JWKS rotation, don't.
Move feature flag evaluation out of middleware
We rolled back the "evaluate flags at the edge" change. The flag SDK was dragging in analytics, polling, and a storage adapter we didn't need. For the handful of routes that genuinely needed edge flag gating, we fetch flag state from a KV store directly with a thin wrapper — about 2KB instead of 160KB.
Step three: guardrails so it doesn't happen again
Cutting the bundle once is easy. Keeping it cut is the real work.
A size budget in CI
We added a check to our GitHub Actions pipeline that fails the build if the middleware chunk exceeds 700KB gzipped — giving us 300KB of headroom before Vercel rejects the deploy.
- name: Check middleware size
run: |
SIZE=$(gzip -c .next/server/middleware.js | wc -c)
echo "Middleware gzipped size: $SIZE bytes"
if [ $SIZE -gt 716800 ]; then
echo "Middleware exceeds 700KB budget"
exit 1
fi
It's crude, but it has caught two near-misses since we added it.
A PR comment with the diff
More useful than the hard cap: a bot comment on PRs that shows the middleware size delta versus main. When someone sees +45KB on a PR that supposedly just renames a function, they investigate. We built this with a small script that runs on both branches and posts the comparison.
An architectural rule
Middleware does three things and only three things: auth check, redirect/rewrite decisions, and request header mutation. Anything else — personalization, flag eval, A/B assignment — happens in the route or in a Route Handler. That rule is written down and reviewed in design docs.
What we won't do
A few things we considered and rejected:
- Splitting middleware into multiple matchers. Vercel runs all matching middleware for a request; you can't shard logic to dodge the limit. You can conditionally import, but dynamic imports at the edge have their own caveats.
- Moving to Node middleware. Next.js has experimented with Node runtime for middleware. Latency cost wasn't worth it for us — our edge middleware runs in single-digit milliseconds, and even a modest increase hurts LCP on cold navigation.
- Paying for a higher limit. Not currently an option in any plan we've seen, and even if it were, the real problem was undisciplined imports, not an undersized limit.
Where we'd start if you're close to the limit
If your middleware is anywhere north of 600KB gzipped today, do these in order:
- Run the bundle analyzer and look at the gzipped treemap, not parsed.
- Audit every import in
middleware.ts— if any of them is a barrel file, replace it with a direct import and re-measure. - Grep for heavy dependencies (
jose,jsonwebtoken, any analytics SDK, anything withpolyfillin the name) and ask whether they actually need to run at the edge. - Add a CI size check with a budget below 1MB so you find out on PR, not on deploy.
- Write down what middleware is allowed to do, and defend that list in code review.
The limit isn't the enemy. It's a forcing function that keeps the edge fast. The team that treats it as a budget from day one never has this incident. If you want a hand auditing an edge setup or tightening a Vercel deployment pipeline, our DevOps and Cloud team does this work regularly.
Want a team like ours?
72Technologies builds production software for the kind of teams who actually read this blog.
Start a projectKeep reading
GCP Cloud Run vs AWS Fargate for Bursty Workloads: A Cost and Cold-Start Breakdown
We ran the same containerized API on Cloud Run and Fargate for six months. Here's what the bills, cold starts, and scaling behavior actually looked like when traffic went sideways.
Pulumi vs Terraform in 2026: A Migration Postmortem
We moved a mid-sized AWS estate from Terraform to Pulumi, then moved part of it back. Here's what the migration actually cost, where Pulumi earned its keep, and where HCL still wins.
Sentry Performance Quotas Blew Up Our Budget: How We Tamed Transaction Volume
We burned through a year of Sentry performance quota in six weeks. Here's what actually caused it, what the dashboards didn't show us, and the sampling rules that brought the bill back under control.
