javascript
javascript copied to clipboard
How do you use Clerk with tRPC successfully?
trafficstars
We've been using Clerk with tRPC and Remix. So our application makes requests to tRPC in the usual way, and I try get get auth like this:
import { getAuth } from "@clerk/remix/ssr.server.js";
import { FetchCreateContextFnOptions } from "@trpc/server/adapters/fetch";
import { getUserIdFromAuth } from "app/integrations/clerk.server";
export async function createContext({
req,
resHeaders,
}: FetchCreateContextFnOptions) {
const headers = Object.fromEntries(req.headers.entries());
const auth = await getAuth({
request: req,
context: {},
params: {},
});
let userId: string | null = null;
if (auth.userId) {
userId = (await getUserIdFromAuth(auth)) || null;
}
return { req, resHeaders, userId };
}
This works at first but is not actually good at all: the getAuth method in Clerk makes a pretty hard assumption that it can throw an error and present an interstitial page. Which in a tRPC context makes no sense - you're doing an API request, and getting back a HTML page instead of JSON isn't going to work.
So, we get crashes in prod and pretty polluted logs. What's the right way to do this? As it is, I don't see how to make Clerk work with tRPC, to get a user's auth from an API request and not break the API endpoint.