TRPC pass res to ctx using app router

I used the template provided by trpc, ctx doesn't contain req or res. I managed to pass the req but couldn't figure out the res. Create Context:
/**
* This is the actual context you will use in your router. It will be used to process every request
* that goes through your tRPC endpoint.
*
* @see https://trpc.io/docs/context
*/
export const createTRPCContext = async (opts: {
req: NextRequest;
// res: NextResponse;
}) => {
// Fetch stuff that depends on the request

const innerContext = await createInnerTRPCContext({
headers: opts.req.headers,
});

return {
...innerContext,
req: opts.req,
};
};
/**
* This is the actual context you will use in your router. It will be used to process every request
* that goes through your tRPC endpoint.
*
* @see https://trpc.io/docs/context
*/
export const createTRPCContext = async (opts: {
req: NextRequest;
// res: NextResponse;
}) => {
// Fetch stuff that depends on the request

const innerContext = await createInnerTRPCContext({
headers: opts.req.headers,
});

return {
...innerContext,
req: opts.req,
};
};
Handler
import { fetchRequestHandler } from "@trpc/server/adapters/fetch";
import { type NextRequest } from "next/server";

import { env } from "~/env.mjs";
import { appRouter } from "~/server/api/root";
import { createTRPCContext } from "~/server/api/trpc";

const handler = (req: NextRequest) => {
return fetchRequestHandler({
endpoint: "/api/trpc",
req,
router: appRouter,
createContext: () => createTRPCContext({ req }),
onError:
env.NODE_ENV === "development"
? ({ path, error }) => {
console.error(
`❌ tRPC failed on ${path ?? "<no-path>"}: ${error.message}`,
);
}
: undefined,
});
};

export { handler as GET, handler as POST };
import { fetchRequestHandler } from "@trpc/server/adapters/fetch";
import { type NextRequest } from "next/server";

import { env } from "~/env.mjs";
import { appRouter } from "~/server/api/root";
import { createTRPCContext } from "~/server/api/trpc";

const handler = (req: NextRequest) => {
return fetchRequestHandler({
endpoint: "/api/trpc",
req,
router: appRouter,
createContext: () => createTRPCContext({ req }),
onError:
env.NODE_ENV === "development"
? ({ path, error }) => {
console.error(
`❌ tRPC failed on ${path ?? "<no-path>"}: ${error.message}`,
);
}
: undefined,
});
};

export { handler as GET, handler as POST };
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server