TanStack Start: how to return a response from a server middleware? #3627
-
Hi, I've been trying to build an authentication middleware for my TanStack Start app but I could not find out how to create how to halt the execution and return a response to the client if the user is not logged-in. I've tried something like export const authMiddleware = createMiddleware().server(async (ctx) => {
const request = getWebRequest();
invariant(request, 'Request not found');
const { session, user } = (await auth.api.getSession(request)) ?? {
session: null,
user: null,
};
if (!session) {
await sendWebResponse(new Response('Unauthenticated', { status: 401 }));
return; // <--- results in typescript complaining about the return type
}
return ctx.next({
sendContext: {
session,
user,
},
});
}); But Typescript complains about the return type:
What is the right way of returning a response directly and to prevent other middlewares and the server function from executing? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
you would need to throw a redirect or an Error |
Beta Was this translation helpful? Give feedback.
you would need to throw a redirect or an Error