TanStackT
TanStack4mo ago
7 replies
worthy-azure

Server Route Search Params

Is there a proper way to implement search params in server routes? I'm struggling to figure this out, since 'search' isn't available at all in the GET function parameters, and validateSearch is seemingly meaningless for server routes.

For my main app, I'm using server functions in my SSR/queryClient fetching rather than fetching from the API like a conventional backend. But, eventually, having an external API would be important for my users.

import { createFileRoute } from "@tanstack/react-router";
import { getUsers } from "../../../lib/user";
import { json } from "@tanstack/react-start";

export const Route = createFileRoute("/api/users/")({
  server: {
    handlers: {
      GET: async ({ params, request }) => {
        const { ids, pageOffset, pageSize } = params;
        const users = await getUsers({data: { ids, pageOffset, pageSize }});

        return json(
          users
        )
      },
    },
  },
});


I suppose it's feasible to do something like this, but it feels like circumventing Start.

const url = new URL(request.url);
const q = url.searchParams.get("q")?.trim() || undefined;
const pageSize = clampInt(url.searchParams.get("limit"), 1, 100, 50);
const pageOffset = clampInt(url.searchParams.get("offset"), 0, 10000, 0);
Was this page helpful?