T
TanStack3mo ago
aware-green

Returning in middleware

Hi, I'm just getting started with TanStack Start. Right now I'm trying to do something like:
export const authMiddleware = createMiddleware({ type: 'function' }).server(async ({ next }) => {
const h = getHeaders();

if (h['x-auth'] !== 'good') {
setResponseStatus(403);
return json({ error: 'Forbidden' });
}

return next();
});
export const authMiddleware = createMiddleware({ type: 'function' }).server(async ({ next }) => {
const h = getHeaders();

if (h['x-auth'] !== 'good') {
setResponseStatus(403);
return json({ error: 'Forbidden' });
}

return next();
});
but this gives a type error and doesn't seem to work. How do I return in a middleware? Or should I be using something else for this?
2 Replies
absent-sapphire
absent-sapphire3mo ago
I think with the middleware you have to return with next(). You will pass the json as part of the context.
return next({
context: {error: 'Forbidden'},
})
return next({
context: {error: 'Forbidden'},
})
or with what you are trying to do. Throw an error instead
throw new Error('Forbidden');

throw new Error('Forbidden');

fair-rose
fair-rose3mo ago
you can also do
throw json({error: "Forbidden"}, {status: 403})
throw json({error: "Forbidden"}, {status: 403})

Did you find this page helpful?