Encabezado personalizado
Traducción Beta No Oficial
Esta página fue traducida por PageTurner AI (beta). No está respaldada oficialmente por el proyecto. ¿Encontraste un error? Reportar problema →
La opción headers puede personalizarse en la configuración al usar httpBatchLink o httpLink.
headers puede ser tanto un objeto como una función. Si es una función, se llamará dinámicamente para cada solicitud HTTP.
utils/trpc.tsts// Import the router type from your server fileimport 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.tsts// Import the router type from your server fileimport 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,};},}),],};},});
Ejemplo con autenticación (login)
pages/auth.tsxtsconst loginMut = trpc.auth.login.useMutation({onSuccess(opts) {token = opts.accessToken;},});
pages/auth.tsxtsconst loginMut = trpc.auth.login.useMutation({onSuccess(opts) {token = opts.accessToken;},});
El token puede ser cualquier cosa que desees. Depende completamente de ti si es solo una variable del lado del cliente cuyo valor actualizas tras un éxito o si almacenas el token y lo recuperas del almacenamiento local.