Skip to content
Source
Sign inSign up
TanStack/router

`setResponseHeaders` and `setResponseStatus` don't work in global middleware #5407

Send to my agent
Closednickprinsloo(GitHub profile, opens in a new tab) opened this issue 1 comment

Which project does this relate to?

Start

Describe the bug

When setting response headers using setResponseHeaders or response status using setResponseStatus in a global middleware server handler, the headers and status are not set.

setResponseHeader works as expected.

Your Example Website or App

https://github.com/nickprinsloo/tss-example

Steps to Reproduce the Bug or Issue

Given the following start.ts:

import { createMiddleware, createStart } from "@tanstack/react-start";
import { setResponseHeaders, setResponseStatus } from "@tanstack/react-start/server";

const requestMiddleware = createMiddleware().server(({ next }) => {
  const headers = new Headers()
  headers.set("X-Hello", "World")
  headers.set("X-Foo", "Bar")
  setResponseHeaders(headers)
  setResponseStatus(404)
  return next()
})

export const startInstance = createStart(() => {
  return {
    requestMiddleware: [requestMiddleware],
  };
});

I'd expect the custom headers + status to be present on the response.

Expected behavior

As a user, I expect to see the headers and status of the response to be those set in the global middleware.

Screenshots or Videos

No response

Platform

  • Start: ^1.132.48
  • Node: v22.19.0
  • macOS Tahoe

Additional context

No response

  1. Ran into this as well.

    Sounds like they're actively working on header manipulation. Root cause is likely related to this parent issue.

    See https://github.com/TanStack/router/pull/5537#issuecomment-3419862262.

    The author of that PR suggested this as a possible workaround. I did have to restart the dev-server though:

    import { createMiddleware, createStart } from "@tanstack/react-start";
    import { setResponseHeaders, getResponseHeaders, setResponseStatus } from "@tanstack/react-start/server";
    
    const requestMiddleware = createMiddleware().server(({ next }) => {
      // Access typed headers
      // -------------VVVVVVVVVVVVVVVVVV
      const headers = getResponseHeaders()
      headers.set("X-Hello", "World")
      headers.set("X-Foo", "Bar")
      setResponseHeaders(headers)
      setResponseStatus(404)
      return next()
    })
    
    export const startInstance = createStart(() => {
      return {
        requestMiddleware: [requestMiddleware],
      };
    });
  2. schiller-manuel(GitHub profile, opens in a new tab) added labelsneeded-for-start-stable

Sign in to join this conversation.