next.js: Server functions silently return undefined when response Content-Type is not RSC

Verify canary release

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

Provide environment information

Operating System:
      Platform: darwin
      Arch: arm64
      Version: Darwin Kernel Version 22.3.0: Mon Jan 30 20:39:46 PST 2023; root:xnu-8792.81.3~2/RELEASE_ARM64_T6020
    Binaries:
      Node: 18.13.0
      npm: 8.19.3
      Yarn: 1.22.19
      pnpm: 7.29.1
    Relevant packages:
      next: 13.4.5-canary.3
      eslint-config-next: 13.3.4
      react: 18.2.0
      react-dom: 18.2.0
      typescript: 5.0.4

Which area(s) of Next.js are affected? (leave empty if unsure)

App directory (appDir: true)

Link to the code that reproduces this issue or a replay of the bug

https://codesandbox.io/p/sandbox/server-functions-intercept-undefined-i4gedd

To Reproduce

Click the button, check the console for output

The important steps:

  • Server function gets called from client
  • Middleware intercepts request and returns something like a 401 (redirects work as expected though)

Describe the Bug

The reason I believe this is a bug is because right now it’s essentially impossible to differentiate between a server function call that succeeded but returned undefined, and one that failed because some middleware (or something else), intercepted it. The common case, and what I hit, is probably auth middleware.

I’ve tracked the behaviour to server-action-reducer:

  • If not a FlightResponse and not a redirect, fetchServerAction returns empty object
  • If not redirect and no actionFlightData, the serverActionReducer falls through to here and resolves with actionFlightData, which is undefined

Expected Behavior

Should probably reject with an error, possibly including the status code of the response which might be valuable in this case?

Which browser are you using? (if relevant)

No response

How are you deploying your application? (if relevant)

No response

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Reactions: 37
  • Comments: 33 (2 by maintainers)

Commits related to this issue

Most upvoted comments

guys, i don’t know if this is the best approach but adding the header “next-action” to “missing” in the config has solved the problem, for me.

my middleware file looks like this:

import { NextRequest, NextResponse } from "next/server";
import { generateCSP } from "./lib/generate-csp";
import { generateNonce } from "./lib/generate-nonce";
import { directives } from "./config/directives";

export const middleware = (req: NextRequest) => {
  const nonce = generateNonce();

  const cspHeader = generateCSP(directives({ nonce }));

  const requestHeaders = new Headers(req.headers);

  requestHeaders.set("x-nonce", nonce);

  requestHeaders.set("content-security-policy", cspHeader);

  return NextResponse.next({
    headers: requestHeaders,
    request: {
      headers: requestHeaders,
    },
  });
};

export const config = {
  matcher: [
    {
      source: "/((?!api|_next/static|_next/image|favicon.ico).*)",
      missing: [
        { type: "header", key: "next-router-prefetch" },
        { type: "header", key: "next-action" },
        { type: "header", key: "purpose", value: "prefetch" },
      ],
    },
  ],
};

Subtle difference, but this is what worked for me. Do not include headers: requestHeaders, but use request: { ... } instead.

import { env } from "@/env";
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";

export async function middleware(req: NextRequest) {
	const requestHeaders = new Headers(req.headers);
	requestHeaders.set("x-auth-token", `Bearer ${env.AUTH_TOKEN}`);

	const response = NextResponse.next({
		// !-- do not do this (next line) as it will break server actions
		// !-- headers: requestHeaders,
		// instead, do this
		request: {
			headers: requestHeaders,
		},
	});
	return response;
       }

I don’t know if it is the same issue but for me server actions return undefined when I return something like return NextResponse.next({ headers: requestHeaders, request: { headers: requestHeaders, }, }); From a middleware function. Without setting the headers it works perfectly.

I’m experiencing this right now. If I remove middleware, the server action works.

hey everyone, just wanted to let you know that i’m currently working on fixing some outstanding server action bugs and this is on my list, it should be fixed soon!

After some research - we have to differentiate between request and response headers correctly.

To set some custom response headers we can do it like this:

export function middleware(request: NextRequest) {
  // We shouldn't clone request headers here because we are setting response headers.
  const rewritedHeaders = new Headers();

  return  NextResponse.next({
    headers: rewritedHeaders,
  });
}

To set request headers:

