silj6
silj6

Reputation: 1

Passport.js session returns undefined for req.user in TRPC-context

I'm using Express.js with Passport.js for user authentication in my Vue 3 app. My session setup uses express-session and cookie-parser to store session cookies. While the authentication works, when I try to access req.user in my trpc-procedures after declared in the Context, it returns undefined.

IMPORTANT: My console.log inside of my context-declaration returns the correct user object, while USING the user with ctx.user returns undefined.

The console.log(req.user) here, returns the correct user object.

import * as trpcExpress from '@trpc/server/adapters/express';
import express from 'express';
import cors from 'cors';
import passport from 'passport';
import './passport.ts'; // Ensure passport configuration is loaded
import { trpc } from './trpc.ts';
import { inferRouterOutputs } from '@trpc/server';
import { appRouter } from './services/router.ts';
import { PrismaClient } from '@prisma/client';
import session from 'express-session';
import routes from './auth.ts';
import dotenv from 'dotenv';
import redis from 'redis';
import RedisStore from 'connect-redis';

dotenv.config();

const prisma = new PrismaClient();

**// Context logic
const createContext = ({
  req,
  res,
}: trpcExpress.CreateExpressContextOptions) => {
  console.log(req.user);
  return { prisma, user: req.user }; // Include prisma in the context
};
export type Context = Awaited<ReturnType<typeof createContext>>;
**
// Export type definition of API (e.g: Awaited<RouterOutput['query]>)
export type AppRouter = typeof appRouter;
export type RouterOutput = inferRouterOutputs<typeof appRouter>;
export default appRouter;

// Initialize express app
const app = express();

app.use(
  cors({
    origin: 'http://localhost:8080',
    credentials: true,
  })
);

// Configure redis client
const redisClient = redis.createClient({
  url: 'redis://localhost:6379',
});

// Connect to Redis
redisClient.connect().catch(console.error);

// Initialize RedisStore (after redisClient is declared)
app.use(
  session({
    store: new RedisStore({
      client: redisClient,
    }),
    secret: process.env.SESSION_SECRET!,
    saveUninitialized: false,
    resave: false,
    cookie: {
      maxAge: 1000 * 60 * 60 * 12, // 12 hours
    },
  })
);

// Initialize passport middleware
app.use(passport.initialize());
app.use(passport.session());

// Initialize tRPC middleware
app.use(
  '/trpc',
  trpcExpress.createExpressMiddleware({
    router: appRouter,
    createContext,
  })
);

// Set up authentication routes
app.use(routes);

// Start the server
const PORT = 3000;
app.listen(PORT, () => {
  console.log('API running on: ' + process.env.SERVER_URL);
});

The console.log(ctx.user) here, returns undefined:

import z from 'zod';
import { defineProcedure } from '../../trpc.ts';

export const loggedInAccount = defineProcedure
  .input(
    z.object({
      oAuthID: z.string(),
    })
  )
  .query(async ({ ctx, input }) => {
    console.log('CTX USER: ' + ctx.user);
    return ctx.prisma.user.findUnique({
      where: {
        oAuthID: input.oAuthID,
      },
      select: {
        id: true,
        email: true,
        firstname: true,
        lastname: true,
        username: true,
        profilePic: true,
      },
    });
  });

If you need any more details about my project // setup, feel free to ask! thx :)

Upvotes: 0

Views: 25

Answers (0)

Related Questions