Ted (he/him)
Ted (he/him)5mo ago

Auth0 + fastify + tRPC

Hi, I've inherited a tRPC React/fastify app and need to migrate the auth from supertokens to auth0. I'm running into an issue with the createContext function for the fastifyTRPCPlugin and would love to hear whether this is the right approach or if y'all have any suggestions. Fastify server
export async function buildServer() {
const server = fastify({
<...>
});

<...>

server.register(cors, {
<...>
});

await server.register(formDataPlugin);
await server.register(ws);

await server.register(fastifyTRPCPlugin<typeof appRouter>, {
prefix: '/',
useWSS: true,
trpcOptions: {
router: appRouter,
createContext,
onError({ error, req, path, input }) {
// We use req.log.error, when available, instead of server.log.error because it will automatically add the request id to the log
(req && req.log ? req : server).log.error({
err: error,
path,
input,
});
},
},
});

await server.register(fastifyAuth0Verify, {
domain: '<DOMAIN>',
audience: '<AUDIENCE>',
});

return server;
}
export async function buildServer() {
const server = fastify({
<...>
});

<...>

server.register(cors, {
<...>
});

await server.register(formDataPlugin);
await server.register(ws);

await server.register(fastifyTRPCPlugin<typeof appRouter>, {
prefix: '/',
useWSS: true,
trpcOptions: {
router: appRouter,
createContext,
onError({ error, req, path, input }) {
// We use req.log.error, when available, instead of server.log.error because it will automatically add the request id to the log
(req && req.log ? req : server).log.error({
err: error,
path,
input,
});
},
},
});

await server.register(fastifyAuth0Verify, {
domain: '<DOMAIN>',
audience: '<AUDIENCE>',
});

return server;
}
the createContext function
export async function createContext({ req }: CreateFastifyContextOptions) {
await req.jwtVerify();

const user = req.user;

return createInnerContext({
user,
logger: req.log,
});
}
export async function createContext({ req }: CreateFastifyContextOptions) {
await req.jwtVerify();

const user = req.user;

return createInnerContext({
user,
logger: req.log,
});
}
My understanding is that fastify-auth0-verify plugin would annotate requests with a jwtVerify function (and VSCode thinks it exists). But I'm seeing the error req.jwtVerify is not a function Is the plugin registration order important? Or maybe a special case for websockets? Thanks for any help!
1 Reply
BeBoRE
BeBoRE5mo ago
Are you starting the server before awaiting the register? I believe I've had those same issues because of that.