Skip to content
Websites

Edge vs Node.js Runtime for Next.js API Routes

•
22 min read
•
a robot with a light saber
Share:

Edge functions run in a restricted JavaScript environment that lacks many Node.js APIs, and Vercel's edge runtime documentation lists the modules you lose. An edge runtime is a lightweight JavaScript environment that executes API route code at points of presence close to the user, while the Node.js runtime gives you the full package ecosystem in the regions you configure. For a multi-location operator, that choice decides whether a booking, quote, or lookup responds quickly in every market or only where your primary server sits. This post compares both runtimes on latency, cost per request, database connectivity, and package compatibility, then gives a decision rule for each API route.

What You'll Learn

  • What the Edge and Node.js runtimes actually are in Next.js route handlers and middleware, and where each one executes.
  • The practical differences in cold starts, supported Node APIs, execution limits, and database connectivity.
  • Which types of API routes (forms, auth checks, redirects, personalization, database writes) belong on the Edge and which do not.
  • How runtime choice affects time to first byte, Core Web Vitals, and regional latency for visitors across many locations.
  • A decision checklist and migration sequence for moving individual routes without breaking lead capture or conversion tracking.

What Is the Edge Runtime vs the Node.js Runtime in Next.js?

Next.js lets you choose where a route handler or middleware runs. The two options are the Node.js runtime and the Edge runtime. The choice sets which APIs your code can call, where it executes, and how quickly it responds. You set it per route with export const runtime = 'edge' in the route file. Omit the line to use Node.js.

What the Node.js Runtime Is

The Node.js runtime is the full server environment. It runs on a regional server or a serverless function. Your code can use the complete Node.js API, including file system access, native npm packages, and persistent database connections.

Common uses include:

  • Database queries that rely on a connection pool
  • PDF generation and image processing
  • Libraries that depend on native Node.js modules
  • Webhook handlers that call third-party SDKs

What the Edge Runtime Is

The Edge runtime is a lighter environment. It runs on a provider's edge network, which places code in many points of presence (PoPs) around the world. It uses web-standard APIs such as fetch, Request, and Response.

The Edge runtime does not expose every Node.js API. Some packages that work in Node.js will fail on the edge without changes.

Common uses include:

  • Redirects and rewrites based on location or headers
  • A/B test assignment before a page loads
  • Cookie-based auth checks that return early
  • Small JSON responses that need low latency

Where Each Runtime Executes

  1. Edge: The request runs at the PoP nearest the visitor, often in the same metro area.
  2. Node.js: The request travels to one region, such as a single data center, where the function lives.

Consider a hypothetical 40-location HVAC group whose customers sit in dozens of cities. An edge handler can answer a cookie check in the visitor's city. A Node.js handler in one region adds the round trip to every visitor who is far from that region.

The difference matters most on the first hop. It matters less when the route spends most of its time on a slow database query, because the query time dominates either way.

The Core Trade-Off

Edge trades compatibility for proximity. Node.js trades proximity for full capability. Pick the Edge runtime when the work is short, stateless, and needs to happen close to the visitor. Pick the Node.js runtime when the route touches a database, a native library, or heavy compute.

Many production apps split the two. They run edge middleware for routing and light checks, then send data work to Node.js handlers. Teams that need help mapping routes to runtimes can work with our custom software team or our websites team.

Key Insight: Use the Edge runtime for fast, stateless decisions near the visitor. Use the Node.js runtime for anything that needs full Node.js APIs, database connections, or native packages.

Edge vs Node.js Runtime: Key Differences for API Routes

The Edge runtime and the Node.js runtime both run Next.js API routes, but they make different trade-offs. Edge runs code in a lightweight, restricted environment close to the caller. Node.js runs code in a full server environment with the standard Node library. Most of the decisions below come from that one difference.

Side-by-side comparison

FactorEdge runtimeNode.js runtime
Cold startUsually faster, less code to loadSlower, loads a full runtime
Node.js APIsSubset of web-standard APIsFull set of built-in modules
File system accessNone, no persistent diskRead and write local files
Native modulesNot supportedSupported
Database driversHTTP or edge-compatible driversStandard TCP drivers work
Execution durationShort limits, measured in secondsLonger limits, set by host plan
Bundle sizeTight compressed size capLarger allowance

Platform limits change often. Cold start behavior, duration caps, and bundle size ceilings shift with each platform release. Check current platform docs before you choose a runtime.

Cold start and execution time

Cold start is the delay before a function handles its first request after being idle. Edge functions usually start faster because they load less code. For a 40-location group that receives a burst of booking requests each morning, that gap is visible to customers.

Execution duration matters just as much. Edge suits short tasks that finish quickly, such as:

  • Checking an auth token
  • Redirecting a request
  • Returning a cached JSON response
  • Running a simple A/B test split

Longer jobs belong on Node.js. These include PDF generation, image processing, and multi-step data imports. If a job runs past the edge limit, the timeout shows up in production, not in your local tests.

APIs, file system, and native modules

Edge functions use web-standard objects such as fetch, Request, and Response. Many Node.js built-ins, including fs and child_process, are unavailable. An npm package that depends on a native binary will fail on Edge.

Edge also has no persistent disk. A route that writes temporary files or logs locally will lose that data between requests. Move that work to object storage or a queue. Node.js can read and write local files, although many serverless hosts treat that disk as temporary too.

Database drivers and bundle size

Most traditional database drivers open raw TCP connections. Many edge environments cannot open those sockets. Teams usually switch to an HTTP-based driver or a connection pooler to make Edge work.

Bundle size is the last constraint. Large ORMs, PDF libraries, and image tools can push an Edge route past the compressed size cap. Node.js tolerates heavier dependencies, so dependency-heavy routes usually belong there.

Which runtime fits your API routes

Use this rule of thumb:

  1. Pick Edge for lightweight, latency-sensitive logic like auth checks, redirects, and cached reads.
  2. Pick Node.js for database writes with standard drivers, file work, native modules, and reporting.
  3. Test any route that sits near a limit under production-like load before you commit.

Teams that run many routes across several regions often split them between both runtimes. If you need help mapping which routes belong where, our custom software team can review your API surface and recommend a split.

Key Insight: Choose the runtime by what the route must do, not by which one is newer. Edge wins on speed for small, stateless tasks, while Node.js wins on compatibility for anything heavy.

Which Next.js API Routes Should Run on the Edge?

The Edge runtime suits small, fast, stateless work. A route fits when it can answer from the request alone. It should not need a database query, a file read, or a background job. Six route types pass that test.

  1. Lead form validation. The route checks required fields, email format, phone pattern, and a hidden spam field. It returns an error or passes the lead forward. Only the submitted data is needed, so no stored session is required.
  2. Geo-based redirects. A visitor from Tampa lands on the Tampa page. A visitor from Orlando lands on the Orlando page. The platform attaches country and region data to each request, and the route reads it before the page loads.
  3. A/B split logic. The route assigns each visitor to version A or B. It sets a cookie so the same visitor sees the same version on return. The logic is a few lines of code.
  4. Auth token checks. The route reads a signed token and verifies its signature and expiry date. It can block or allow the request before it reaches the origin server.
  5. Header manipulation. The route adds security headers, cache rules, or request IDs. It can also remove headers that should never reach the browser. These steps repeat on every request.
  6. Personalized rewrites for location pages. One route maps a shared URL, such as /plumbing/, to the city page that fits the visitor. The visitor sees a relevant page without an extra trip to the origin.

Why these routes are stateless and latency-sensitive

Each route above reads the incoming request and returns a response. It does not need to remember the previous request. That makes it stateless, so it can run in any data center without coordination.

These routes are also latency-sensitive. A form that stalls, or a redirect that flashes a blank page, costs the visitor patience. Running the logic close to the visitor removes a round trip to a distant server.

For a 40-location service group, the math is simple. Each location page that loads fast and lands on the right city keeps a lead in the funnel. Each slow page gives that lead a reason to call a competitor.

What Edge code must leave out

Edge runtimes support a subset of the Node.js API. Heavy packages often fail there or inflate the bundle. Keep these out of Edge routes:

  • Full database clients that open persistent connections
  • Image processing and PDF generation libraries
  • Large SDKs for CRM, payment, or analytics tools
  • Anything that reads or writes the local file system
  • Long-running jobs such as report exports

When a route needs one of these, split the work. Let the Edge route handle the quick decision, then call a Node.js route for the heavy task. Teams that want this split designed and built can review our custom software services for multi-location systems.

Key Insight: Put the fast, stateless decision at the Edge and the heavy, stateful work on Node.js. Small Edge bundles keep response times low across every location.

Need help applying this to your business? Tell us about your project and we will scope it with you.

When Node.js Runtime Is the Right Choice for API Routes

Many ORMs and database drivers open a TCP socket to reach the database. Postgres and MySQL drivers built on Node's net module depend on that socket. The Edge runtime does not provide raw TCP, so these calls fail there.

