fix: improve error handling for SESSION_EXPIRED and UNAUTHORIZED in TRPC links

This commit is contained in:
Marco Pedone 2026-04-13 16:23:09 +02:00
parent 680d344215
commit c8b11c745e
2 changed files with 26 additions and 7 deletions

View file

@ -9,7 +9,10 @@ export default createNextApiHandler({
createContext: createTRPCContext, createContext: createTRPCContext,
onError: ({ path, error }) => { onError: ({ path, error }) => {
if (error.message.startsWith("SESSION_EXPIRED")) { if (
error.message.startsWith("SESSION_EXPIRED") ||
error.code === "UNAUTHORIZED"
) {
return; return;
} }
if (env.NODE_ENV === "development") { if (env.NODE_ENV === "development") {

View file

@ -44,6 +44,7 @@ const errorLink: TRPCLink<AppRouter> = () => {
err, err,
); );
window.location.reload(); window.location.reload();
return;
} }
observer.error(err); observer.error(err);
}, },
@ -60,12 +61,27 @@ export const api = createTRPCNext<AppRouter>({
links: [ links: [
errorLink, errorLink,
loggerLink({ loggerLink({
enabled: (opts) => enabled: (opts) => {
(process.env.NODE_ENV === "development" && const isDev = process.env.NODE_ENV === "development";
typeof window !== "undefined") ||
(opts.direction === "down" && if (opts.direction === "down" && opts.result instanceof Error) {
opts.result instanceof Error && const isIgnoredError =
!opts.result.message.startsWith("SESSION_EXPIRED")), opts.result.message.startsWith("SESSION_EXPIRED") ||
opts.result.data?.code === "UNAUTHORIZED";
if (!isIgnoredError) {
return true;
}
if (isDev) {
console.warn("Following error is ignored in production:");
return true;
}
return false;
}
if (isDev) {
return true;
}
return false;
},
}), }),
splitLink({ splitLink({