TanStackT
TanStack14mo ago
64 replies
clean-aquamarine

Redirect from Middleware

Hello, is it possible to redirect from a middleware function? It doesn't seem to be working correctly for me when calling a serverFn from the client when the middleware would throw the redirect. I am using useServerFn for the serverFn, but not sure if there's an equivalent hook that is needed for the middleware as well; currently just getting the following error in the console:
react-dom_client.js?v=a8826ad7:6490 Uncaught Error: Switched to client rendering because the server rendering errored:

{to: ..., isRedirect: true, statusCode: ...}


Below is the code from the middleware
export const authMiddleware = createMiddleware().server(async ({ next }) => {
  const request = getWebRequest();
  const authResp = await auth.api.getSession({ headers: request.headers });
  const user = authResp?.user;

  if (!user) {
    throw redirect({ to: "/sign-in" });
  }

  return next({ context: { user } });
});
Was this page helpful?