T
TanStack12mo ago
flat-fuchsia

Possible to call a server function within an api route?

I can't get around this error: createServerFn must be called with a function that is marked with the 'use server' pragma. Are you using the @tanstack/start-vite-plugin
8 Replies
rare-sapphire
rare-sapphire12mo ago
please provide a minimal complete example
flat-fuchsia
flat-fuchsiaOP12mo ago
// app/functions/getServerTime.ts import { createServerFn } from '@tanstack/start' export const getServerTime = createServerFn().handler(async () => { // Wait for 1 second await new Promise((resolve) => setTimeout(resolve, 1000)) // Return the current time return new Date().toISOString() }) // app/routes/api/users.ts import { json } from '@tanstack/start' import { createAPIFileRoute } from '@tanstack/start/api' import { getServerTime } from '../../functions/getServerTime' export const APIRoute = createAPIFileRoute('/api/users')({ GET: async ({ request }) => { const time = await getServerTime(); return json({ message: 'Hello "/api/users"!', time }); }, })
rare-sapphire
rare-sapphire12mo ago
ah I think you can't call a server function from an API route that sounds strange when I type it out @Sean Cassiere am I right though?
equal-jade
equal-jade12mo ago
I don't think we've got the functionality for it. Since both are separated into different bundles and I don't think we've gone about mapping how the request for the client-runtime works when the Vinxi router is for API routes.
flat-fuchsia
flat-fuchsiaOP12mo ago
Makes sense. I was exploring exposing the functionality of RPC functions through the API, but not sure if practically that makes sense. Maybe clarification in the docs, though: https://tanstack.com/router/latest/docs/framework/react/start/server-functions They can be called from anywhere in your application, including loaders, hooks, components, etc.
Server Functions | TanStack Router React Docs
What are Server Functions? Server functions allow you to specify logic that can be invoked anywhere (even the client), but run only on the server. In fact, they are not so different from an API route,...
rare-sapphire
rare-sapphire12mo ago
can you create a PR for the docs?
flat-fuchsia
flat-fuchsiaOP12mo ago
Yes I can do that this evening.
equal-jade
equal-jade12mo ago
When you do so, could you please use a Github Warning? https://github.com/orgs/community/discussions/16925
GitHub
[Markdown] An option to highlight a "Note" and "Warning" using bloc...
Alerts are an extension of Markdown used to emphasize critical information. On GitHub, they are displayed with distinctive colors and icons to indicate the importance of the content. An example of ...

Did you find this page helpful?