TanStackT
TanStack2mo ago
4 replies
faint-white

How to short-circuit in auth middleware?

The pattern is simple- if auth session is available, add it to the context and pass it down the chain (so downstream server functions don't have to check that), and if not, we want to return early; but what is the idiomatic way to short-circuit a middleware? I tried to throw a 401
Response
, but that broke the server (500); can't just return a Response either, because middleware is expected to return a ServerRequestResult, and in that case, I'm not sure how to set the context property correctly so the types match, between the authenticated and unauthenticated cases. Any insight or advice is much appreciated, thanks.

const authMiddleware = createMiddleware().server(async ({ next, request }) => {
    const auth = await authServer.api.getSession({
        headers: request.headers,
    });

    // How to short-circuit if not authenticated?
    if (!auth) {
        // TODO throwing 401 response causes 500
        // throw new Response('Unauthorized', { status: 401 });
    }

    return next({
        context: { auth },
    });
});
What is Middleware? Middleware allows you to customize the behavior of both server routes like GET/POST/etc (including requests to SSR your application) and server functions created with createServerF...
Middleware | TanStack Start Solid Docs
Was this page helpful?