Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Next.js and React

Upgrading to Next.js 16: middleware becomes proxy, and the other things that break

ErrorThe "middleware" file convention is deprecated

Short answer

Next.js 16 renames middleware.ts to proxy.ts and its exported function to proxy. Proxy always runs on Node.js, so middleware that needs the Edge runtime stays as middleware for now. The same release makes Turbopack the default bundler, removes synchronous params, cookies and headers, requires Node.js 20.9, and changes revalidateTag and image defaults. Run the codemod, then fix what the build reports.

  • Applies to Next.js 16.0 to 16.4, React 19.2, Node.js 20.9+, TypeScript 5.1+
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Upgrade on a branch, let the official codemod make the mechanical changes, then run a production build. Most breaking changes stop the build or the type check, and the first error names the area. The upgrade codemod does not convert synchronous params or cookies; that has its own codemod (third cause).

    node -v                                    # must be 20.9.0 or newer
    git switch -c upgrade-next-16
    npx @next/codemod@canary upgrade latest
    npx next build 2>&1 | tee build.log
  2. 2Match what you see, then jump to its fix

    1. 1next dev and next build print a deprecation notice for the middleware file convention; after a hand-made rename, the build fails if the file still declares a runtime.middleware.ts is deprecated and becomes proxy.tsFix
    2. 2next build fails because it found a webpack configuration, even one you never wrote (a plugin wrapper can add it); or client code fails with Module not found: Can't resolve 'fs'; or Sass imports that start with ~ stop resolving.Turbopack is now the default, and a webpack config stops the buildFix
    3. 3params.slug or searchParams.page is undefined at runtime, TypeScript says a property does not exist on a Promise type, or the build stops on a leftover @next-codemod-error comment.Synchronous params, searchParams, cookies() and headers() are goneFix
    4. 4TypeScript flags revalidateTag('posts') with Expected 2 arguments, but got 1.; experimental.dynamicIO, experimental.useCache or experimental.ppr no longer exist; unstable_cacheLife and unstable_cacheTag imports need renaming.revalidateTag and the experimental cache flags changedFix
    5. 5Missing Required default.js for Parallel Route; a lint script that calls next lint fails; next/config, serverRuntimeConfig or publicRuntimeConfig no longer work; AMP settings are rejected.The build stops on parallel routes, next lint or runtime configFix
    6. 6/_next/image answers 400 for some images, local images with a ?v= query string stop loading, images from a host on a private IP fail, or a changed image takes hours to appear.Images return 400 or update less often after the upgradeFix

What does the error look like?

  • The "middleware" file convention is deprecated
  • Missing Required default.js for Parallel Route
  • Module not found: Can't resolve 'fs'
  • Expected 2 arguments, but got 1.

Cause 1 of 6

middleware.ts is deprecated and becomes proxy.ts

1Check

Find the file, any runtime key in its config, and config flags that carry the old name. Proxy runs on Node.js only: declaring runtime in a proxy file fails next build even when the value is 'nodejs', and the edge runtime is not available there at all.

ls middleware.* proxy.* src/middleware.* src/proxy.* 2>/dev/null
grep -nE "runtime|skipMiddlewareUrlNormalize" middleware.* src/middleware.* next.config.* 2>/dev/null

2Fix

Run the dedicated codemod: it renames the file and the exported function and removes the runtime key. Confirm skipMiddlewareUrlNormalize became skipProxyUrlNormalize. If the code depends on the Edge runtime, keep middleware.ts for now; it is deprecated but still works for that case.

npx @next/codemod@canary middleware-to-proxy .

// proxy.ts (was middleware.ts)
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

export function proxy(request: NextRequest) {      // was: export function middleware
  if (!request.cookies.has('session')) {
    return NextResponse.redirect(new URL('/login', request.url))
  }
}

export const config = {
  matcher: ['/dashboard/:path*'],                  // no runtime key: proxy is always Node.js
}

3Verify

Build again: the deprecation notice is gone. Then request a protected path without a cookie and confirm the redirect still happens.

npx next build && npx next start
# second terminal
curl -s -o /dev/null -w "%{http_code} %{redirect_url}\n" http://localhost:3000/dashboard
Did this fix it?

Cause 2 of 6

Turbopack is now the default, and a webpack config stops the build

1Check

Look for a webpack function in the config and for wrappers around the exported config, then for Node-only imports reaching client code and tilde imports in stylesheets.

grep -nE "webpack|module.exports = with|export default with" next.config.* 2>/dev/null
grep -rn "@import '~" --include=*.scss . 2>/dev/null | grep -v node_modules

2Fix

Either keep webpack for production with the --webpack flag while you migrate, or move the setup to Turbopack: experimental.turbopack is now the top-level turbopack key, resolveAlias replaces webpack's resolve.fallback, and Sass imports drop the ~. The --turbopack flags in package.json scripts are no longer needed.

// package.json: keep webpack for builds while you migrate
"scripts": { "dev": "next dev", "build": "next build --webpack", "start": "next start" }

// next.config.ts: or move to Turbopack
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  turbopack: {
    // stop-gap only: better to stop importing fs from client code
    resolveAlias: { fs: { browser: './empty.ts' } },
  },
}
export default nextConfig

3Verify

Build again and read the first lines: with Turbopack the header reads Next.js 16 (Turbopack), and the build finishes.

npx next build 2>&1 | head -5
Did this fix it?

Cause 3 of 6

Synchronous params, searchParams, cookies() and headers() are gone

1Check