export function middleware(request: NextRequest) {
  // We have to clone request headers here because we are passing them further
  const rewritedHeaders = new Headers(request.headers);

  return  NextResponse.next({
    request: {
       headers: rewritedHeaders,
    }
  });
}

This way Server actions are working fine (at least on newest Next.js 14.2.8) and our headers are set correctly.

In my case, the problem is caused by conflict content-type returned from server actions, which leads to isFlightResponse check failed.

image

Solution

Hope nextjs official can fix this, but before their solution, we can fixed it by this:

const fixContentType = 'text/x-component'

export function middleware(request: NextRequest) {
  const rewritedHeaders = new Headers(request.headers);
  const response =  NextResponse.next({
    headers: rewritedHeaders,
  });
  if (process.env.NODE_ENV === 'development') {
    // this only occurs during development
    if (response.headers.get('accept') === fixContentType) {
      response.headers.set('content-type', fixContentType)
    }
  }
  return response
}

Here is my solution for headers in middleware

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
  const response = NextResponse.next({
    request: {
      headers: request.headers,
    },
  });

  response.headers.set('x-current-path', request.nextUrl.pathname);

  return response;
}

I ended up implementing @nicholas-yo’s solution. However, I’m concerned this approach might bypass any middleware that handles security responsibilities. Could this be a potential issue?

@nicholas-yo thank you so much for sharing that, it resolved my issue! Lost over a day trying to get this working with my existing RHF forms with vanilla actions and useFormState with no luck. Setup next-safe-actions only to also end up getting undefined response even though I could finally see the data coming back whereas vanilla actions were returning an empty body. I have middleware setup for supertokens and adding that missing block got it working as expected!

@Ephem - can you try this and see if it resolves your problem, and close this out?

This kind of issue reminds me sometimes it’s good to have a spare dummy project to test things out when hitting problems. Gives a sanity check as to whether you are doing something wrong, the system is broken, or something specific to your project configuration as is the case here.

I am facing similar issue and not even using middlware.tsx

After some research - we have to differentiate between request and response headers correctly.

To set some custom response headers we can do it like this:

export function middleware(request: NextRequest) {
  // We shouldn't clone request headers here because we are setting response headers.
  const rewritedHeaders = new Headers();

  return  NextResponse.next({
    headers: rewritedHeaders,
  });
}

To set request headers:

export function middleware(request: NextRequest) {
  // We have to clone request headers here because we are passing them further
  const rewritedHeaders = new Headers(request.headers);

  return  NextResponse.next({
    request: {
       headers: rewritedHeaders,
    }
  });
}

This way Server actions are working fine (at least on newest Next.js 14.2.8) and our headers are set correctly.

Thank you! I’ve also have spent long time on this issue and this fix solves it correctly

Just spent ages trying to figure out why my server action was returning undefined until I came across this article. Can someone explain the logic behind this? A simple request header change in middleware should not complete mess up server actions… Here is my middleware:

export async function middleware(req: NextRequest) {
	req.headers.append("x-auth-token", `Bearer ${env.X_AUTH_TOKEN}`);
	return NextResponse.next({
		headers: req.headers,
	});
}

Running into the same problem when adding custom headers. Server actions returning undefined when this middleware is active. Without it, server actions return the expected response…

export function middleware(request: NextRequest) {
  const headers = new Headers(request.headers);
  headers.set("x-current-pathname", request.nextUrl.pathname);
  headers.set(
    "x-current-search-params",
    request.nextUrl.searchParams.toString()
  );
  return NextResponse.next({ headers });
}

Seems like editing headers changes the Content-Type. Using the following solution did fix it. What a mess honestly. Does it have any security implications?

In my case, the problem is caused by conflict content-type returned from server actions, which leads to [isFlightResponse]

const fixContentType = 'text/x-component'

export function middleware(request: NextRequest) {
  const rewritedHeaders = new Headers(request.headers);
  const response =  NextResponse.next({
    headers: rewritedHeaders,
  });
  if (process.env.NODE_ENV === 'development') {
    // this only occurs during development
    if (response.headers.get('accept') === fixContentType) {
      response.headers.set('content-type', fixContentType)
    }
  }
  return response
}

In case the middleware has some security responsibility adding { type: "header", key: "next-action" } will bypass the middleware.