Teams often find this late. The code builds, the preview deploys, and the first real query throws an error. Connection pooling adds a second risk. Each cold start can open new connections, which can exhaust a database's connection limit across many locations at once.

Native and Node-Only Packages

Some packages ship compiled binaries. Others depend on Node modules such as fs, path, or crypto, or on the Buffer global. Edge functions do not run those packages. Common cases include:

  • PDF libraries that read font files from disk
  • Image processing packages with native bindings
  • Older SDKs that load certificates through fs
  • Packages that read environment variables at import time without guards

Long-Running Jobs and Large Payloads

PDF generation, bulk CRM syncs, and report exports take real time. A route that pulls 10,000 contacts from a CRM and writes them to a data warehouse does not belong in a request that must return in seconds. Node functions give you more time and memory for this work. Even so, every platform sets a limit, so split large jobs into queued batches.

Large payloads have their own limits. Multipart uploads and big JSON imports can hit size caps set by the host. Edge bundle sizes and execution limits are usually tighter than standard Node functions. Check the platform's documented limits before you commit a route to either runtime.

Third-Party SDKs That Assume Node Globals

Many SDKs assume Node globals like process, Buffer, or __dirname exist. Some check for them at import time. A billing, email, or analytics SDK that works in local development can crash on import in production.

Test each SDK on the runtime you plan to use. Do not assume a package that worked in a Node-based dev server will work at the edge.

Test Node-Only Paths Explicitly

These failures appear at runtime, not at build time. The Next.js build can succeed while the route returns a 500 on the first database call. Build checks catch syntax errors and static import problems. They miss a socket that only opens when a real request arrives.

Treat each Node-dependent route as its own test target:

  1. Call the route in a preview deployment with real credentials.
  2. Trigger the slowest path, such as the largest payload or the longest job.
  3. Check logs for Node-only module errors after a cold start.
  4. Repeat the test after every dependency upgrade.

This matters most for multi-location operators. One broken route can stop lead capture at every site at once. If you need help mapping which routes belong on Node, a custom software build can audit them before launch.

Key Insight: Any route that opens a database socket, loads a native package, runs a long job, or depends on Node globals belongs on the Node runtime. Prove that with a runtime test in a preview deployment, because a build that passes tells you nothing about these failures.

How Runtime Choice Affects Core Web Vitals and Regional Latency

Runtime choice changes how fast the first byte arrives. It does not change every metric, and the size of the gain depends on where your data lives.

Where edge execution shortens the path

Time to First Byte (TTFB) measures how long a browser waits before the server sends its first response byte. Edge functions run in data centers close to the visitor, so that wait shrinks for dynamic responses. Personalized pricing, geo-gated content, and access checks benefit most.

Edge helps most in three cases:

  1. Personalized responses that read a cookie or header and return a variant.
  2. Redirects and access checks that run before any page renders.
  3. Light transforms, such as localizing a price or trimming a JSON payload.

Largest Contentful Paint (LCP) depends on TTFB on most pages. The browser cannot paint the main content until the HTML arrives. Faster first bytes give the largest element an earlier start.

Where edge execution does not help

Cached static pages already sit on a CDN edge. Moving a function there adds little, because the HTML is already close to the visitor.

Origin-bound database reads are the bigger trap. If your database sits in one region and the visitor sits across an ocean, every query still crosses that distance. A transatlantic round trip adds roughly 70 to 100 milliseconds per hop. A page that makes five sequential queries pays that cost five times.

Edge code that calls a distant database can end up slower than a Node.js function running next to that database.

How INP fits in

Interaction to Next Paint (INP) measures responsiveness after a user taps or clicks. Runtime choice matters less here. INP is driven mostly by client-side JavaScript and main-thread work.

A faster API response helps only when the interface waits on that response before it updates.

The real variable: database location

The gain depends on where the origin database sits relative to visitors. Consider a 40-location service company with customers in one metro area. A Node.js function in the same region as the database will often beat an edge function.

A national brand with customers in every time zone may see the opposite result. Edge code paired with a regional read replica often wins there.

Measure before you migrate. Compare TTFB and LCP by region using field data, not lab tests. If you need help mapping this to your stack, see our custom software services.

Key Insight: Edge runtimes cut first-byte time for personalized responses, but only when the data they need is close to the visitor. Move the database closer to your users first, then decide where the code should run.

Cost per Location: Runtime Economics for Multi-Location Brands

Runtime choice looks like a technical decision, but for a multi-location brand it is a unit-cost decision. The useful question is not what one invocation costs. It is what each location and each lead costs to serve.

Map the Routes That Carry Volume

