Skip to content

Where to best run redirect on TRPCError({ code: "UNAUTHORIZED" }); #1229

@jpainam

Description

@jpainam

throw new TRPCError({ code: "UNAUTHORIZED" });

Hi.
In api/trpc.ts, we have this

if (!ctx.session?.user) {
    throw new TRPCError({ code: "UNAUTHORIZED" });
}

I'm wondering where we need to catch this error, to run a nextjs redirect to a custom login page.

I've added this in the nextjs/app/api/[...route]/route.ts

...
const handler = auth(async (req) => {
  try {
 
    const heads = new Headers(req.headers);
   // added custom headers
    const response = await fetchRequestHandler({
      endpoint: "/api/trpc",
      router: appRouter,
      req,
      createContext: () =>
        createTRPCContext({
          session: req.auth,
          headers: heads,
        }),
      onError({ error, path }) {
        console.error(`>>> tRPC Error on '${path}'`, error);
        // added this
        if (error.code == "UNAUTHORIZED") {
          redirect("/auth/login");
        }
      },
    });

    setCorsHeaders(response);
    return response;
  } catch (e) {
    console.error(">>> tRPC Error", e);
    const error = e as TRPCError;
     // added this
    if (error.code == "UNAUTHORIZED") {
      redirect("/auth/login");
    } else {
      throw e;
    }
  }
});

export { handler as GET, handler as POST };

But it doesn't work.

If i add redirect in api/trpc.ts, it shows this (even after adding redirect in the finally block).

o [TRPCError]: UNAUTHORIZED
    at /app/apps/nextjs/.next/server/chunks/6532.js:1:1126
    at r (/app/apps/nextjs/.next/server/chunks/2381.js:1:90577)
    at next (/app/apps/nextjs/.next/server/chunks/2381.js:1:90689)
    at /app/apps/nextjs/.next/server/chunks/6532.js:1:915
    at r (/app/apps/nextjs/.next/server/chunks/2381.js:1:90577)
[TRPC] student.count took 0ms to execute
    at e (/app/apps/nextjs/.next/server/chunks/2381.js:1:90919)
    at /app/apps/nextjs/.next/server/chunks/2381.js:4:1361
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  code: 'UNAUTHORIZED',
  [cause]: undefined
}
Error: NEXT_REDIRECT
    at c (/app/apps/nextjs/.next/server/chunks/3145.js:1:55251)
    ... 8 lines matching cause stack trace ...
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  code: 'INTERNAL_SERVER_ERROR',
  name: 'TRPCError',
  digest: '212336672',
  [cause]: Error: NEXT_REDIRECT
      at c (/app/apps/nextjs/.next/server/chunks/3145.js:1:55251)
      at l (/app/apps/nextjs/.next/server/chunks/3145.js:1:55466)
      at /app/apps/nextjs/.next/server/chunks/6532.js:1:1407
      at r (/app/apps/nextjs/.next/server/chunks/2381.js:1:90577)
      at next (/app/apps/nextjs/.next/server/chunks/2381.js:1:90689)
      at /app/apps/nextjs/.next/server/chunks/6532.js:1:915
      at r (/app/apps/nextjs/.next/server/chunks/2381.js:1:90577)
      at e (/app/apps/nextjs/.next/server/chunks/2381.js:1:90919)
      at /app/apps/nextjs/.next/server/chunks/2381.js:4:1361
      at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
    digest: 'NEXT_REDIRECT;replace;/auth/login;307;',
    mutableCookies: f {
      _parsed: [Map],
      _headers: Headers {
        'set-cookie': '__Secure-authjs.session-token=eyJhbGcih=/'
      }
    }
  }
}```

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions