Global Auth middleware tRPC problem

Im trying to build an admin dashboard app. I wanted more global approach for auth so rather than with protected/public/useSession approach which T3 is set up with Im trying to go with global middleware. So far so good it works but whenever I delete my session and tRPC request is made then middleware is calling redirect on tRPC api causing it crash as it responds with HTML document thus not making any redirect and making trpc erroring. refreshing works and I get redirected. Can I somehow overcome this and be able to also guard over trpc api calls or I would need to also disable middleware for /api/trpc and handle unauthorised on client? I would like to be able to handle it in middleware tho but can't find out how. Im using custom middleware with next-auth which is just calling api route that returns session.
const publicPaths = ["/api/auth", "/api/_status", "/static", "favicon.ico"];

export default async function middleware(req: NextRequest) {
const url = req.nextUrl.clone();

// allow to unauthorized access for these paths
if (publicPaths.some((path) => url.pathname.includes(path)))
return NextResponse.next();

// fetch here requires an absolute URL to the auth API route
const {
data: { auth },
} = await fetch(
`${url.origin}${env.NEXT_PUBLIC_APP_BASE_PATH}/api/auth/authed`,
{
headers: req.headers,
}
).then((res) => res.json());

// we patch the callback to send the user back to where auth was required
url.search = new URLSearchParams(`callbackUrl=${url}`).toString();
url.pathname = `/api/auth/signin`;

return !auth ? NextResponse.redirect(url) : NextResponse.next();
}
const publicPaths = ["/api/auth", "/api/_status", "/static", "favicon.ico"];

export default async function middleware(req: NextRequest) {
const url = req.nextUrl.clone();

// allow to unauthorized access for these paths
if (publicPaths.some((path) => url.pathname.includes(path)))
return NextResponse.next();

// fetch here requires an absolute URL to the auth API route
const {
data: { auth },
} = await fetch(
`${url.origin}${env.NEXT_PUBLIC_APP_BASE_PATH}/api/auth/authed`,
{
headers: req.headers,
}
).then((res) => res.json());

// we patch the callback to send the user back to where auth was required
url.search = new URLSearchParams(`callbackUrl=${url}`).toString();
url.pathname = `/api/auth/signin`;

return !auth ? NextResponse.redirect(url) : NextResponse.next();
}
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server