Replies: 1 comment
-
|
Yes, you can pass data from server middleware to the client using TanStack Start's middleware context. Here's the pattern: 1. Create the middleware// app/middleware.ts
import { createMiddleware } from "@tanstack/react-start";
import { nanoid } from "nanoid";
export const requestIdMiddleware = createMiddleware().server(
async ({ next }) => {
const requestId = nanoid();
console.log(`[${requestId}] Request started`);
const result = await next({ context: { requestId } });
console.log(`[${requestId}] Request completed`);
return result;
}
);2. Use it in a server function// app/server/functions.ts
import { createServerFn } from "@tanstack/react-start";
import { requestIdMiddleware } from "../middleware";
export const getRequestContext = createServerFn()
.middleware([requestIdMiddleware])
.handler(async ({ context }) => {
// context.requestId is available here
return { requestId: context.requestId };
});3. Consume it in a route loader// app/routes/index.tsx
import { createFileRoute } from "@tanstack/react-router";
import { getRequestContext } from "../server/functions";
export const Route = createFileRoute("/")({
loader: async () => {
const { requestId } = await getRequestContext();
return { requestId };
},
component: RouteComponent,
});
function RouteComponent() {
const { requestId } = Route.useLoaderData();
return <div>Request ID: {requestId}</div>;
}For logging on both sidesIf you want the same request ID available in both server and client logs: // app/middleware.ts
import { createMiddleware } from "@tanstack/react-start";
import { nanoid } from "nanoid";
export const requestIdMiddleware = createMiddleware().server(
async ({ next, request }) => {
// Check for existing request ID from header (e.g., load balancer)
const requestId =
request.headers.get("x-request-id") || nanoid();
// Set response header so client can read it
const result = await next({
context: { requestId },
headers: { "x-request-id": requestId },
});
return result;
}
);Alternative: Use
|
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I want to generate a requestId from the server to the client i.e. so I can include it in logs on both client and server side.
Is this possible with TS Start middleware?
Beta Was this translation helpful? Give feedback.
All reactions