T
TanStack2mo ago
stormy-gold

Extending createServerFn

Hello! I want to extend createServerFn so that it is run with an authentication middleware like this:
import { createServerFn } from "@tanstack/react-start";
import { authenticationMiddleware } from "@/middleware/authentication-middleware";

export const createProtectedServerFn = (
...args: Parameters<typeof createServerFn>
) => {
const fn = createServerFn(...args);
return fn.middleware([authenticationMiddleware]);
};
import { createServerFn } from "@tanstack/react-start";
import { authenticationMiddleware } from "@/middleware/authentication-middleware";

export const createProtectedServerFn = (
...args: Parameters<typeof createServerFn>
) => {
const fn = createServerFn(...args);
return fn.middleware([authenticationMiddleware]);
};
I get build failure when I call this function. It says Rollup failed to resolve import "tanstack-start-injected-head-scripts:v" from... Any help please?
8 Replies
foreign-sapphire
foreign-sapphire2mo ago
i mean, just use the middleware normally you can't do that anyway, because it's compile time magic
stormy-gold
stormy-goldOP2mo ago
Thanks @notKamui Actually I want to use auth middleware for all my server functions BUT not for a small set of them. I can implement a global middleware at start applied for all server functions but I guess there is no way to set a server function skip the global middleware right?
foreign-sapphire
foreign-sapphire2mo ago
i don't think so no, unfortunately unless your global auth middleware throws a special error, that is only caught by a specific non auth middleware that you add to that small set of unauthed functions which should make it work, but is pretty dumb (because the auth check still happens and is just ignored)
stormy-gold
stormy-goldOP2mo ago
ok then I'll continue to decorate most of my createServerFn() calls with .middleware([authenticationMiddleware]) have a great day @notKamui!
foreign-sapphire
foreign-sapphire2mo ago
you too !
adverse-sapphire
adverse-sapphire2mo ago
you can do this
const createAuthenticatedFn = createServerFn().middleware([...])

const myAuthenticatedFn = createAuthenticatedFn().handler(...)
const createAuthenticatedFn = createServerFn().middleware([...])

const myAuthenticatedFn = createAuthenticatedFn().handler(...)
foreign-sapphire
foreign-sapphire2mo ago
oh
stormy-gold
stormy-goldOP2mo ago
thank you @Manuel Schiller!

Did you find this page helpful?