Hoppa till huvudinnehållet
Version: 9.x

Anpassad header

Inofficiell Beta-översättning

Denna sida har översatts av PageTurner AI (beta). Inte officiellt godkänd av projektet. Hittade du ett fel? Rapportera problem →

Alternativet för headers kan anpassas i konfigurationen när du använder withTRPC i Next.js eller createClient i React.js.

headers kan vara antingen ett objekt eller en funktion. Om det är en funktion kommer den att anropas dynamiskt vid varje HTTP-förfrågan.

_app.tsx
ts
import type { AppRouter } from '@/server/routers/app';
import { withTRPC } from '@trpc/next';
import { AppType } from 'next/dist/shared/lib/utils';
export let token: string;
const MyApp: AppType = ({ Component, pageProps }) => {
return <Component {...pageProps} />;
};
export default withTRPC<AppRouter>({
config(config) {
return {
links: [
httpBatchLink({
/** headers are called on every request */
headers: () => {
return {
Authorization: token,
};
},
}),
],
};
},
})(MyApp);
_app.tsx
ts
import type { AppRouter } from '@/server/routers/app';
import { withTRPC } from '@trpc/next';
import { AppType } from 'next/dist/shared/lib/utils';
export let token: string;
const MyApp: AppType = ({ Component, pageProps }) => {
return <Component {...pageProps} />;
};
export default withTRPC<AppRouter>({
config(config) {
return {
links: [
httpBatchLink({
/** headers are called on every request */
headers: () => {
return {
Authorization: token,
};
},
}),
],
};
},
})(MyApp);

Exempel med auth-inloggning

pages/auth.tsx
ts
const loginMut = trpc.useMutation(['auth.login'], {
onSuccess({ accessToken }) {
token = accessToken;
},
});
pages/auth.tsx
ts
const loginMut = trpc.useMutation(['auth.login'], {
onSuccess({ accessToken }) {
token = accessToken;
},
});

token kan vara precis vad du vill. Det är helt upp till dig om det bara är en klientsidig variabel som du uppdaterar vid lyckade förfrågningar, eller om du lagrar token och hämtar den från local storage.