Next.js 15 still allowed synchronous access with a warning; 16 removed it. Look for the comments the codemod leaves where it could not convert code, then type-check the project.

grep -rn "@next-codemod-error" app src 2>/dev/null
npx tsc --noEmit

2Fix

Run the async request API codemod, then fix what it flagged by hand: await these values in Server Components and route handlers, and unwrap them with React's use() in Client Components. next typegen generates the PageProps, LayoutProps and RouteContext helper types. Image routes (opengraph-image, icon) now receive params and id as promises, and sitemap receives id as a promise.

npx @next/codemod@canary next-async-request-api .
npx next typegen

// app/blog/[slug]/page.tsx
import { cookies } from 'next/headers'

export default async function Page({ params, searchParams }: PageProps<'/blog/[slug]'>) {
  const { slug } = await params
  const { page = '1' } = await searchParams
  const theme = (await cookies()).get('theme')?.value
  return <Post slug={slug} page={Number(page)} theme={theme} />
}

3Verify

The type check and the build pass, and a dynamic route renders with its parameter.

npx tsc --noEmit && npx next build
curl -s http://localhost:3000/blog/hello-world | grep -c "hello-world"
Did this fix it?

Cause 4 of 6

revalidateTag and the experimental cache flags changed

1Check

List every cache call and every old flag so you can decide the intended behaviour of each, rather than adding a second argument blindly.

grep -rnE "revalidateTag\(|unstable_cache(Life|Tag)|dynamicIO|useCache|experimental_ppr|ppr:" \
  app src lib next.config.* 2>/dev/null

2Fix

revalidateTag(tag, 'max') marks data stale and keeps serving the old copy while it refreshes in the background. updateTag(tag), allowed only in Server Actions, expires the data and reads it fresh in the same request, so a user sees their own edit. Import cacheLife and cacheTag without the prefix. Delete the old flags; enable cacheComponents only if you are adopting that model, because it is not a rename and can surface new build errors for uncached data outside Suspense.

'use server'
import { revalidateTag, updateTag } from 'next/cache'

export async function publishPost(id: string) {
  await db.posts.publish(id)
  revalidateTag('posts', 'max')   // listings: a short stale window is fine
  updateTag(`post-${id}`)         // the editor's own page: fresh in this request
}

3Verify

The type check passes, and after saving in the editor the post page shows the new value on the next render without a manual reload.

npx tsc --noEmit && npx next build
Did this fix it?

Cause 5 of 6

The build stops on parallel routes, next lint or runtime config

1Check

Every slot folder (a folder whose name starts with @) now needs its own default file. Then look for the removed commands and options.

for d in $(find app src/app -type d -name '@*' 2>/dev/null); do
  ls "$d"/default.* >/dev/null 2>&1 || echo "no default file: $d"
done
grep -rnE "next lint|serverRuntimeConfig|publicRuntimeConfig|next/config|useAmp" \
  package.json next.config.* app src pages 2>/dev/null

2Fix

Add a default file to each slot that returns null, or calls notFound() to keep the old 404. Replace next lint with the ESLint CLI (the codemod rewrites the scripts; next build no longer lints). Move runtime config to environment variables: NEXT_PUBLIC_ for values the browser needs, and call connection() before reading process.env when the value must be read per request rather than baked in at build time.

// app/@modal/default.tsx
export default function Default() {
  return null
}

npx @next/codemod@canary next-lint-to-eslint-cli .

// app/support/page.tsx: replaces getConfig().serverRuntimeConfig
import { connection } from 'next/server'

export default async function Page() {
  await connection()
  return <p>{process.env.SUPPORT_EMAIL}</p>
}

3Verify

The build passes, the lint script runs on its own, and a direct load of a URL that only one slot matches renders the fallback instead of failing.

npx next build
npx eslint .
Did this fix it?

Cause 6 of 6

Images return 400 or update less often after the upgrade

1Check

Request the optimizer directly with the quality and URL a failing image uses. In 16 only quality 75 is allowed by default, local sources with query strings need a matching pattern, local-IP sources are blocked, redirects stop after 3, and optimized images are cached for at least 4 hours.

curl -s -o /dev/null -w "%{http_code}\n" "http://localhost:3000/_next/image?url=%2Fhero.jpg&w=1080&q=90"

2Fix

List every quality you use; a quality prop outside the list is rounded to the nearest allowed value, but direct requests with other values get 400. Allow query strings on local images with localPatterns, set dangerouslyAllowLocalIP only on a private network, and lower minimumCacheTTL if 4 hours is too long for your images.

// next.config.ts
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  images: {
    qualities: [75, 90],
    localPatterns: [{ pathname: '/assets/**', search: '?v=2' }],
    minimumCacheTTL: 300,          // seconds; the new default is 14400
    // dangerouslyAllowLocalIP: true,   // only if the image host resolves to a private IP
  },
}
export default nextConfig

3Verify

The same request now returns 200, and the page shows the image.

curl -s -o /dev/null -w "%{http_code}\n" "http://localhost:3000/_next/image?url=%2Fhero.jpg&w=1080&q=90"
Did this fix it?

How do I stop it coming back?

  • Pin Node.js 20.9 or newer in package.json engines and in the CI image before upgrading the framework.
  • Upgrade on a branch: codemods, then type check, build and an end-to-end run, because a green build does not prove the redirects, caching and images still behave.
  • Keep proxy small and check authorization again inside each Server Function; a matcher change can quietly stop proxy from running for them.
  • Read the deprecation lines in every build log; later 16.x releases removed more experimental flags.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.