Skip to content

[NextJS 14] - Middleware + output: 'export' is no longer working from Next 13+ #57695

@ShanonJackson

Description

@ShanonJackson

Link to the code that reproduces this issue

https://github.com/ShanonJackson/next-issue-output-export

To Reproduce

1: Create application with output: export (in next.config.js)
2: Create middleware.tsx in the root of the directory
3: Run npm run dev
4: Note the error in the terminal and middleware not working.

Current vs. Expected behavior

Current behavior in Next 13 is that there is no warning or error.
Expected behavior should be at most a warning letting people know that static deployments will not use middleware.

The reason why I believe this should be the expected behavior is that there's use cases for middleware that are only applicable for
development.

For example we use middleware currently to rewrite requests to a legacy CRA application if they're not hitting a NextJS route.

/*
    return undefined = route to next
    return rewrite = route to legacy application hosted.
*/
export async function middleware(request: NextRequest) {
	const path = new URL(request.url).pathname;
	if (path.includes("_next")) return undefined;
	if(path === "/next-page-example") return undefined;
	if(path ==== "/about") return undefined
	return NextResponse.rewrite(new URL(path, String(process.env.NEXT_PUBLIC_CRA_HOST)));
}

When we deploy our application we discard middleware and have a matching configuration in our gateway that does the same thing.

Verify canary release

  • I verified that the issue exists in the latest Next.js canary release

Provide environment information

Binaries:
  Node: 18.18.2
  npm: N/A
  Yarn: N/A
  pnpm: N/A
Relevant Packages:
  next: 14.0.1-canary.2
  eslint-config-next: 14.0.0
  react: 18.2.0
  react-dom: 18.2.0
  typescript: 5.2.2
Next.js Config:
  output: export

Which area(s) are affected? (Select all that apply)

Middleware / Edge (API routes, runtime), Static HTML Export (output: "export")

Additional context

Currently prevents upgrading many projects from 13 -> 14.

Workarounds for those that find themselves in a similar boat. This setup will enable middleware on dev mode, and hide the file before production build starts.

output: process.env.NODE_ENV === "development" ? undefined : "export",
"scripts": {
    "build:ci": "node ./scripts/prebuild && next build",
 }
 // .scripts/prebuild
 require("fs").renameSync("./middleware.tsx", "./_middleware.tsx", "utf-8");

Metadata

Metadata

Assignees

No one assigned

    Labels

    RuntimeRelated to Node.js or Edge Runtime with Next.js.bugIssue was opened via the bug report template.staleThe issue has not seen recent activity.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions