import * as trpc from "@trpc/server";
import * as trpcFetch from "@trpc/server/adapters/fetch";
import { PrismaClient } from "@prisma/client";
import {
SignedInAuthObject,
SignedOutAuthObject,
auth,
getAuth,
} from "@clerk/nextjs/server";
import { NextApiRequest } from "next";
import { headers } from "next/headers";
import { NextRequest } from "next/server";
import { RequestCookies } from "next/dist/compiled/@edge-runtime/cookies";
interface ClerkAuthContext {
auth: SignedInAuthObject | SignedOutAuthObject;
}
/**
* Inner context. Will always be available in your procedures, in contrast to the outer context.
*
* Useful for:
* - testing, database-connection and server-side helpers, so you don't have to mock Next.js' `req`/`res`
*
* @link https://trpc.io/docs/v11/context#inner-and-outer-context
*/
export const createInnerContext = async ({ auth }: ClerkAuthContext) => {
const prisma = new PrismaClient();
return {
auth,
prisma,
};
};
export async function createContext(
opts?: trpcFetch.FetchCreateContextFnOptions
) {
// ? Reference for Clerk Auth in Next.js App Router: https://clerk.com/docs/references/nextjs/read-session-data
const clerkAuth = auth();
const innerContext = await createInnerContext({ auth: clerkAuth });
return { ...innerContext, ...opts };
}
export type Context = trpc.inferAsyncReturnType<typeof createContext>;