FinnF
tRPC2y ago
15 replies
Finn

Using tRPC in Next.js Middleware

Hello, I am quite new to tRPC so forgive me if I'm asking something quite obvious/dumb.

I was introduced to tRPC by the t3-stack, that I discovered when I started with Next.js. Now onto the question. I am storing user session inside a database and want to validate a user that has a session_token cookie by its value. So, the value of the cookie needs to exist in the database. That way I can authenticate the request as well as associate a user.

The problem I was facing is that I was having a hard time trying to access tRPC routes from the Next.js middleware. The t3 stack came with a pre-configured tRPC server and react client. Both of them do not work inside the Next.js middleware, because it runs on the Edge runtime. I have found some posts here that were asking a similar question, but none of them gave me an answer for my question.

One of the posts helped solving the problem by suggesting to create a new client with a httpBatchLink that points to the api/trpc route. And that works the way it's suppose to. But right now, I export 3 api variables:

// src/trpc/react.tsx
export const api = createTRPCReact<AppRouter>();



// src/trpc/server.ts
const createContext = cache(() => {
  const heads = new Headers(headers());
  // ...
});

export const api = createTRPCProxyClient<AppRouter>({
  transformer,
  links: [
    // ...
    () =>
      ({ op }) =>
        observable((observer) => {
          createContext()
            // ...
        }),
  ],
});


// src/trpc/edge.ts
export const api = createTRPCProxyClient<AppRouter>({
    transformer,
    links: [
        httpBatchLink({
            url: `${getBaseUrl()}/api/trpc`,
            fetch(url, options) {
                return fetch(url, {
                    ...options,
                });
            },
        }),
    ],
});


Would you say, that what I've done is okay, or am I doing something completely unnecessary here?
Was this page helpful?