NextJs middleware broken by tRPC

Hi, I have a NextJs middleware that is redirecting to the login page. Basically an Auth guard over my all pages and apis but I have a problem with tRPC api routes. Whenever NextJs middleware pickup /api/trpc call and there is no session it tries to redirect to the login page breaking the redirect and trpc itself. Is there a way to get this working so redirect would actually work as expected?
AK
Alex / KATT 🐱540d ago
You might need a custom link at the end to deal with it Unsure what you expect the trpc api request to do here though
M
Mugetsu540d ago
yeah I was looking at links but cant actually get to understand them
AK
Alex / KATT 🐱540d ago
I think you should exclude the trpc api requests in your middleware
M
Mugetsu540d ago
But then i need to handle unathorized on the client side like in queryclientconfig. I was expecting I would be able to handle this with nextjsmiddleware which would be much simpler having guard in one place
AK
Alex / KATT 🐱540d ago
You're on your own here, I'm afraid. Nextjs middlewares have a lot unexpected behaviours when it overrides the api calls like this - I don't use them myself and don't have the capacity to solve your problems with them
M
Mugetsu540d ago
I see. Yeah I've been searching for a few days already. I guess I will go with client handle for trpc then. Thanks for quick response tho @alex / KATT . Loving tRPC keep up the good work ❤️
UU
Unknown User540d ago
M
Mugetsu540d ago
@Bennett My usecase is simple. I dont need to expose my api to external clients so its pure backend for fronted api and everything of the app must be gated behind OneLogin oauth. So Ideally with use of the nextJs middleware I suppose to be able to authorise my app within single place for all my page routes and api routes. With middleware I should be able to achieve checking/validating the authorisation before request even hits my api endpoints. So there would be no extra trip to server for it to checking auth in trpc context and returning auth status to the client and then action on it. With middleware I can remove that extra layer and handle auth before request even tries reaching that particular api route if my understanding is correct. But what I found is that trpc swallows the redirects due to nature of fetch not being able to redirect document. Here are my findings https://github.com/trpc/trpc/issues/3081
UU
Unknown User540d ago
M
Mugetsu539d ago
@Bennett How the response json should look like then for it to work?? I believe this wont fix the problem as trpc httplinks are swallowing the response if I respond with 401 anyway.
return NextResponse.json(
{
result: { data: 1 },
},
{ status: 401 }
);
return NextResponse.json(
{
result: { data: 1 },
},
{ status: 401 }
);
UU
Unknown User539d ago
M
Mugetsu539d ago
Yeah I would like to have some response to the issue but I believe @alex / KATT is currently busy with doing stable release of v10 👀 For now I exclude trpc api from middleware and handle it globally with reactquery onerror but I believe if Im not mistaken that this will be anyway an issue once NextAuth will figure out middleware database sessions instead of jwt. I havent checked if this is also an issue with current nextauth middleware if I find time I will check
AK
Alex / KATT 🐱539d ago
Haha, I'm busy with day to day work, trpc is mainly evenings, weekends, and got half a day a week to work at it during work hours 😅
More Posts
How to infer the output of a mutation? The current methods appear to be depreciated.I am attempting to export the bellow utility function to use client side to infer an output type thaTrouble inferring the type of a very simple structure of nested routersA very simple router results in an inference error, causing the client to not be able to infer the rcalling trpc endpoints from vanilla nextJs api routesI'm struggling to find what's the best way to call a trpc endpoint directly from the server. BasicalMultiple React providersGood morning! Is there any workaround, how to use multiple trpc-client instances with react-query? IMutation type issueI'm trying to mutate something like this with tRPC and Prisma ```const updateColumn = trpc.project.uCan I redirect the user from inside my router?I have a query protectedProcedure, which returns an object from my prisma planetscale db What's theInfer the type of ctx for a specific procedureLet's say I had a helper function that I wanted to pass the context to, I can't use the default ContCORS in standalone serverHi, I'm trying to get CORS working in standalone server. Attempted this solution but unfortunatelyQueries break when in production on Vercel; work on localhostThe query is called like this: ```javascript const { data } = api.useQuery(["user.!getCount"], { Can't get client to workHi, I can't get my client to work I'm using Next.js but I have also tried the React method from the Request context inside middleware?Hi, Is it possible to get the request context inside a middleware somehow? I'm trying to migrate data becomes never[] when destructuring with a fallback valueCurrently it doesn't seem possible to set a fallback value on a destructured `data` property, for exSyntaxError Unexpected token u in JSON at position 0 with mutationsI'm trying to use trpc client to await a mutation and just keep getting this error. everything worksLosing the type between the client and serverHello everyone, I am new to tRPC and the magic of types in typescript so I am looking for ideas as tMobile app with tRPCWhat's the suggested way of working with tRPC when it comes to mobile apps? How do you ensure that yHow to use trpc react hooks from an external data sourceHi, I have a monorepo, nextjs and keystone cms. The cms has trpc running, and I managed to get it coNextJS & Keystone CMS, issues when connecting both in a monorepoHello everyone, so I have a monorepo with NextJS and keystone cms, both are running trpc v10beta.15Best practices for implementing an offline applicationHey there! I'm building a full stack react-native app with Expo and a tRPC backend. I'd like for thisomehow when move typed function out of the router files, frontend infer type to be any ?this is inferred corrected since they are in the same file. ``` getX: t.procedure.query(() => { retBig companies that use tRPC?Some of my fellow colleagues were wondering if there are any big companies that use tRPC and how mat