You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I am trying to create a context/middleware procedure where the middleware checks the next-auth session before proceeding. In DEV this all works as expected, however when building for production:
// server/trpc.ts
import { TRPCError, initTRPC } from '@trpc/server';
import { type Context } from './context';
export const t = initTRPC.context<Context>().create();
export const router = t.router;
//export const protectedProcedure = t.procedure;
export const protectedProcedure = t.procedure.use(opts => {
if (!opts.ctx.session) {
throw new TRPCError({
code: 'UNAUTHORIZED'
});
}
return opts.next({
ctx: {
session: opts.ctx.session
}
});
});
// server/context.ts
import { getServerSession } from 'next-auth';
import { authOptions } from '@/constants/authOptions';
export async function createContext() {
const session = await getServerSession(authOptions);
return { session };
}
export type Context = Awaited<ReturnType<typeof createContext>>;
// app/_trpc/serverClient.ts
import { appRouter } from '@/server';
import { createContext } from '@/server/context';
import { t } from '@/server/trpc';
const createCaller = t.createCallerFactory(appRouter);
export const serverClient = createCaller(await createContext());
// app/api/trpc/[trpc]/route.ts
import { fetchRequestHandler } from '@trpc/server/adapters/fetch';
import { appRouter } from '@/server';
import { createContext } from '@/server/context';
const handler = (req: Request) =>
fetchRequestHandler({
endpoint: '/api/trpc',
req,
router: appRouter,
createContext: async () => await createContext()
});
export { handler as GET, handler as POST };
I have narrowed this down to the way I'm calling getServerSession within createContext (as if I comment this out it builds fine). Is there an alternative way to get around this? Why does it work in dev and not production?
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
I am trying to create a context/middleware procedure where the middleware checks the next-auth session before proceeding. In DEV this all works as expected, however when building for production:
Error:
headers
was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-contextI have narrowed this down to the way I'm calling getServerSession within createContext (as if I comment this out it builds fine). Is there an alternative way to get around this? Why does it work in dev and not production?
Beta Was this translation helpful? Give feedback.
All reactions