denik1981
denik19812y ago

Is it ok to use a createCaller() router within ServerSideProps?

The official trpc docs shown an example of how to use the SSGHelper router within SSPs. The procedure I wanna use needs the session object within the context. This procedure is shared by the public API trpc router thus I wouldn't want to create a different procedure that will do the same but taking the session information from someplace else. I was able to create a server side only router with createCaller and tne innerContext as suggested and it is working perfectly inside SSPs. Is there any CAVEAT regarding using this type of reouter instead the SSG provided. I do understand that I won't be able to prefetch and hydrate the page, but apart from that, is there anything that I should be aware of. My particular use case was not feeding props into the page but to get a value from the user procedure that wil later allow to redirect to another path. This is working great with the SSO router but I'm planning to use it later for a traditional SSP props feed operation.
1 Reply
denik1981
denik19812y ago
To add more context to the post what I'm basically doing is: In the server
// server - appRouter is the API trpc router

export async function createContextInner(opts: CreateInnerContextOptions) {
return {
session: opts.session,
};
}

export type Context = inferAsyncReturnType<typeof createContextInner>

export const caller = async (ctx: Context) =>
appRouter.createCaller(await createContextInner(ctx));
// server - appRouter is the API trpc router

export async function createContextInner(opts: CreateInnerContextOptions) {
return {
session: opts.session,
};
}

export type Context = inferAsyncReturnType<typeof createContextInner>

export const caller = async (ctx: Context) =>
appRouter.createCaller(await createContextInner(ctx));
In ServerSideProps
export async function getServerSideProps(ctx: GetServerSidePropsContext) {
const session = await unstable_getServerSession(
ctx.req,
ctx.res,
authOptions
);

const c = await caller({ session });

// this procedure use the session context object
const user = await c.user.me();

return session
? { redirect: { permanent: false, destination: `/${user.type}/member` } }
: { props: {} };
}
export async function getServerSideProps(ctx: GetServerSidePropsContext) {
const session = await unstable_getServerSession(
ctx.req,
ctx.res,
authOptions
);

const c = await caller({ session });

// this procedure use the session context object
const user = await c.user.me();

return session
? { redirect: { permanent: false, destination: `/${user.type}/member` } }
: { props: {} };
}