Skip to content
Source
Sign inSign up
TanStack/router

`setResponseStatus` does not work anymore with `throw new Error(...)` #5107

Closedviclafouch(GitHub profile, opens in a new tab) opened this issue 2 comments

Which project does this relate to?

Start

Describe the bug

Classic code I have in my better auth with TS project for a long time :

export const authUserRequiredMiddleware = createMiddleware({
  type: 'function'
}).server(async ({ next }) => {
  const { headers } = getWebRequest()

  const session = await auth.api.getSession({
    headers,
    query: {
      // ensure session is fresh
      // https://www.better-auth.com/docs/concepts/session-management#session-caching
      disableCookieCache: true
    }
  })

  if (!session) {
    setResponseStatus(401)
    throw new Error('Unauthorized')
  }

  return next({ context: { user: session.user } })
})

I'm pretty sure I had the correct status code (401) with my Unauthorized message.

Now, I got a 500 in any case.. I would like to throw with a custom status code. Not sure if there is a regression or is it me ?

Your Example Website or App

https://codesandbox.io/p/devbox/bold-johnson-3ly6mc?workspaceId=ws_VUPqXCcptK4abDwy6H7mEq

Steps to Reproduce the Bug or Issue

  1. Go to https://codesandbox.io/p/devbox/bold-johnson-3ly6mc?workspaceId=ws_VUPqXCcptK4abDwy6H7mEq
  2. Click on the button
  3. Check network tab
  4. Check that we got 500 instead of 401

Expected behavior

As a user (not logged), I should get a 401 status instead of 500.

Screenshots or Videos

No response

Platform

  • Router / Start Version: 1.131.36
  • OS: Mac
  • Browser: Chrome
  • Browser Version: 139.0.7258.155
  • Bundler: Vite
  • Bundler Version: 7.0.0

Additional context

I think i worked a few weeks ago. 80% sure.

  1. schiller-manuel(GitHub profile, opens in a new tab) added labelsrevisit-after-rc

  2. does this issue still exist on the latest version?

  3. schiller-manuel(GitHub profile, opens in a new tab) added labelsneeded-for-start-stable

  4. schiller-manuel(GitHub profile, opens in a new tab) removed labelsrevisit-after-rc

  5. This is fixed on current main. I reproduced the original behaviour on v1.131.36, where setting the response status to 401 and then throwing from function middleware returned 500. The same production server-function request now returns 401 in Chromium.

    The relevant response handling change landed through #5189 and was available from v1.132.0.

    If this still happens on a current version, please open a new issue with an updated reproduction.

Sign in to join this conversation.