Traffic on a 40-location site concentrates in a few routes. Not every route deserves the same runtime.

  • Location page renders: one page per city or store, usually the highest volume
  • Form submissions: quote requests, booking forms, and callback requests
  • Availability or lookup calls: hours, service areas, and inventory checks
  • Webhooks and CRM syncs: lower volume, but often slower

Here is an illustrative model. Assume 40 locations, each page drawing 3,000 visits per month, and each location producing 20 form submissions per month. That yields 120,000 page requests and 800 form submissions. Page requests outnumber form submissions roughly 150 to 1.

How Invocations Scale With Locations

Invocations grow with location count, not with lead count. Each new location adds its own page traffic and its own form stream. Add 10 locations to the model above and page requests rise by 25 percent with no change in per-location behavior.

Lead volume is the number that pays the bills. Track invocations by route so you can see which ones multiply fastest.

When Edge Is Cheaper and When Node Is Costlier

Per-invocation pricing favors short work. An Edge handler that returns cached location data in a few milliseconds, with no database round trip, is cheap across 120,000 requests. A regional Node function bills on duration and memory, so a handler that waits two seconds on a slow CRM costs more per call.

The pattern flips for form handlers. A handler that writes to one regional database and calls a CRM can run slower on Edge because of cross-region hops. Regional Node placed near the database often wins on latency and cost.

A simple decision rule:

  1. Cached page renders: test on Edge first.
  2. Form handlers that write to a database: test on regional Node.
  3. Calls to slow third-party APIs: keep on Node with a strict timeout.

Cost per Lead Is the Metric to Track

Use this formula: Cost per lead = monthly runtime cost for lead routes / leads captured. Calculate it per location, then roll it up to the group. A location that costs more to serve but converts more may still be the better investment.

Pull current rates from your host before you run these numbers. This model uses no price figures on purpose, because published rates change. Teams that want the math built against real traffic can start with a custom software build or a runtime audit.

Key Insight: Price the runtime per lead, not per call. Put cached, low-latency pages on Edge and keep database-bound form handlers on regional Node.

Real-World Example: Rebuilding a Next.js Site Around the Right Runtime

DDES is an economic research and workforce development organization. Before the rebuild, it was effectively invisible on Google. Its work was relevant, but the people searching for it could not find it.

Gaazzeebo rebuilt the site as a performance-focused Next.js application. The project included full Search Console integration and optimization for AI and LLM search. The organization moved from invisible to indexed and ranking for high-intent research queries. The DDES case study covers the full scope.

The case study does not publish a traffic or ranking percentage, so none appears here.

Where Each Route Should Run

A rebuild like this forces a decision about where each piece of code runs. Next.js route handlers can run on the Node.js runtime or the Edge runtime. The choice affects latency, cost, and what the code is allowed to do.

We apply a simple rule on builds like this:

  1. Keep data-heavy routes on Node.js. Routes that query databases, call internal services, or parse large payloads need the full Node.js API.
  2. Reserve the Edge for lightweight handlers. Redirects, header rewrites, and locale detection read little data and benefit from running close to the user.
  3. Choose the runtime per route. One Next.js project can mix both. Forcing every route onto one runtime is the most common mistake.

What Transfers to Multi-Location Sites

Multi-location businesses face the same split. Consider a hypothetical 40-location service group. Its site has a location finder, a booking flow, and a lead form. Each location has its own hours, phone number, and service area.

  • Location lookups and redirects can run at the Edge, since they read little data.
  • Booking and lead capture belong on Node.js, where CRM writes and retries are dependable.
  • Schema markup and sitemaps should be generated once and cached, not rebuilt on every request.

This split keeps the fast paths fast and the data paths reliable. It also keeps per-location costs predictable, because the expensive work runs only where it adds value.

If your multi-location site is slow or invisible in search, the websites service is where we start. A short audit will show which routes belong on which runtime.

Key Insight: Put each route on the runtime its work requires. Data-heavy routes stay on Node.js, and the Edge handles lightweight redirects and rewrites.

Edge vs Node.js Runtime Decision Checklist and Migration Steps

Answer these four questions for every route. Record the answers in one row per route.

  1. Does the handler use a Node-only API, such as fs, native modules, or a Node-specific SDK?
  2. Does it open a database connection through a driver that needs raw TCP sockets?
  3. Is it latency-sensitive, where a few hundred milliseconds changes the user outcome?
  4. Is it stateless, so each request stands alone with no in-memory cache or session state?

