Send cookies cross-origin
If your API resides on a different origin than your front-end and you wish to send cookies to it, you will need to enable CORS on your server and send cookies with your requests by providing the option {credentials: "include"}
to fetch.
The arguments provided to the fetch function used by tRPC can be modified as follow.
app.tsts
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';const client = createTRPCProxyClient<AppRouter>({links: [httpBatchLink({url: 'YOUR_SERVER_URL',fetch(url, options) {return fetch(url, {...options,credentials: 'include',});},}),],});
app.tsts
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';const client = createTRPCProxyClient<AppRouter>({links: [httpBatchLink({url: 'YOUR_SERVER_URL',fetch(url, options) {return fetch(url, {...options,credentials: 'include',});},}),],});
Enabling on the server
The tRPC handler is essentially just a function that takes a request and response objects. You can wrap the handler in another handler that modifies the response object to enable CORS, before passing it to the tRPC handler.
server.tsts
importhttp from 'http';import {createHTTPHandler } from '@trpc/server/adapters/standalone';import {appRouter } from "./router";// Create the tRPC handlerconsttrpcHandler =createHTTPHandler ({router :appRouter ,createContext : () => ({}),});// create and listen to the server handlerhttp .createServer ((req ,res ) => {// act on the req/res objects// enable CORSres .setHeader ('Access-Control-Allow-Origin', '*');res .setHeader ('Access-Control-Request-Method', '*');res .setHeader ('Access-Control-Allow-Methods', 'OPTIONS, GET');res .setHeader ('Access-Control-Allow-Headers', '*');// accepts OPTIONSif (req .method === 'OPTIONS') {res .writeHead (200);returnres .end ();}// then we can pass the req/res to the tRPC handlertrpcHandler (req ,res );}).listen (8080);
server.tsts
importhttp from 'http';import {createHTTPHandler } from '@trpc/server/adapters/standalone';import {appRouter } from "./router";// Create the tRPC handlerconsttrpcHandler =createHTTPHandler ({router :appRouter ,createContext : () => ({}),});// create and listen to the server handlerhttp .createServer ((req ,res ) => {// act on the req/res objects// enable CORSres .setHeader ('Access-Control-Allow-Origin', '*');res .setHeader ('Access-Control-Request-Method', '*');res .setHeader ('Access-Control-Allow-Methods', 'OPTIONS, GET');res .setHeader ('Access-Control-Allow-Headers', '*');// accepts OPTIONSif (req .method === 'OPTIONS') {res .writeHead (200);returnres .end ();}// then we can pass the req/res to the tRPC handlertrpcHandler (req ,res );}).listen (8080);
note
You can do the same thing when using Next.js, Express or any other framework.