Aller au contenu principal
Version : 10.x

En-tête personnalisé

Traduction Bêta Non Officielle

Cette page a été traduite par PageTurner AI (bêta). Non approuvée officiellement par le projet. Vous avez trouvé une erreur ? Signaler un problème →

L'option headers peut être personnalisée dans la configuration lorsque vous utilisez httpBatchLink ou httpLink.

headers peut être soit un objet soit une fonction. Si c'est une fonction, elle sera appelée dynamiquement à chaque requête HTTP.

utils/trpc.ts
ts
// Import the router type from your server file
import type { AppRouter } from '@/server/routers/app';
import { httpBatchLink } from '@trpc/client';
import { createTRPCNext } from '@trpc/next';
let token: string;
export function setToken(newToken: string) {
/**
* You can also save the token to cookies, and initialize from
* cookies above.
*/
token = newToken;
}
export const trpc = createTRPCNext<AppRouter>({
config(config) {
return {
links: [
httpBatchLink({
url: 'http://localhost:3000/api/trpc',
/**
* Headers will be called on each request.
*/
headers() {
return {
Authorization: token,
};
},
}),
],
};
},
});
utils/trpc.ts
ts
// Import the router type from your server file
import type { AppRouter } from '@/server/routers/app';
import { httpBatchLink } from '@trpc/client';
import { createTRPCNext } from '@trpc/next';
let token: string;
export function setToken(newToken: string) {
/**
* You can also save the token to cookies, and initialize from
* cookies above.
*/
token = newToken;
}
export const trpc = createTRPCNext<AppRouter>({
config(config) {
return {
links: [
httpBatchLink({
url: 'http://localhost:3000/api/trpc',
/**
* Headers will be called on each request.
*/
headers() {
return {
Authorization: token,
};
},
}),
],
};
},
});

Exemple avec authentification

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

Le token peut être ce que vous souhaitez. Il dépend entièrement de vous qu'il s'agisse simplement d'une variable côté client dont vous mettez à jour la valeur lors d'un succès, ou que vous stockiez le token pour le récupérer depuis le local storage.