I am building Token Based Authentication in my TRPC Nextjs application. I am storing the refresh token in the users cookies. In case a request fails because the access token is expired, i want to access my API route to generate a new access token.I can't wrap my head around how to access the cookies (in my case the refreshToken) in my TRPC fetch handler that runs on each request. (It obviously runs clientside)
import { httpBatchLink, loggerLink } from "@trpc/client";
import { createTRPCNext } from "@trpc/next";
import { type inferRouterInputs, type inferRouterOutputs } from "@trpc/server";
import superjson from "superjson";
import { type AppRouter } from "@/server/api/root";
export let token: string;
export const setToken = (newToken: string) => {
token = newToken;
};
{... ...}
export const api = createTRPCNext<AppRouter>({
config({ctx}) {
return {
links: [
loggerLink({
...
}),
httpBatchLink({
transformer: superjson,
url: `${getBaseUrl()}/api/trpc`,
headers: ({
}) => {
const newHeaders = new Headers();
if(token) newHeaders.set("Authorization", `Bearer ${token}`);
return newHeaders;
},
fetch(url, options) {
//I need to access the cookies here
//Ctx is undefined
return fetch(url, {
...options,
credentials: "include",
});
},
}),
],
};
},
ssr: false,
transformer: superjson,
});
{... ...}
I tried using a package like js-cookie but this did not work since the code does not run in an actual React component. I also tried accessing the my ctx containing the headers passed down in the config({ctx}) but it is always undefined
In the page router, we can access the
headersonly in thegetServerSidePropsorgetInitialProps. And if you want to access the headers using tRPC, you should enable itsssrflag as described in the official document: https://trpc.io/docs/client/nextjs/ssrWhich will be like this:
However, it's also been said:
So the recommended solution is to use the Server-Side Helpers which can be done in
getServerSidePropsfunction (example from official document https://trpc.io/docs/client/nextjs/server-side-helpers#nextjs-example):