There is an example of passing a auth token to headers
function that will be used on every query and mutation sent to backend.
Unfortunately, the heavy lifting of getting cookies of an already logged-in user to the token client-side is left as an exercise and will probably look like this:
let token = typeof window === 'undefined' ? undefined : parseClientCookies(document.cookie).token;
export function setToken(newToken: string) {
token = newToken;
}
export const trpc = createTRPCNext<AppRouter>({
config: ({ ctx }) => ({
links: [
httpBatchLink({
url: 'http://localhost:3000/api/trpc',
headers: () => ({
Authorization: typeof window === 'undefined' ? parseServerCookie(ctx.req).token : token
}),
}),
],
}),
});
In case of config return being dependant on something like next.js' locale - I don't see a clear solution, though we definitely have locale in the ctx
object passed to config
function server-side.
I suggest adding a meta
prop (derived from ctx
) to the config
parameter that will be universal for both client and server-side.
Server-side meta is pretty simple:
+ config meta = getMeta(ctx);
+ const config = getClientConfig({ meta });
- const config = getClientConfig({ ctx });
const trpcClient = createTRPCClient(config);
const queryClient = getQueryClient(config);
Client getting meta server-side:
+ const meta = getMeta(ctx);
+ const getAppTreeProps = (props: Record<string, unknown>) => isApp ? { pageProps: props, meta } : props;
- const getAppTreeProps = (props: Record<string, unknown>) => isApp ? { pageProps: props } : props;
if (typeof window !== 'undefined' || !opts.ssr) {
return getAppTreeProps(pageProps);
}
Client-side using meta:
+ const WithTRPC = ({ meta, ...props }: AppPropsType<NextRouter, any> & { trpc?: TRPCPrepassProps; meta: TMetaContext }) => {
- const WithTRPC = (props: AppPropsType<NextRouter, any> & { trpc?: TRPCPrepassProps }) => {
const [prepassProps] = useState(() => {
if (props.trpc) {
return props.trpc;
}
+ const config = getClientConfig({ meta });
- const config = getClientConfig({});
The alternate solution would be using a specific tool to extract every needed part of a server-side context for each specific case.
No response
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too