Enhance API error handling: add errorLink to handle UNAUTHORIZED errors and reload the page

This commit is contained in:
Marco Pedone 2025-08-19 19:14:30 +02:00
parent 709ac307e1
commit e20731e027
2 changed files with 25 additions and 1 deletions

View file

@ -125,7 +125,6 @@ const refreshAuthToken = async (
response.cookies.delete(REFRESH_TOKEN_COOKIE_NAME);
return response;
}
// If refresh token is valid, sign a new access token
const redirect = req.nextUrl.searchParams.get("redirect");
const destination = onSuccessDashboard

View file

@ -3,9 +3,12 @@ import {
httpSubscriptionLink,
loggerLink,
splitLink,
TRPCClientError,
type TRPCLink,
} from "@trpc/client";
import { createTRPCNext } from "@trpc/next";
import type { inferRouterInputs, inferRouterOutputs } from "@trpc/server";
import { observable } from "@trpc/server/observable";
import superjson from "superjson";
import type { AppRouter } from "~/server/api/root";
@ -19,10 +22,32 @@ const getUrl = () => {
return `${base}/api/trpc`;
};
const errorLink: TRPCLink<AppRouter> = () => {
return ({ next, op }) => {
return observable((observer) => {
const unsubscribe = next(op).subscribe({
next: observer.next,
error(err) {
if (
err instanceof TRPCClientError &&
err.data?.code === "UNAUTHORIZED"
) {
window.location.reload();
}
observer.error(err);
},
complete: observer.complete,
});
return unsubscribe;
});
};
};
export const api = createTRPCNext<AppRouter>({
config() {
return {
links: [
errorLink,
loggerLink({
enabled: (opts) =>
(process.env.NODE_ENV === "development" &&