T
tRPC

express-session for tRPC

express-session for tRPC

Iippo4/29/2023
I am using express-session for all my servers to create session authentication. Is there something for tRPC that you can recommend, to get session authentication? does anyone know a repo, that uses cookie authentication where the session-id is stored in a database/redis/memory and where on every request the user is queried and store in the req object?
Ttomheaton4/30/2023
you can send the auth cookie or similar with the request in the headers (https://trpc.io/docs/client/setup)
httpBatchLink({
url: 'http://localhost:3000/trpc',
// You can pass any HTTP headers you wish here
async headers() {
return {
authorization: getAuthCookie(),
};
},
}),
httpBatchLink({
url: 'http://localhost:3000/trpc',
// You can pass any HTTP headers you wish here
async headers() {
return {
authorization: getAuthCookie(),
};
},
}),
then define a middleware that uses the auth to find a matching session (in your redis etc.) (https://trpc.io/docs/server/middlewares)
const hasSession = middleware(async (opts) => {
const { req } = opts;

// get session from redis etc.
const session = await getSessionFromRedis(req.headers);

if (!session) {
throw new TRPCError({ code: 'UNAUTHORIZED' });
}

return opts.next({
ctx: {
user: session.user,
},
});
});
const hasSession = middleware(async (opts) => {
const { req } = opts;

// get session from redis etc.
const session = await getSessionFromRedis(req.headers);

if (!session) {
throw new TRPCError({ code: 'UNAUTHORIZED' });
}

return opts.next({
ctx: {
user: session.user,
},
});
});
Iippo4/30/2023
@tomheaton but where do you set the cookie properties? the max age, the signature secret, its behavior and so on?
MMugetsu4/30/2023
You can use express session as normal with trpc No magic Here. You dont need anything specilal just for trpc. Trpc is based on the req/res from express so you have access to the req.session within trpc routes.
Iippo4/30/2023
this is how I setup my session with express-session:
app.use(
session({
name: "COOKIE_ID",
store: new RedisStore({
client: redis,
disableTouch: true,
}),
cookie: {
maxAge: 1000 * 60 * 60 * 24, // 1 day
httpOnly: true,
sameSite: "lax", // reLAXed CSRF - Cross Site Request Forgery
secure: true, // cookie only works in https
domain: ".myapp.com", // cookie only works if request comes from this domain
},
saveUninitialized: false, // not every session will be stored, only modified once
secret: "very complicated string", // this string is used to sign the cookie and protect it from modifications.
resave: false, // will not save the session in store on every request, only if was modified
})
);
app.use(
session({
name: "COOKIE_ID",
store: new RedisStore({
client: redis,
disableTouch: true,
}),
cookie: {
maxAge: 1000 * 60 * 60 * 24, // 1 day
httpOnly: true,
sameSite: "lax", // reLAXed CSRF - Cross Site Request Forgery
secure: true, // cookie only works in https
domain: ".myapp.com", // cookie only works if request comes from this domain
},
saveUninitialized: false, // not every session will be stored, only modified once
secret: "very complicated string", // this string is used to sign the cookie and protect it from modifications.
resave: false, // will not save the session in store on every request, only if was modified
})
);
Is there an equivalent for next-auth?
MMugetsu5/1/2023
You need an adapter with next-auth. I see u use redis with express. Then either use up-stash adapter for redis or you need to roll out your own adapter for redis. There is custom adapter for redis on next-auth issues or discussions as I was in need for one too. You have to look for it https://next-auth.js.org/adapters https://authjs.dev/reference/adapter/upstash-redis https://authjs.dev/guides/adapters/using-a-database-adapter https://authjs.dev/concepts/faq#databases https://authjs.dev/reference/adapters
Ttomheaton5/1/2023
vercel just announced vercel-kv šŸ™Œ

Looking for more? Join the community!

T
tRPC

express-session for tRPC

Join Server
Recommended Posts
next-prisma-websockets-starter seeds twice on 'pnpm dx'Hi, i'm using this starter template for my app. The `dx` script from package.json runs both `prisma Can you return from an API endpoint before a sync operation is complete?I'm curious, if I have an endpoint that saves something to a DB and I choose to return from the endpuseInfiniteQueryHey i saw on trpc docs that it is used with prisma, but can i so it with drizzle ? How to past cursoTRPC Next/Server Types Broken >10.5.0Hi all, recently I upgraded from 10.5.0 to latest 10.21.2, discovering that I now have type-check erJWT Token is type "never" in frontend.??!!TRPC Backend is sending JWT Token as string but frontend is reading it as type "never". I am using tHow to properly check the contents of prefetched data?I have dynamic route with SSG and if coming product slug is not in db I want to return notFound: trutrpc/next very slowI have set up my project using trpc/next and i have extremely slow queries, simple hello world takinGeneric handler for data.isLoading and data.isErrorHi, I'm looking for a way to create generic interface for useQuery result (budgetData from example bBug where 2 requests are fired at once. TRPC batches them. Can I cancel the 2nd via ProcedureOption?Hey all. I have a bug where my app fires two identical requests at the same time. This happens do toHow to do an async API call in useEffect (T3 stack)Hey, I have the router below and want to call the `tutor`async in an `useCallback` function, but thepagination - Offset MethodHi trpc has pagination example but only using cursor https://trpc.io/docs/reactjs/useinfinitequery next js appDirNext js tRpc What are the advantages of using trpc instead of the native Next.js APIs when buildingHow can you fetch data on a dynamic router with trpc?Iā€™m creating a table component within my NextJs app. Instead of making an api call in the parent comMocking tRPC call w/ Playwright (Transform Error)I have a tRPC call that I would like to mock out for a Playwright E2E test. I've followed their doczod input validation from ts typeI imported a type using `import type { WebhookEvent } from "@clerk/nextjs/api";`. Is there a way to Looking to fix my tRPC implementationHi guys I am looking for some help implementing tRPC in my current project, I have 3 files that needExpression produces a union type that is too complex to representHi! I have started to encounter the above on error on pretty simple react components using trpc v10 Skipping useQuery with typescriptI'm wondering if there is a way to skip a query in a typescript friendly way? `rtk-query` has a hand