T
TanStack2h ago
stormy-gold

Server function middleware's aren't receiving the request object

Could someone help me out here, think I might be missing something obvious. I would expect this middleware to log out the request object so it can be used for authentication etc.
import { createMiddleware, createServerFn } from '@tanstack/react-start';

const logRequestMiddleware = createMiddleware({ type: 'request' }).server(async (args) => {
const { next, request } = args;
console.log('request:', request);
return next();
});

export const demoNames = createServerFn()
.middleware([logRequestMiddleware])
.handler(() => {
return ['Alice', 'Bob', 'Charlie'];
});
import { createMiddleware, createServerFn } from '@tanstack/react-start';

const logRequestMiddleware = createMiddleware({ type: 'request' }).server(async (args) => {
const { next, request } = args;
console.log('request:', request);
return next();
});

export const demoNames = createServerFn()
.middleware([logRequestMiddleware])
.handler(() => {
return ['Alice', 'Bob', 'Charlie'];
});
But instead the log is always undefined being invoked from both route loader and useQuery:
import { createFileRoute } from '@tanstack/react-router';
import { demoNames } from '@/server/functions/demoNames';
import { useQuery } from '@tanstack/react-query';

export const Route = createFileRoute('/demo/start/api-request')({
component: Home,
loader: async () => {
return {
names: await demoNames(),
};
},
});

function Home() {
const { names } = Route.useLoaderData();

const otherNames = useQuery({
queryKey: ['names'],
queryFn: () => demoNames(),
});

return (
<ul>
{names.map((name) => (
<li key={name}>{name}</li>
))}
</ul>
);
}
import { createFileRoute } from '@tanstack/react-router';
import { demoNames } from '@/server/functions/demoNames';
import { useQuery } from '@tanstack/react-query';

export const Route = createFileRoute('/demo/start/api-request')({
component: Home,
loader: async () => {
return {
names: await demoNames(),
};
},
});

function Home() {
const { names } = Route.useLoaderData();

const otherNames = useQuery({
queryKey: ['names'],
queryFn: () => demoNames(),
});

return (
<ul>
{names.map((name) => (
<li key={name}>{name}</li>
))}
</ul>
);
}
On version 1.132.31
3 Replies
harsh-harlequin
harsh-harlequin2h ago
createMiddleware({ type: 'function' }) and then use getRequest inside it
stormy-gold
stormy-goldOP2h ago
ah that has worked thank you! it is a little confusing as docs say function type is a subset of request, so would have expected a request middleware to still receive the request on function calls. It means having to maintain separate middlewares for route requests and function calls I guess
absent-sapphire
absent-sapphire1h ago
might be a bug. can you please create a GitHub issue including a complete reproducer example?

Did you find this page helpful?