Routes that answer yes to question 1 or 2 stay on the Node.js runtime. Routes that answer yes to questions 3 and 4, and no to 1 and 2, are candidates for the Edge runtime. Anything unclear stays on Node by default. A wrong move to Edge breaks production. A delayed move costs only a few milliseconds.

Migration sequence

  1. Inventory routes. List every route with its runtime, dependencies, and traffic volume. Sort the list by traffic and risk.
  2. Move one low-risk handler. Choose a read-only, stateless route with modest traffic. Convert it, deploy it to a preview environment, and compare responses against production.
  3. Monitor errors and Core Web Vitals. Track error rate and p95 response time for two weeks. Watch Largest Contentful Paint and Interaction to Next Paint on the pages that call the route.
  4. Expand in batches. Move the next group only after the first handler holds steady. Keep rollback to a single config change.

Multi-location operators need this discipline at every site. A route that performs well for one location can fail under another location's peak traffic. Test each batch against the busiest market first.

How Gaazzeebo approaches route-level decisions

We classify routes centrally before touching any code. The audit covers dependencies, traffic by location, and failure cost. Most multi-location clients end up with a mixed setup: stateless lookups on Edge, and anything touching a database or a third-party SDK on Node.

We applied this route audit when we rebuilt DDES, an economic research organization, on Next.js. The work covered which endpoints could move without risk and which needed to stay put. If you want the same audit for your own stack, start with our custom software practice or request a site and route review.

Key Insight: Move routes one at a time, starting with the stateless and read-only ones. Keep anything that touches a database or a Node-only API on the Node.js runtime until you have data proving the move is safe.

Further reading

Verified primary sources on this topic:

Sources and References

Primary sources cited above:

Share:

Free SEO & Local Visibility Audit

We read your website, and your Google Business Profile when we can match it, the way Google and AI assistants read them. Then we show you the gaps that matter most, ranked by impact, with the evidence and the exact fix for each one. Free. Enter your website and an email address, and the report is emailed to you.

Free SEO audit

Related Articles

More on this topic:

Browse the Websites hub

Take the next step

Want this in your business?

We build websites systems for growing operations, without the agency-speak. Here's where to look next.

Frequently asked questions

What is the difference between the edge runtime and the Node.js runtime for Next.js API routes?

The Node.js runtime gives your route the full Node.js API, native npm packages, file system access, and persistent database connections, running in the regions you configure. The edge runtime is a lightweight JavaScript environment that executes code at points of presence close to the user, but it lacks many Node.js APIs. You choose per route by exporting runtime = 'edge' in the route file; omitting the line uses Node.js. The trade-off is reach versus compatibility: edge code responds closer to visitors, while Node.js code can do more.

Should every API route in my Next.js app run on the Edge runtime?

No. Gaazzeebo's recommendation is to default every API route to Node.js and promote only stateless, latency-sensitive handlers to the Edge after measuring both. Edge fits routes like redirects, simple auth checks, personalization, and lightweight lookups that need fast responses near visitors. Routes that use database connection pools, native modules, PDF generation, or long-running work belong on Node.js. Moving a route without testing can break lead capture or conversion tracking, so verify each one before committing.

Can the Edge runtime connect to my database for booking or lead form API routes?

Usually not with a traditional connection pool. Edge functions run in a restricted environment without many Node.js APIs, so drivers that open persistent TCP connections often fail or need an HTTP-based or serverless-compatible client instead. Node.js routes handle pooled connections directly in your chosen regions. For booking and lead forms that write to a database, Node.js is the safer default. If you do move a form handler to the Edge, confirm your database driver works in that environment and test writes end to end before routing live traffic.

Does the Edge runtime make API routes cheaper and faster for multi-location websites?

It can reduce latency for stateless requests, but it is not automatically cheaper. Edge code runs at points of presence close to visitors, which helps time to first byte for users spread across many markets. Cost per request depends on your platform's pricing and on how much work the handler does, so measure both runtimes with your real traffic. For a multi-location brand with 10 to 150 locations, the gain is largest on per-location lookups and redirects, while database-heavy routes often perform better on Node.js close to the data.

How do I switch a single Next.js API route to the Edge runtime?

Add export const runtime = 'edge' to the top level of that route file, and leave other routes unchanged so they keep the Node.js default. Then confirm the handler uses only APIs available at the edge, since imports of unsupported Node.js modules will fail. Deploy to a preview environment and test the full request path, including form submissions and any tracking calls. Compare time to first byte and error rates against the Node.js version for a few days before promoting the change to production.

Join Our Free Newsletter

One short tip a week on getting found online and putting software to work. Three-minute read, plain English.

No spam. Unsubscribe anytime. We respect your privacy.